"""
File_manager.py  —  Dual-Panel File Manager with FTP support

ALLT I PROGRAMMET SKA ALLTID VARA PÅ ENGELSKA - ALDRIG SVENSKA!
(EVERYTHING IN THIS PROGRAM MUST ALWAYS BE IN ENGLISH - NEVER SWEDISH!)

Settings / data:  Helpfiles/redigerare/
Log files:        Helpfiles/0---Empty/
Icon:             Icons/File_manager.ico   (external file, not embedded)

Section index (search for "DEL " to jump):
    DEL 01  Imports, paths, constants, help text
    DEL 02  Helpers
    DEL 03  Built-in PDF / image / text / audio viewer
    DEL 04  Copy / move engine + task queue
    DEL 05  Queue window
    DEL 06  EditorFrame (main frame, toolbar, keys)
    DEL 07  Search window
    DEL 08  File panel (local)
    DEL 09  FTP client
    DEL 10  Icon helper
    DEL 11  Network utilities + window
    DEL 20  Archive engine (ZIP/RAR/7z/TAR/GZ/ISO/CAB)
    DEL 21  Multi-Rename tool
    DEL 22  File compare (diff / binary)
    DEL 23  Directory synchronize
    DEL 24  Duplicate finder
    DEL 25  Quick View panel
    DEL 26  Branch view helper
    DEL 27  Checksums (CRC32 / MD5 / SHA)
    DEL 28  Split / combine files
    DEL 29  Directory hotlist
    DEL 30  Directory print / export (TXT / CSV / HTML / PDF)
    DEL 31  Command bar + command library
    DEL 32  Folder auto-refresh watcher
    DEL 33  Keyboard shortcut configuration
    DEL 34  Tools menu wiring
    DEL 46  Network location chooser (ready-made lists + scanning)
    DEL 47  Portable devices (phones / cameras — MTP, no drive letter)
    DEL 48  "Which one is newest?" — the ⚖ left/right comparison
    DEL 49  Delete-when-unlocked (a file another program holds open)
    DEL 50  Relocator (⤴ tidy files away by rule)
    DEL 51  "Go to:" path box (Workspace bar, far right → the right panel)
    DEL 52  Connect to a PC / Share this PC (connection file, one hidden account)
    DEL 90  Entry point

# ══════════════════════════════════════════════════════════════════════════
# ToDo
# ══════════════════════════════════════════════════════════════════════════
#
# DONE (2026-11-29 revision CP — "det får inte låsa sig när det packar (upp)"):
#   [x] FIXED: unpacking could freeze the whole file manager.  Three causes:
#       the before-snapshot of the target folder (os.walk) ran on the window
#       thread; every archive member posted a progress message and each one
#       repainted the Task Queue window; and 7z archives were extracted by
#       py7zr INSIDE the program, holding the interpreter lock.
#   [x] Unpack is now the LOWEST priority job: it steps aside (short sleeps
#       between members) while there is mouse/keyboard input in the last
#       second, takes everything when you are idle.  7z/ISO/CAB run through
#       7z.exe at IDLE priority (cancel works while it runs); progress is
#       posted ~4 times a second and the queue draws only the newest one.
#   [x] NEW: Task Queue toolbar tick "Close when empty" (default ON, saved as
#       queue_autoclose): the window hides itself when the list goes from
#       having jobs to EMPTY (everything done and cleared) — never while
#       anything runs or waits, and not a window you opened on an empty queue.
#       It keeps your saved ⚡ state for the next time it opens.
#
# DONE (2026-11-22 revision CO — "det vore bra om det kunde skötas via Webdock-servern"):
#
#   [x] NEW DEL 52b, NET ▾ → "🌐 Server for connection files …": the connection file goes
#       through YOUR server, encrypted here with a secret that never leaves the PCs.
#       "Share this PC" uploads it by itself; every File manager fetches new/changed files
#       at start and signs in (no USB).  Setting = ONE file, Helpfiles/redigerare/pc_relay.json
#       {url, key, secret}, or paste/copy a code (ISSUSYNC1:) in that window.
#   [x] The relay + installer are in 0---Claude_work_dir\PcConnectRelay (WebdockTool job
#       "PC connect relay", port 8108).  Tested against a local relay process only.
#   [x] Mapped network drives are named with their computer in the drive menus:
#       "Z:  FILM-Good" instead of "Z:  Good" (_net_drive_caption).  File manager's own
#       lists only - Explorer still shows the volume name.
#
# DONE (2026-11-22 revision CN — "kan det bli en del av File manager ... i stället
#                               för bat, 2 json och en py?  Json i en helpfiles-katalog"):
#
#   [x] File_manager.py is now the ONLY file: PC_Drives.bat/.ps1, PC_Drives_settings.json,
#       Share_This_PC.py and the loose PC_connect.json are no longer needed.
#   [x] NEW  File_manager.py --share   opens ONLY the "Share this PC's drives" window (for
#       FILM: copy this one .py there, run it with that switch; Python is enough).
#   [x] A connection file lying next to File_manager.py (where PC_connect.json used to be)
#       is imported at the next start and copied into Helpfiles/redigerare.  The original
#       name is now remembered too (before, PC_connect.json was redone at EVERY start).
#   [x] Drives already mapped to a share of that PC (by hand or by the old .bat) keep their
#       letter instead of getting a new one.
#
# DONE (2026-11-21 revision CM — "kan du lägga in detta i File manager... både
#                               att man kan dela ut och komma in"):
#
#   [x] CAUSE of the endless sign-in trouble: the PC (FILM) wanted a real Windows
#       account nobody had, and a reinstalled Windows 11 blocks guest access.
#   [x] NEW DEL 52, NET ▾ and Tools: "📤 Share this PC's drives …" (SHARE OUT: one
#       hidden account + Drive_<letter> shares + firewall/services, ONE Administrator
#       question, writes Helpfiles/redigerare/Share_out/PC_connect.json) and
#       "🔌 Connect to a PC (connection file) …" (GET IN: sign-in into Windows +
#       net_logins.json, favourites with letters, connected at once).  A
#       PC_connect*.json dropped into Helpfiles/redigerare is imported by itself at
#       the next start; saved drives of such PCs reconnect at every start.
#   [x] "Connection file…" button in the Network locations window.
#   [x] FIXED: _net_connect_favorite and _net_run_sys started `net` by bare name
#       and left stdin open, so a favourite without a sign-in hung on a hidden
#       "user name:" prompt.  Now full path + stdin closed + 45 s.
# ToDo: no "Revoke sharing" button yet (remove the account + the Drive_ shares).
#
# DONE (2026-11-07 revision CL — "lägg då in något så att jag kan flytta grejer
#                               i bus lane till vanlig kö"):
#   [x] REPORTED: a 874 MB folder was running, a 68 MB and a 4 MB job were
#       queued behind it; the 4 MB one said "⏳ after #8" and never got going.
#       (That wait is the SAME-FILE rule, not the lane: a job may not overtake
#       an EARLIER job that touches the same path or a folder holding it.)
#   [x] NEW: any job that has not started can be moved OUT of the fast/bus lane
#       into the normal queue.  Before, 🚌 "Out of lane" only worked on jobs
#       that had been sent down the lane by hand; a job the size rule had put
#       in the ⚡ lane could not be moved at all.  Now:
#         · 🚌 on a ⚡ or 🚌 job = "Out of lane" -> task.main_only = True, so the
#           job stays in the MAIN queue whatever its size (shown as 🛣);
#         · right-click 🚌 empties the whole lane the same way;
#         · right-click a row > "Let the program choose the lane again" undoes it;
#         · main_only is saved in task_queue.json and comes back after a restart.
#   [x] REAL CAUSE of "KvarnPC.py (212 KB) is after #10" (live queue file showed
#       it): job #10 copied the folders Kvarn + Ringar (381 MB, main lane, NOT a
#       bus lane) and the .py lives inside Kvarn.  The same-file rule treated two
#       COPIES that merely READ the same source as a fight.  _tasks_clash() now
#       needs one side to CHANGE a path the other uses (write/write, write/read,
#       or a MOVE, which removes its source); read/read no longer waits.  Pack /
#       unpack keep the old strict rule.
#   [x] TWO SMALL LANES (asked for: "det kanske måste finnas 2 snabb lanes... en
#       som enbart kan väljas manuellt"):  ⚡ = the AUTOMATIC lane (size rule,
#       single-file instant moves) and 🚌 = the MANUAL one (only jobs you send
#       there with 🚌).  Each has its OWN worker, current job, clock and
#       progress numbers (_run_fast_loop / _run_bus_loop, _fprog_* / _bprog_*),
#       so a 35 GB job in the bus lane never holds up the 18 KB files in the ⚡
#       lane, and the main job stands aside for either one by the same rules.
#       The strip shows the 🚌 job (the slow one) and names the ⚡ job running
#       beside it.  ✖ on the strip stops the job it shows.
#   [x] A job that is already RUNNING in the lane cannot be moved (it is moving
#       bytes) — ✖ Cancel, then ↺ Resume it into the main queue.
#   [x] ROOT CAUSE of "the 1 GB folder takes the bus lane slot" (2026-11-07, same
#       thing with the 874 MB one): a same-drive MOVE counted as "instant" and so
#       went in the ONE-worker fast lane whatever its size — but a FOLDER is moved
#       file by file, not renamed, so it ran for as long as it had files and every
#       small job queued behind it.  QueueTask.is_instant() is now True only for
#       plain files; a folder goes by its size (over the limit = main queue).
# ToDo: "⏳ after #n" could name the shared path in the row's tooltip.
#
# DONE (2026-11-03 revision CK — "Network hittar datorn (192.168.50.47) men inte
#                               hårddiskarna" after a Windows reinstall):
#
#   [x] CAUSE: the computer answers (ports 445/139 open) but only offers guest
#       access; Windows 11 blocks that (error 1272) and `net view` says "53 not
#       found".  The old Windows had the sign-in stored; the reinstall lost it.
#   [x] A computer that answers but needs a sign-in is now SAID to be so (was
#       "not found"), and Network locations shows a "🔑 Sign in to <host>" row
#       (double-click) -> NetSignInDialog.  Find drives on host fills in the saved
#       user/password and also remembers a typed one.
#   [x] The sign-in is saved in Windows (cmdkey) AND in Helpfiles\redigerare\
#       net_logins.json; it is put back into Windows at start-up, before listing
#       shares, and before connecting a favourite - so it is found again if
#       Windows forgets it.  (Password only base64-obscured, like favourites.)
#
# DONE (2026-10-20 revision CJ — "SFV saknas fast det finns en, kan inte Force?"
#                               + "Transfer has been PAUSED: grå text på vit
#                               bakgrund" + "Unexpected crash"):
#
#   [x] FIXED the crash: _ask_close_while_busy built tk.Frame(..., pady=(0, 12));
#       a widget's pady must be one number (tuples are for pack/grid) ->
#       TclError "bad screen distance", the dialog was left half built (that was
#       the unreadable grey-on-white box) and the close did nothing.  Now the
#       padding is in pack(), and the dialog has the dark background (C_BG).
#   [x] FIXED: a folder with several releases: every .sfv counted, so another
#       release's missing file kept this archive waiting.  Only the .sfv that
#       lists THIS archive counts now; quoted names are understood; an empty
#       file whose CRC is 00000000 is not "missing".
#   [x] CLEARER wait text: "3 of 12 files listed in X.sfv are not here: a, b, c"
#       (it used to read as if the .sfv itself were missing).  Right-click >
#       "Show what is missing" lists them ALL (_sfv_check, _on_show_missing).
#   [x] NEW: right-click a waiting unpack job in the Task Queue -> "Unpack
#       anyway" (QueueTask.force_unpack, TaskQueueManager.force_unpack_tasks).
#       Also rescues a job that already gave up waiting.
#
# DONE (2026-10-20 revision CI — "7-zip: restart behövdes" + "konstant uppdatering
#                               längst ned i File manager"):
#
#   [x] FIXED: 7-Zip installed (or 7z.exe dropped into Helpfiles/redigerare)
#       while the program ran was ignored until a restart: sevenzip_path()
#       remembered "not found".  Now only a FOUND path is remembered.
#   [x] NEW: when 7-Zip is missing and Helpfiles/0---Ninite/7-zip.exe (the
#       Ninite installer, always the latest 7-Zip) exists, the error box asks
#       to run it (_archive_error_box, SevenZipMissing), then watches every 2 s
#       (up to 15 min) and says when 7-Zip is installed.  No restart.
#   [x] CHANGED: the live job line in the main status bar (file, %, speed) is
#       now OPT-IN, setting "queue_in_statusbar" (default OFF), Settings >
#       General > Display.  The Task Queue window (⚡) shows the same in detail.
#
# DONE (2026-10-11 revision CH — "ingen scrollbar där jag 'run all in order'-klickar"):
#
#   [x] FIXED: the "Relocator — running" window (RelocatorRunWindow) was exactly as
#       tall as its rule list and could not be resized up or down, so with many
#       rules it ran off the bottom of the desktop and nothing could be scrolled.
#       The rules now sit in a scrolling list (scrollbar + mouse wheel), the
#       window is capped to what the desktop can show and can be dragged taller or
#       shorter, and the rule that is running is scrolled into view.  The status
#       line and Close / Stop buttons stay put under the list.
#
# DONE (2026-10-11 revision CG — "Lägg in så att det automatiskt exkluderar den
#                               katalog som man relocate:ar till... så att det
#                               inte blir en mega-loop"):
#
#   [x] NEW: a Relocator rule never walks into its own destination folder (nor,
#       for a "newer" rule, the folder replaced copies are retired to).  That
#       folder is pruned from the walk automatically, whatever the exclude list
#       says; an entry there is still honoured but no longer needed.  A source
#       that itself sits inside the destination behaves as before ("already at
#       the destination").
#   [x] CHANGED: the rule editor no longer refuses a destination that sits inside
#       a source with "Look in sub-folders too" ticked — that was the loop guard,
#       and the scan now is.  "The destination is also a source" still refuses.
#
# DONE (2026-10-11 revision CF — "Jag kan inte F3 filer inuti Zip. När jag kopierar
#                               filer från zip, så bara de skriver över utan att
#                               göra backup."):
#
#   [x] FIXED: F3 (and F4 / Shift+F4 / Ctrl+F4) did nothing on a file shown INSIDE
#       an archive panel.  _resolve_selected_local() joined the folder the zip sits
#       in with the inner name - a path that does not exist - and quietly gave up.
#       It now extracts the cursor / marked file to a temp folder first (same as
#       double-click already did) and hands THAT path on, so the built-in viewer
#       (or your F3 program) opens it.  Folders inside the zip are ignored.
#   [x] FIXED: F5 / F6 out of an archive panel extracted straight into the other
#       panel's folder and overwrote same-named files with no question and no
#       backup (archive_extract_members just writes).  It now extracts into a
#       hidden staging folder INSIDE the destination (.fm-from-archive-...) and
#       queues a normal MOVE from there into the destination, so it gets the
#       whole ordinary clash machinery: the red bar / dialog / queue banner,
#       "Backup-rename old", Overwrite older, Skip, the conflict rules.
#       F6 (move out of the zip) removes from the archive ONLY what actually
#       landed: a file that was skipped, or a job that failed or was cancelled,
#       stays in the zip.  The staging folder is deleted when the job finishes
#       (QueueTask.on_finished, called by TaskQueueManager._execute).
#       Known edge: a job removed from the queue before it ran, or one still
#       queued when the program closes, leaves its .fm-from-archive-* folder behind.
#
# DONE (2026-10-10 revision CE — "File manager... har blivit väldigt känsligt.
#                               Ibland räcker det att jag klickar på en fil, en
#                               (ganska) kort gång... så blir det redigeringsläge"):
#
#   [x] FIXED: the slow-click rename (click an already-selected row, wait
#       650 ms, edit box opens) was armed far too easily.  "Already selected"
#       is also true for the plain keyboard cursor - the first row of a freshly
#       opened folder, the row a refresh restored, the grey cursor row of the
#       panel you just clicked into - so ONE ordinary click on such a row opened
#       edit mode (revCD's click-activates-panel change made it show up more).
#       Now the rename is armed only when (a) the panel was already active when
#       the button went down, (b) the same row got a plain mouse click 0-2.5 s
#       earlier (FilePanel._last_plain_click, SLOW_CLICK_MAX_GAP_S),
#       and when the timer fires (_fire_slow_rename) (c) the pointer is still on
#       that row and (d) it is still the only selected row.  F2 / Shift+F2 / Tab
#       are unchanged.
#
# DONE (2026-10-10 revision CD — "om jag klickar i andra fönstret så blir det
#                               ofta att jag inte hamnar där jag klickar...
#                               kanske att det ligger kvar tangentbordsmarkering
#                               från tidigare, som 'overrule'. Det är irriterande"):
#
#   [x] FIXED: clicking a row in the INACTIVE panel could land the cursor on
#       the old (grey) keyboard row instead of the row under the mouse.  The
#       cursor log shows the order of events: ttk selects the clicked row,
#       then the tree's <FocusIn> runs _activate_side -> _promote_panel, which
#       put back the grey keyboard row (selection_set(*restore)) AND scrolled
#       it into view with tree.see().  Only a later after_idle "pin" in
#       _on_single_click put the clicked row back - sometimes 0.7-0.9 s later
#       when the UI was busy, and by then the list had already scrolled, so a
#       double-click / drag / F5 hit the wrong row.
#       Now _on_single_click records the clicked row (panel._click_target) and,
#       for a plain click on the inactive side, activates that panel at once;
#       _promote_panel gives the clicked row priority over the remembered grey
#       row and does not scroll.  Ctrl/Shift clicks are left alone.  The old
#       after_idle pin stays as a safety net and now also re-activates the
#       panel if the focus ended up on the other side.
#
# DONE (2026-10-09 revision CC — "lägg in i settings att man kan visa
#                               versionsnumret, som kommer uppe till vänster,
#                               direkt efter File manager. Nu visas det och
#                               default så ska det inte visas men kunna visas"):
#
#   [x] The title bar used to read "File Manager    ·    build <time>" always.
#       New setting "show_build_in_title" (default OFF): Settings > General >
#       Display, "Show the version (build time) in the title bar".  Off = the
#       title is just "File Manager".  Applied the moment Save is pressed
#       (EditorFrame._apply_window_title) and at start.  About still shows it.
#
# DONE (2026-10-08 revision CB — "Relocator, skönt om den kunde autostängas
#                               efter klar"):
#
#   [x] The Relocator's "Run all" window (RelocatorRunWindow) now closes ITSELF
#       a couple of seconds after the last rule has finished — but only when
#       the run was clean.  A run that was stopped with ⏹, or where a rule
#       failed / was cancelled / queued nothing, stays open so the ⚠ is seen.
#       New tick-box "Close this window when done" at the bottom of that
#       window, setting "relocator_autoclose" (default ON).  Untick it during
#       the run and the window stays after all.
#
# DONE (2026-10-02 revision CA — "Kan inte kopiera in filer i zip/rar? De hamnar
#                               utanför, även om jag öppnar zip så att det blir
#                               ena fönstret"):
#
#   [x] COPY / MOVE INTO AN ARCHIVE.  Browsing INTO a zip worked, copying OUT
#       of it worked, but nothing handled the other direction: F5 / F6 took
#       the other panel's current_path as the target, and for a panel standing
#       inside an archive that is the folder the archive sits in — so the
#       files landed beside the zip, exactly as reported.  Now, when the
#       receiving panel is inside an archive, the files are written INTO the
#       archive, at the folder you are standing in:
#         · F5 / F6, drag & drop from the other panel or Explorer, and Ctrl+V
#           (copy or cut in Explorer) all go through  _add_to_archive;
#         · writable formats = PACK_FORMATS (zip / 7z / tar / tar.gz / .bz2 /
#           .xz).  RAR / ISO / CAB cannot be written (7-Zip cannot make RAR),
#           so they now SAY so and copy nothing — instead of dropping the
#           files outside as before;
#         · a name already in the archive asks once: Yes = replace, No = skip
#           those, Cancel = add nothing.  A move only trashes the originals
#           that went in whole (they go to the ~deleted~ trash, Ctrl+Z works);
#         · zip without a clash = copy of the archive + append (nothing
#           recompressed); zip with a clash = rebuilt member by member;
#           7z / tar = extract, lay over, re-create.  The archive is swapped in
#           only when the new one is complete, so Cancel / a crash leaves the
#           original as it was;
#         · both panels inside archives, or FTP as the source, say "copy out
#           first" rather than guessing.
#   [x] archive_delete_members (Delete / F6 out of an archive) built its new
#       file in %TEMP% and swapped it in with os.replace — which fails across
#       drives.  An archive on another drive than the temp folder could not
#       be rewritten.  Both now use _replace_file (os.replace, else move).
#   Not done: Shift+F5 / Shift+F6 (Copy As) still takes a typed path and does
#   not know about archives.
#
# DONE (2026-09-30 revision BZ — "Relocator... går den i samma Task queue?
#                               Det är ju dumt för relocator är alltid
#                               sekund-jobb så stönigt om det ska ligga och
#                               vänta i några minuter.  Det behöver en 'egen
#                               fil', som görs oavsett task queue-aktiviteter"):
#
#   [x] THE RELOCATOR HAS A LANE OF ITS OWN.  It did go through the ordinary
#       Task Queue: a rule's files were queued like any copy, so a small job
#       slipped through the fast lane but a rule that moved something bigger
#       than the fast-lane limit (a fresh .exe build, say) sat behind whatever
#       big transfer was running — and stood still for Pause and for 🚌 only
#       as well.  Rule jobs are now marked  QueueTask.reloc  and are run by a
#       THIRD worker (_run_reloc_loop), beside the big lane and the fast lane:
#         · it does not wait for the big job, the fast lane, Pause or 🚌;
#         · the big job does not yield to it either (they share the disk, as
#           with a hand-picked 🚌 job) — only the fast lane makes it yield;
#         · a rule's jobs run one after another inside their own lane, and
#           the "Run all" chain still waits for each to finish before the next
#           rule, because it watches the job's status, which is lane-blind;
#         · a clash on the destination still parks the job and is answered in
#           the same bar / window as before; answering wakes THIS lane too
#           (_start_fast_worker now wakes it, and so does release_preflight);
#         · ✖ Cancel on the big bar does not touch it (per-task cancel); a
#           program CLOSE does, through shutdown_stop, exactly like the other
#           lane — a half-written file is deleted, never left under its name;
#         · it posts no progress to either strip (two bars are enough) — the
#           ⤴ "Relocator — running" window and the queue row say where it is;
#         · the lane survives a saved / restored queue ("reloc" in the state
#           record).
#       Nothing else changed: the rules, their scan and the retire-then-copy
#       step behave exactly as before.
#
# DONE (2026-09-27 revision BY — "jag testade igen… ESC kan stänga task queue
#                               men det är fortfarande 1 ANSWER + grejen i
#                               botten.  Jag måste klicka PÅ Skip-knappen"):
#
#   [x] THE THIRD PLACE, AND THE ONLY ONE THAT ACTUALLY ASKS.  BV bound Esc on
#       the per-file dialog, BX bound it on the pre-flight window — and neither
#       is what comes up by default.  The default way of asking is
#       "conflict_alert_mode = bar": the red CLASH BAR at the bottom of the
#       main window, with the ⚡ button showing "⚠1 ANSWER".  Esc there was
#       _cbar_release_keys — "give the keyboard back to the file list" — so it
#       looked like Esc did nothing, and if the keyboard happened to be in the
#       Task Queue, Esc closed that window and left the question standing.
#   [x] While a name clash is waiting, Esc now answers SKIP in all three
#       places it can be pressed:
#         · on the bar's own buttons (was: hand the keys back — ↑/↓ still do
#           that, and always did),
#         · anywhere else in the main window, through a binding on the
#           TOPLEVEL that lives exactly as long as the bar does
#           (_cbar_escape_skip, installed and removed by _cbar_bind_keys),
#         · in the Task Queue window, which answers the clash instead of
#           closing — and still closes when nothing is waiting.
#   [x] It stands back for a text box.  In an inline rename or the command bar
#       Esc still means "cancel what I am typing": the handler returns None
#       rather than "break" there, so the box's own binding decides.
#   [x] The bar's hint line says what is true now: "←/→ pick · Enter = do it ·
#       Esc = Skip · ↑/↓ back to the list · Ctrl+Alt+1…5".
#
# DONE (2026-09-27 revision BX — "jag är där med File already exist, och klickar
#                               ESC, men det blir inte SKIP.  Dessutom… om fil
#                               är nyare på en sida men storlek är identisk…
#                               i stället för grön, så kanske blå (för nu kan
#                               det bara vara att jag kopierat till två
#                               kataloger och den ena blev sekunden yngre…
#                               och verkar som att den är nyare).  Which one
#                               is newest-knappen.  Den kan vara ofärgad när
#                               den är aktiv.  Den kan vara röd när den är
#                               icke-aktiv.  Nytt läge: Den kan vara orange,
#                               grön eller blå, när den även kollar filer som
#                               finns på ena sidan men inte på andra"):
#
#   [x] ESC WAS ALREADY SKIP — ON THE WRONG WINDOW.  Revision BV bound it on
#       _ConflictDlg, the per-file "File already exists" dialog, and that does
#       work (Escape there answers Skip, checked against the real window).  But
#       the window a copy with clashes actually opens FIRST is the PRE-FLIGHT
#       check — "N file(s) already exist at destination:" — and Escape there
#       was still _setup_toplevel's plain close, i.e. cancel the whole job.
#       Escape on the pre-flight window now means "Skip all": skip the files
#       that clash, copy the rest.  If there is no room for that mode, or
#       nothing clashes at all, Escape keeps its old meaning rather than
#       promising something it cannot do.
#
#   GREEN NO LONGER MEANS "EQUAL SIZE".  It means "the same file".
#   [x] A file copied into two folders can land a moment apart, and the program
#       then called one of them newer — which is what sent him looking for a
#       change nobody had made.  Same size + different moment is now its own
#       state, BLUE, everywhere two copies are compared:
#         · the pre-flight conflict list (was green "equal", now blue
#           "same size"),
#         · the per-file dialog's Size row (was green "✓ equal", now blue
#           "= same size, different moment"),
#         · the ⚖ side comparison (was GREEN newer / RED older, now blue on
#           both sides — neither copy is called the newer one).
#   [x] Green is kept for same size AND same moment, amber for same moment but
#       different size.  "The same moment" is one number now, SAME_MOMENT_S =
#       2 s (FAT resolution), shared by the dialogs and DEL 48 instead of each
#       having its own idea.
#   [x] _conflict_entry also carries the RAW mtimes.  The displayed ones stop
#       at the minute, so two files three seconds apart looked identical in the
#       list — exactly the case the colour has to be able to tell apart.
#   [x] The pre-flight list's "smaller" rows moved from light blue to orange so
#       blue means one thing only, and the four colours are now spelled out in
#       a legend under the list rather than left to be guessed at.
#
#   THE ⚖ BUTTON HAS THREE STATES, AND SAYS WHICH ONE IT IS IN.
#   [x] off → comparing → comparing + one-sided files → off.
#   [x] RED "⚖" while off, plain "⚖▪" while comparing, BLUE "⚖◆" while it also
#       flags one-sided files.  The colour is a ttk style; the character is
#       there as well because a Windows theme is allowed to ignore a tint on a
#       ttk button, and the state must be readable either way.
#   [x] The new third state marks, in VIOLET, every file that is in one panel
#       and not in the other — which is half of what you are asking when you
#       put two folders side by side, and was the one thing the comparison
#       deliberately left out.  Folders are still skipped: a folder's own
#       timestamp says nothing about what is inside it.
#   [x] Remembered between sessions like the old toggle
#       (compare_sides_singles), so the state you leave it in is the state you
#       come back to.
#
# DONE (2026-09-27 revision BW — "Om jag är i workspace Python, med kanske tab
#                               Left3 + Right2 och byter till workspace Cubase
#                               (default L1 + R1) och sedan tillbaka till
#                               Python… så är det inte L3 + R2, utan L1 + R1.
#                               Det får vara programstart-default, men inte
#                               default'a när jag bara byter mellan
#                               workspaces"):
#
#   [x] _ws_load set the active tab to index 0 on both panels every single
#       time, so every Workspace opened on its first tab however you got
#       there.  Switching away and back therefore threw away the only thing
#       you were actually in the middle of.
#   [x] Where each Workspace was standing is now remembered per session, per
#       side — _ws_spot[(name, side)] = (tab index, that tab's folder) — noted
#       on the way OUT of a Workspace (both panels, since the other one may be
#       the one you switch back to next) and used on the way back in.
#   [x] The FOLDER outranks the number.  If the strip has changed since you
#       left (an extra tab opened or closed, or you loaded base tabs only) you
#       still come back to the folder you were in; only if that folder is gone
#       does the old index decide, clamped, and tab 1 is the last resort.
#   [x] SESSION ONLY, on purpose.  Nothing is remembered at program start, so
#       the ★ start-up Workspace still opens on its first tabs — which is
#       exactly the line drawn: start-up default yes, defaulting on every
#       switch no.
#
# DONE (2026-09-27 revision BV — "När det kommer upp File exist, så ESC = Skip.
#                               Portable devices… när det kommer upp
#                               'existerar, vill du….' så spelar det ingen
#                               roll att jag klickar i checkbox - det frågas
#                               varje gång (redan nästa fil, i kön).  Snabbt
#                               att kopiera till telefonen… superslött att
#                               hämta från den.  Den står på 0/31 hela tiden,
#                               trots alla popups och, jag tror, att filer
#                               flyttades."):
#
#   [x] ESC ON THE "File already exists" DIALOG NOW MEANS SKIP.  It used to
#       run _setup_toplevel's plain Escape-closes binding, which left the
#       answer on its CANCEL default — so the one key you reach for to wave a
#       single file away stopped the whole job instead.  Escape now does
#       exactly what the Skip button does, and obeys the "apply to all" tick
#       the same way.  X and the Cancel button still stop everything.
#   [x] "Apply to all remaining conflicts" now covers RENAME NEW as well.
#       Overwrite, Skip and Backup-rename-old already carried to the rest of
#       the files; Rename new had no all-variant at all, so ticking the box and
#       picking it asked again on the very next file — the same complaint, on
#       the ordinary copy path (new AUTO_RENAME_ALL).
#
#   FETCHING FROM A PHONE — the checkbox that changed nothing, and the 0/31.
#   Sending TO a device was fixed on 2026-09-23 (one clash question up front);
#   fetching FROM one still had the identical hole on the other side of the
#   cable, and it is the whole of what was reported:
#
#   [x] The 16 handed to CopyHere is FOF_NOCONFIRMATION, "overwrite, do not
#       ask".  With a portable device in the job the shell ignores it and pops
#       its own Replace-or-Skip window, ONE PER FILE.  Its "do this for all
#       current items" tick covers only the single item that CopyHere call was
#       given — which is exactly why ticking it changed nothing and the next
#       file asked again.
#   [x] That window also BLOCKS the CopyHere call that raised it, so the loop
#       never reached file 2, no probe was ever armed, and the status line sat
#       on "0/31" for the whole batch however many windows were answered.  Same
#       reason it was "superslött": every file waited for a human, one at a
#       time, while sending to the device did not.
#   [x] So _mtp_transfer_out now settles the clash ONCE, before the shell is
#       handed anything — the same single Yes/No/Cancel that sending already
#       uses (_mtp_clash_asker grew a *place* argument so the question reads
#       correctly in both directions).  Yes moves each clashing file aside, No
#       fetches only the new ones, Cancel fetches nothing.
#   [x] OVERWRITE DOES NOT DELETE FIRST.  The old file is renamed to a
#       .fm-old name in the same folder and only dropped once its replacement
#       has actually landed; if the transfer stalls or the cable goes, it is
#       put straight back.  The tidy-up is a finally, so even an error return
#       half way through a batch cannot leave a file parked under .fm-old.
#   [x] The counter counts again: with no clash left to block the pipe the
#       probes arm, files land, and the total is the number of files really
#       being fetched (skipped ones are not counted in it).
#   [x] mtp_copy_out / mtp_move_out take on_clash; copy_to_panel and
#       move_to_panel pass it.  Sending to the device is untouched.
#   [x] _do_single_copy_move is NOT called by anything any more (every copy
#       goes through the queue).  It only understands four of the dialog's
#       answers and would overwrite on the rest, so it now says so at the top
#       rather than waiting to be wired back up by someone in a hurry.
#
# DONE (2026-09-14 revision BU — "Om en av mina tabbar står i en katalog, som
#                               jag raderar från annan tab/profil, så ser det
#                               ut som att den tabben… hamnar i user-katalog.
#                               Om det är så, så ska det inte vara så.  Alla
#                               påverkade tabbar ska gå upp ett steg, så länge
#                               som det krävs, till dess att de når en
#                               icke-raderad katalog"):
#
#   It was so.  FilePanel.refresh() ended in a bare `except` that jumped
#   straight to os.path.expanduser("~") whatever had gone wrong — so deleting
#   the folder a tab was standing in did not move the tab one step, it threw it
#   right across the disk into the user folder, and whatever you were working
#   on was simply gone from the strip.
#
#   [x] _nearest_existing_dir() — walk UP, one level at a time, until a folder
#       that still exists is reached.  That is where you would have gone
#       yourself.  The root of the drive is the last stop; the user folder is
#       now only reached when the whole DRIVE has gone (a USB disk pulled out),
#       which is the one case where there is nothing above to walk to.
#   [x] ALL affected tabs, not just the one you are looking at.  A delete
#       sweeps both panels' whole tab strips: any tab standing in the folder
#       that went — or anywhere under it — comes up to the nearest surviving
#       folder, the strip redraws and the status line says where it landed.
#       Finding out only when you click a tab three along is finding out too
#       late.
#   [x] Switching to a tab whose folder went while it sat in the strip lands
#       one level up as well, quietly, instead of making the panel discover it
#       the hard way.
#   [x] The saved start path gets the same treatment: a Workspace made when a
#       folder existed now opens in that folder's PARENT, not in the user
#       folder.
#   [x] A folder that is THERE but cannot be READ is no longer treated as a
#       deleted one.  It used to fall into the user folder as well; now the
#       panel stays where it is and says why.  It must not be a message box:
#       the auto-refresh poll comes back every 1.5 seconds and would put one on
#       the screen every 1.5 seconds.
#   [x] Nothing here touches an FTP panel or a UNC server path — testing a
#       network path that is down can block for seconds, and a window that
#       stops answering is worse than a stale tab.
#
# DONE (2026-09-14 revision BT — "jag ser inte något sätt att pausa eller
#                               'ta bort från' bus lane… Jag har 73kb, 73 kb,
#                               178kb och 35 gb i bus lane, och task queue kör
#                               35-gb.  Även vanliga borde ha valt att köra in
#                               KB-överföringarna först.  Det ska vara
#                               automatiskt att göra sig av med mängden
#                               överföringar… minska dem, så fort som möjligt
#                               (i.f.a. det blir krasch så blir det mindre
#                               rörigt).  Remove i botten, är det remove from
#                               bus lane eller remove från task queue?"):
#
#   THE BUG, and it is one line.  auto_priority() returned a flat 0.0 for
#   EVERY job in the bus lane, so all four of his scored the same and Python's
#   stable sort left them in the order they had been queued in — 35 GB first.
#   The bus lane is a QUEUE with ONE worker, so the three tiny ones were not
#   "not started": they were stuck behind the 35 GB one, in the lane that is
#   supposed to be the fast way round.
#
#   [x] SHORTEST JOB FIRST, and now it means what it says.  The old heuristic
#       sorted by TYPE first (instant move 1.0, unpack 2.0, pack 3.0, cross-
#       drive move 4.0, copy 5.0) and used size only to break ties inside a
#       band, so a 4 GB unpack could still go before a 73 KB copy.  It is now
#       an estimate of how LONG the job takes — bytes × a per-byte weight for
#       the type (pack 2.0, unpack 1.5, cross-drive move 1.2, copy 1.0) — and
#       the smallest estimate goes first.  A same-drive move is still free
#       whatever its size: it is a rename, no bytes travel.
#       His four now run 73 KB, 73 KB, 178 KB, 35 GB.  The reason he asked for
#       it is the right one: the list gets SHORT fast, so a crash leaves less
#       mess behind.
#   [x] The bus lane is ordered the same way — it simply sorts before
#       everything else instead of on top of it.  Hand-picked still beats the
#       heuristic; inside the lane the small ones go first.
#   [x] NEW "🚌 paused" on the Task Queue toolbar.  Holds the bus lane still —
#       a job already running IN it stops at the next block boundary (nothing
#       half-written) and the MAIN lane carries straight on.  That is the
#       other half of "I hit 🚌 on the 35 GB one by mistake": you do not have
#       to throw its progress away to get it out of the way.  Not remembered
#       between sessions — a hold you have forgotten about must never be able
#       to stop work at the next start.
#   [x] RIGHT-CLICK the 🚌 button = empty the whole lane, every job that has
#       not started back into the normal queue.  One press to undo the
#       mis-click.
#   [x] The 🚌 button was ALWAYS a toggle, it just never said so — which is
#       why "jag ser inte något sätt att ta bort från bus lane".  It now reads
#       "🚌 Out of lane" when everything picked is already in it.
#   [x] "🗑 Remove" is now "🗑 Out of queue".  It never had anything to do with
#       the bus lane: it takes the job out of the LIST altogether.  Taking one
#       out of the lane is the 🚌 button, and both tooltips now say the other
#       one's name so neither can be mistaken for the other again.
#   [x] The status line at the top of the queue now has a ROW OF ITS OWN.  It
#       was packed on the right of the button row, and pack hands out space in
#       the order things are packed, so the last one in loses: measured, that
#       button row wants 785 px and the status label up to 325, in a window
#       820 wide.  The sentence saying what had just happened was being thrown
#       away — which is part of why the bus lane felt like it did nothing.
#       The window's minimum width went 660 → 800 for the same reason; 750 is
#       what the bottom button row needs to show every button, measured.
#   [x] Answer to "om det är flera saker i bus lane och huvudgrejen blir klar,
#       flyttas de över till huvud då?"  No — and nothing is stranded.  The
#       bus lane is a lane of its own with its own worker; it keeps running
#       its jobs one after another and the main lane simply has nothing left
#       to do.  They are not moved across on purpose: two streams onto one
#       disk is the worst case there is, and the whole queue exists to avoid
#       it.  The bus strip says how many are still in the lane.
#
# DONE (2026-09-14 revision BS — "det där med task queue som ibland är top,
#                               ibland tillfälligt, ibland aldrig, är stönigt.
#                               Nu är det 'on top' + top, i task queue.  Ändra
#                               så att det är i file manager i stället…
#                               task queue-ikonen (blixten)"):
#
#   The whole "is the queue in the way or is it buried?" question was spread
#   over THREE controls in two different windows — 📌 On top and ⏱ Top on the
#   Task Queue's own toolbar, plus a tick in Settings ▸ General — and none of
#   them told you at a glance which of them was winning.  All three are gone.
#   There is now ONE control, and it is the ⚡ button in the FILE MANAGER's
#   toolbar, where every other button already is:
#
#     LEFT-click cycles, and the bolt itself changes colour so the state is
#     readable without opening anything:
#
#       1  🟢 green    open — no priority at all.  An ordinary window: the
#                      file manager AND any other program may cover it.
#       2  🟠 orange   open — always above the FILE MANAGER, never above
#                      anything else.  Alt-Tab to a browser and the browser
#                      covers it, exactly as it should.
#       3  🔴 red      open — above EVERYTHING, for ever.  The aggressive
#                      one, so it is drawn in the aggressive colour.
#       4  ⚡ plain    closed.  Original button colour, nothing on screen.
#
#     RIGHT-click closes it from any state (same as stepping round to 4).
#
#   [x] State 2 is the one that did not exist before, and it is the one that
#       was actually wanted: "above the file manager" was previously done with
#       WS_EX_TOPMOST, which does not mean that at all — it means above the
#       whole desktop, so the queue sat on top of Claude, the browser and
#       everything else too.  State 2 gives the queue an OWNER window instead
#       (GWLP_HWNDPARENT → the file manager's frame).  Windows always draws an
#       owned window above its owner and nowhere else, which is the real
#       middle setting.  It is set with SetWindowLongPtrW rather than Tk's
#       `wm transient` on purpose: transient RECREATES the wrapper window, and
#       the queue's WS_EX_NOACTIVATE + WS_EX_TOOLWINDOW styles (the ones that
#       stop it ever owning the keyboard, and stop it appearing in the
#       taskbar) would be thrown away with it.
#   [x] The button never lies.  The colour comes from what is ON SCREEN, not
#       from the saved setting, so a remembered "red" cannot paint the button
#       red while nothing is open — and the first left-click after a start
#       therefore always gives you state 1, as described above.
#   [x] The queue's own toolbar now only REPORTS the state (🟢 / 🟠 / 🔴 with
#       a word), it no longer sets it.  Its ✖ / Escape still closes, and that
#       now returns the ⚡ button to its original colour, because closing IS
#       state 4.
#   [x] Something that opens the queue BY ITSELF never lowers a state you
#       chose: an unpack that shows the queue lifts it to at least 1, and a
#       job parked on a name clash to at least 2 — or 3 when Settings ▸
#       General ▸ "Bring the Task Queue window to the FRONT" is ticked.
#   [x] Migrated once, silently: the old "queue_always_on_top" tick becomes
#       state 3 if it was on and state 1 if it was off.  A fresh install
#       starts at state 2, the sensible middle.
#   [x] Removed with the old controls: _on_temp_top and its 250 ms foreground
#       poll, the <Button-1> watch it had to plant on the main window, and
#       _reassert_on_top (which had had no caller since revBF).
#
# DONE (2026-09-13 revision BR — "med defaulthub… jag vill att det i file manager
#                               visar ikonen för mina program i default hub.  Är
#                               det en jpg, så visa seeviews ikon.  Är det en
#                               pdf… visa pdfull-ikonen o.s.v..  Att File manager
#                               även hämtar fil-ikonen från programmen (eller har
#                               du smartare idé)?"):
#
#   Smarter idea: nothing is fetched FROM the programs, and nothing is started.
#   The two files that answer the question are both lying there already —
#
#       Helpfiles/DefaultHub/defaults.json    ".pdf  ->  PDFull"
#       Icons/PDFull.ico                      that program's own icon
#
#   — and the second is named after the answer the first one gives.  Asking a
#   program for its icon would mean importing it or launching it; reading the
#   .ico it already has costs one isfile() per PROGRAM (not per file) and works
#   for a program that is not even installed, not built, or currently broken.
#   It is also the same single table the double-click follows, so "PDFs open in
#   X instead of PDFull" stays ONE edit in ONE place and the picture follows the
#   launch by construction — they cannot drift apart.
#
#   Why this was needed at all: Windows' shell icon for these types is whatever
#   Adobe or nothing at all left in the registry, because his programs are not
#   registered as default apps — and they deliberately never will be, since
#   Windows identifies an application by .exe path and would show all 122 of
#   them as one app called "Python" with one icon.
#
#   See DEL 42b.  Everything falls THROUGH, never over: a kind DefaultHub marks
#   "system" keeps the Windows icon (that is an answer, not a gap), so does a
#   program with no .ico anywhere, so does a missing or half-written
#   defaults.json.  The column can never go blank because of this.
#   Toolbar "Icons" still turns the whole column off; two new switches in
#   Settings ▸ General:
#       [x] Show MY program's icon in front of a file DefaultHub gives it
#       [ ]    …except text & code  — DefaultHub has ONE "text" kind for
#              .py .json .txt .md .log .csv .xml, so with it off all of them
#              wear the editor's icon and stop telling themselves apart.
#   One os.stat per panel refresh re-reads DefaultHub's table, so a change made
#   over in DefaultHub lands on the next Ctrl+R instead of the next restart.
#   Icons are cached per extension, the .ico walk per program, and the 16-px
#   frame inside the .ico is preferred over shrinking the 256-px one.
#
# DONE (2026-09-12 revision BQ — "fixa det stöniga problemet som 'alltid' händer.
#                               Jag är i Foul_bridge, dubbelklickar '..', kommer
#                               upp en katalog, dubbelklickar och kommer TILLBAKA
#                               i Foul_bridge.  Det verkar som att '..' är
#                               markerat men programmet tycker att jag är på
#                               katalogen."):
#
#   His reading was exactly right, and the cursor log had it on tape — one real
#   click, then sixteen navigations with no click at all between them:
#       19:39:04.087 CLICK-pin  panel=left on '..'      ← the only click
#       19:39:04.295 CHDIR [go_up]            -> …/Foul_bridge
#       19:39:04.648 CHDIR [_on_double_click] -> …/Foul_bridge/csv
#       19:39:04.840 CHDIR [go_up]            -> …/Foul_bridge
#       19:39:05.264 CHDIR [_on_double_click] -> …/Foul_bridge/csv    (…7 s)
#
#   [x] THE CAUSE: _on_double_click acted on tree.selection() instead of on the
#       row under the mouse.  ttk selects the row you point at on the FIRST
#       press of a click train ONLY — the second press comes in as
#       <Double-ButtonPress-1>, and ttk::treeview::DoubleClick does not touch
#       the selection at all.  go_up() then moves the selection every single
#       time by design (it puts the cursor back on the folder you came OUT of),
#       so the next press activated THAT folder, not the ".." under the
#       pointer.  Up, straight back in, up, straight back in.
#   [x] THE FIX: a mouse double-click resolves its row with identify_row(),
#       and selects + focuses it before acting, so the row that is highlighted
#       and the row that opens are the same one.  Enter still uses the
#       selection — with a keyboard the selection IS the aim.
#   [x] identify_region() first: a double-click on a column heading, on a
#       separator or in the empty space below the last row now does nothing.
#       It used to open whatever was selected somewhere off screen.
#   [x] <Triple-1> and <Quadruple-1> are bound and swallowed.  Tk falls back to
#       the <Double-1> binding when they are unbound, so an impatient burst of
#       clicks was one activation PER PRESS — which is how a 7-second bounce
#       could run out of one double-click plus a couple of frustrated ones.
#   [x] Same "act on the pointer, not the selection" fix in the two FTP lists
#       (FTP panel + the transfer window's remote tree).
#
# DONE (2026-09-12 revision BP — "Det kraschade vid formats andra popup.  Kanske
#                               för att hårddisken är tom(?)"):
#
#   NOT the empty disk — an empty drive reads back as 0 folders, 0 files and is
#   handled.  It was mine, and it was a beginner's own goal:
#
#   [x] THE CRASH: the three new dialogs are tk.Toplevel subclasses, and each
#       one did `self._root = "D:\\"`.  `_root` IS TKINTER'S OWN METHOD on every
#       widget (Misc._root).  Overwriting it with a string means tkinter's event
#       dispatch — nametowidget() → `w = w._root()` — raises
#       "TypeError: 'str' object is not callable" on the FIRST event inside such
#       a window.  That is why it built and displayed and then died: the window
#       is fine until you touch it.  Renamed to self._vol (19 places).
#   [x] Found the same class of mistake one step from biting: _QueueStoreDlg had
#       `self._qname = tk.Entry(...)` as `self._name`, and `_name` is
#       BaseWidget's own attribute.  Renamed too, before it cost anything.
#   [x] A test now builds every one of these windows for real and calls the
#       exact thing that crashed (widget._root(), nametowidget()).  Against the
#       copy he ran it fails with his TypeError; against this one it passes.
#
# DONE (2026-09-12 revision BP(b) — "Vi kan ha visa (upp till) de 10 första
#                               katalogerna, på första popup.  Andra popup kan
#                               vara om bestämma vad det ska formateras till…
#                               och inget default… Där måste jag välja och då
#                               kan YES NO (eller snarare Continue och
#                               Abort/Cancel) finnas på vanliga platser"):
#   [x] His design, and it is better than mine.  The two windows are now
#       WHAT IS THERE and WHAT IT BECOMES, in that order:
#         Window 1 — the drive, and the first ten folders on it.  A letter says
#                    nothing; ten folder names say instantly which disk this is.
#                    Also says plainly when the drive is EMPTY, instead of
#                    printing nothing and looking broken.
#         Window 2 — the file system, with NOTHING PRESELECTED.
#   [x] THE GUARD IS NOW THE CHOICE ITSELF.  "Format now" stays disabled until a
#       file system is actually picked, so no amount of clicking through can
#       format a disk as something nobody chose.  That is a better protection
#       than moving the buttons about was, and it lets Continue / Abort / Cancel
#       sit where buttons normally sit.  The moving-buttons trick and the
#       two-second arming delay are both gone with it.
#   [x] Each choice explains ITSELF — what it is for and the limit that actually
#       bites:  NTFS (no size limit, permissions, journal — anything only
#       Windows touches) · exFAT (no size limit either, read and written
#       everywhere, but NO journal so eject it properly) · FAT32 (⚠ no single
#       file over 4 GB, and it fails mid-copy, not up front) · ReFS (specialist,
#       checksums, nothing boots from it).
#
# DONE (2026-09-12 revision BO — "kunna högerklicka på tab och välja att få se
#                               information om hårddisken… så mycket som
#                               möjligt.  Viktigast nu, är vilket format"):
#   [x] Right-click a tab ▸ "🖴  Disk information".  The FILE SYSTEM is in the
#       MENU LINE itself — "🖴 Disk information (D:  NTFS · Win 10 to go ·
#       111 GB)" — so the question that actually gets asked is answered before
#       anything is clicked.  In the window it is the biggest thing on it.
#   [x] Odd detail worth recording: _drive_kind_info has ALWAYS asked
#       GetVolumeInformationW for the file-system name, and has always thrown
#       it away.  The answer was one line from being available all along.
#   [x] Everything else it will say: volume label, serial, drive type, longest
#       filename, total/used/free with a bar, allocation unit, bytes per
#       sector, clusters total and free, and the capability flags (permissions,
#       journal, compression, hard links, sparse files, streams, quotas, and
#       READ-ONLY in amber when that is what it is).
#   [x] A note per file system, because the limit that bites is not obvious:
#       FAT32 refuses any single file over 4 GB, exFAT has no journal so a bad
#       unplug can cost the directory, NTFS has neither problem.
#   [x] The HARDWARE under the letter — model, serial, bus (his D: turns out to
#       be a JMicron USB SSD that Windows calls "Fixed"), SSD or spinning,
#       partition style MBR/GPT, offsets and sizes, health, BitLocker.  None of
#       that is reachable through the plain Win32 volume calls, so it goes via
#       PowerShell's storage cmdlets — which take seconds, so it arrives on a
#       THREAD and fills in when it lands.  The window is usable meanwhile.
#   [x] 📋 Copy all puts the lot on the clipboard (CF_UNICODETEXT, the real
#       one — Tk's dies with the process).
#   [x] AND IN THE STATUS BAR, permanently, because that is where he looked
#       for it: each side's section now ends "… 90,284 MB free of 476 GB  ·
#       NTFS".  The row has always had the space and has never said which
#       format; asking used to cost a right-click.  Cached per drive — the
#       status bar rebuilds every time either panel settles, and a file system
#       does not change underneath you.  The one thing that DOES change it is
#       a format, and that is where the cache is cleared.
#
# DONE (2026-09-12 revision BO(b) — "funktion för att formatera hårddisk men det
#                               ska vara med dubbla popups… Dess YES NO ska vara
#                               på annan plats än vid den första, så att det
#                               inte kan bli dubbelklick-olycka"):
#   [x] TWO windows, and the buttons MOVE between them.  The first one's
#       buttons are BOTTOM-RIGHT; the second one's are TOP-LEFT, and the second
#       window is placed so its Yes cannot land where the first one's "Yes,
#       continue" was — checked at three screen positions by test, including
#       both corners.  A double-click, a held button or a stuck Enter cannot
#       answer both.
#   [x] The second window is the one that shows WHAT IS ON IT: the first ten
#       top-level folder names, how many folders and loose files there are, the
#       label and the current file system.  A drive letter alone says nothing —
#       "D:" could be the empty stick or it could be the backup.
#   [x] Belt and braces on top of his design: the second window's Yes is dead
#       for two seconds and counts down visibly, Escape and the X are always
#       No, and the safe button owns the keyboard in both windows.
#   [x] FOUR drives are refused outright, with the reason in the menu line so
#       it is never a mystery: the drive Windows is running from, the drive
#       this program and its Helpfiles live on (X:), any network drive, and
#       CD/DVD or RAM disks.  The check is re-run at the moment of the final
#       click, not only when the menu was built — a drive can be unplugged in
#       between.
#   [x] It also says when the disk CARRIES WINDOWS.  His D: is labelled "Win 10
#       to go" and holds a whole installation, a BCD store, bootmgr and an EFI
#       folder; GetDriveType calls it "Fixed" and the disk does not report
#       IsBoot because it is not the one running, so nothing else in the
#       program would have breathed a word about it.
#   [x] NTFS / exFAT / FAT32, quick or full, and a new label.  FAT32 carries
#       its 4 GB warning next to the choice.  Format-Volume does the work on a
#       thread; the window says what happened either way and never guesses.
#
# DONE (2026-09-12 revision BN — "task queue… det verkar stå helt still.  Jag
#                               skickar till usb-disk.  Startade snabbt.
#                               Kopplade på bus lane… pausat, startat, full
#                               speed.  Vad ser du?"):
#
#   THE HANG, and it was not "verkar".  Measured on his machine while it was
#   happening: zero bytes read, zero bytes written, zero I/O operations in ten
#   seconds — and the window saying "▶ Running… · 1 MB/s · ~4.6 h left".  Both
#   lanes had been dead for 25 minutes.  The destination disk was fine (1 MB
#   written to it in 77 ms while the copy claimed to be using it), nothing was
#   paused, ⚡ Full speed was on, and no dialog was waiting for an answer.
#   Both lanes had stopped on the file they had just FINISHED writing — and
#   that file could not be opened by anything else, because the copy still had
#   it open.
#
#   [x] THE BUG: in _copy_file_chunked the reader thread's end marker was one
#       `q.put(None, timeout=0.5)` inside a bare `except Exception: pass`.
#       The hand-off queue holds three blocks.  If it was FULL when the last
#       block was read, and the writer took longer than half a second over its
#       own block, the put timed out, the exception was swallowed, and the
#       marker was never sent.  The writer's only way out of its loop is
#       `buf is None` — so it sat on q.get() for ever: file complete, file
#       handle open, task stuck on RUNNING, nothing moving, no error anywhere.
#       Half a second is nothing: one fsync to a USB disk does it (64 MB in
#       "Polite"), so does a throttle sleep of up to 2 s, so does standing
#       aside for the bus lane.  Reproduced on demand and fixed: the marker is
#       now retried until it lands or the copy is torn down.
#   [x] SECOND NET: the writer also gives up when the reader thread is gone
#       and the queue is empty.  The reader puts its marker in BEFORE it ends,
#       so a dead reader with an empty queue can only mean the marker was
#       already taken — never that one is still coming.  Tested with the
#       marker swallowed entirely; the copy still finishes, bytes identical.
#   [x] THE SPEED WAS A FICTION.  It was total bytes ÷ total wall time since
#       the job began.  That average cannot reach zero, it can only sag — so a
#       transfer that had been dead for half an hour still read "1 MB/s", the
#       one number that made it look like slow work instead of no work.  It is
#       measured over the last few seconds now, and it DOES fall to zero.
#   [x] AND THE WINDOW NEVER REPAINTED.  The only thing that redrew the strips
#       was a byte arriving, so when nothing arrived the display froze at its
#       last healthy reading and stayed there looking healthy.  A one-second
#       heartbeat redraws the strips (not the list — that would be a relayout
#       a second, and this window is on screen for hours).
#   [x] So the strip now SAYS IT: "⚠ NOT MOVING — no bytes for 4 min 12 s",
#       amber at 15 seconds, red at a minute, and the ETA reads "stalled"
#       instead of a number.  It also says WHY when the reason is known:
#       "⏸ PAUSED", "🚌 standing down for the bus lane", "⏳ standing aside
#       for the fast lane".  A job that is stood down no longer claims to be
#       "▶ Running…" in the list either.
#   [x] ⚡ Full speed only ever reached HALF the copy.  The writer re-read the
#       setting twice a second; the READER thread took one look at it when the
#       file opened and stayed at Very Low I/O priority for the rest of that
#       file.  It re-reads it now too.
#
# DONE (2026-09-12 revision BN(b) — "fixa så att man kan pausa och spara en
#                               queue… och ladda in och resume senare.  Eller,
#                               än bättre… att den auto-sparar alla inlästa
#                               händelser och tömmer först när det är klart"):
#   [x] The automatic file already survived a close; what it could not do was
#       come back as a RESUME.  A carried-over job was re-queued from scratch,
#       so with "ask" on the clash policy it asked about every file it had
#       already copied — four thousand of them, which is not a resume.
#   [x] NEW: a resumed job skips, in silence, every destination file that is
#       already there AND identical (same size, same date ±2 s).  It applies
#       to a job carried over from the last session, one loaded from a saved
#       queue, and one put back by ↺ Resume.  The clash policy is otherwise
#       untouched.
#   [x] NEW: ↺ Resume on the queue's button row.  THE ANSWER TO "the ones I
#       cancel, do I have to start over?"  No: pick the cancelled (or failed,
#       or finished) row and it goes back to work from where it stopped.  Only
#       the file that was mid-copy is done again — a cancel deletes that one on
#       purpose, so there is never a half-written file wearing the right name.
#   [x] NEW: 🗃 Queues… — park the queue (or just the rows you picked) under a
#       name and pick it up another day.  One JSON file each in
#       Helpfiles/redigerare/queues/, the SAME record format as the automatic
#       one, so both come back through the same code and behave identically.
#       Loading puts them back PAUSED; saving removes nothing.
#   [x] The automatic file still empties itself only when the work is really
#       done, which is what was asked for: it holds everything unfinished —
#       waiting AND running — and is rewritten as the list changes.
#
# DONE (2026-09-12 revision BN(c) — "Bus lane… ska vara toppen.  Den får även ha
#                               funktionen att den kan pausa huvudgrejen = kör
#                               bara bus-lane, och då lyx om man kan markera
#                               flera saker som man vill ska hamna i
#                               bus-lane-kön i stället för i huvudkön"):
#   [x] NEW: "🚌 only" on the queue toolbar.  Ticked, the big transfer stands
#       down at the next block boundary — nothing half-written, nothing thrown
#       away — and STAYS down until the bus queue is empty, then picks itself
#       up exactly where it stopped.  Not sharing the disk: two streams onto
#       one USB disk is the worst case there is, and this is the switch for it.
#       Sticky (queue_bus_solo), because it is a mode, not a one-off.
#   [x] It CANNOT deadlock.  A bus job that could not actually start — parked
#       on a name clash, waiting for room, still being measured, or held back
#       because an EARLIER job has the same file (which may be the very job it
#       would be pausing) — holds nothing, and the main lane runs.  All nine
#       cases have a test.
#   [x] The bus lane is a QUEUE, not one slot.  Several rows can be sent down
#       it at once (the 🚌 button always took a multi-selection; nothing said
#       so), they run one after another in the order they were put in, the
#       rows say "🚌 Bus lane #2", "#3", and the strip says how many are still
#       to come.  It shows the lane even when nothing in it has started yet.
#
# DONE (2026-09-12 — "Overwrite old skriver över allt som finns?  I så fall så
#                   borde den heta Overwrite och inget mer?"):
#   [x] Right, and worse than reported: "overwrite_older" was called "Overwrite
#       older" in the combobox and "Overwrite NEWER" on the clash banner three
#       inches above it — two opposite-sounding names for one mode, in one
#       window.  That is how it came to be read as "overwrites when the source
#       is older".  It does not: it writes only when the file coming IN is the
#       newer one.
#   [x] "Overwrite old" → "Overwrite always" (it overwrites everything in the
#       way, old or not — "old" was decoration), "Overwrite older" → "Overwrite
#       if newer", and the per-file dialog's button is now just "Overwrite".
#       The banner takes its labels from _CONFLICT_LABEL, so there is one name
#       per mode and nowhere for a second one to appear.  Nothing is stored by
#       label — every saved rule, preset and setting keeps the mode string — so
#       no saved data moves.
#
# DONE (2026-09-12 revision BM — "att jag kan redigera titel och sedan gå till
#                               annan fil och fortfarande vara i
#                               redigeringsläge… fungerar det flera steg?  Det
#                               fungerar inte alls för ändelser, vilket det
#                               borde.  Jag tror datumet kan ändras till nu om
#                               jag Move:ar en fil — bättre med ALDRIG, men en
#                               funktion som sätter valda filer till nu."):
#   [x] MANY STEPS, and it already did.  Up/Down in a rename box commits and
#       re-opens the box on the next row, over and over, in the Name column
#       and in the Type column alike, until ENTER (commit and out), ESC
#       (cancel and out) or a click anywhere else.  Proved with a test that
#       walks four rows and checks the box is still open on the fourth, in
#       both columns — no assumption, the widget itself was asked.
#   [x] THE EXTENSION had no way in.  F2 opens the NAME box and always has;
#       the extension could only be reached by a 650 ms slow click on the
#       86-pixel Type column, which is not something anybody finds by looking.
#       So it was not broken — it was invisible.  Two ways in now:
#       **Shift+F2** (next to F2, in the right-click menu, rebindable), and
#       **TAB inside a rename box**, which crosses Name ⇄ Type on the SAME
#       row without leaving edit mode.  The Tab commit finds the row again BY
#       NAME, because renaming a.txt to z.txt re-sorts the list under you.
#   [x] A FOLDER no longer opens an extension box.  The old guard
#       ("item not in _iid_to_fullname") was meant to keep folders out, but
#       that dict holds every row — so a slow click on a folder's Type column
#       opened an empty edit box over the word "Folder".  It renames the
#       folder now, which is what the click meant.
#   [x] MOVE DOES NOT TOUCH THE DATE — it never did, and now it is proved
#       rather than believed.  Same drive: os.replace, a rename on disk, which
#       cannot change a timestamp.  Across drives: the chunked copy runs with
#       keep_date=True and re-applies the source's stamp.  Drag-and-drop,
#       "Move As" and the Relocator all go through shutil.move, which keeps it
#       too.  The ONE thing that can put today's date on a file is a COPY with
#       Settings ▸ Dates ▸ "keep the date on copies" turned OFF — it is ON by
#       default and it is ON in his settings.  Answer: ALDRIG, as asked.
#   [x] …and because "never" needs a deliberate exception: right-click ▸
#       "🕒 Set date and time to NOW" stamps the whole selection.  It asks
#       first (defaulting to NO) and says the stamp it is about to write,
#       because the old dates do not come back.  Unbound by any key on
#       purpose; it is in the shortcut list if he wants one.
#
# DONE (2026-09-11 revision BL — "right-click a tab: I want Copy and Move
#                               too.  Copy = one more of the same tab, same
#                               settings, last in the row.  Move = to the
#                               other side.  A locked tab: Move = Copy, and
#                               you unlock it to move it."):
#   [x] Right-click a tab ▸ "⧉ Duplicate this tab" — a second copy, added
#       LAST on the same side, with the same folder, sort and lock.  The tab
#       you were on stays active; the copy just appears at the end.
#   [x] Right-click a tab ▸ "Move to the RIGHT / LEFT panel" — off this strip,
#       added last on the other one, which switches to it.
#   [x] A LOCKED tab is COPIED, not moved (his choice, and the one that keeps
#       the lock's promise: "this tab stays here").  The menu line itself
#       reads "Copy to the … panel (locked 🔒 — this tab stays here)", so it
#       never surprises; unlock to move.  The copy is locked too (same
#       settings).  "Ignore tab locks" does not change this — that tick is for
#       clearing tabs out, not for relocating them.
#   [x] The LAST tab on a side is copied the same way — a side always keeps
#       one tab, exactly as Close already refuses to take it.
#   [x] Moving a tab that an F8 pair links asks first, the same question
#       Close asks (on that side it is the same loss).  A copy breaks nothing
#       and never asks.
#   [x] Neither is ever a Workspace BASE tab: with a Workspace loaded the new
#       tab arrives as an amber extra and the half-save remembers it, lock
#       included.  Moving a base tab away works like closing it — the saved
#       Workspace is only rewritten by Save / Update.
#   [x] Greyed out, with the reason in the line, when either side is an FTP
#       site — a local folder cannot be shown there.
#
# DONE (2026-09-09 revision BK — "att kunna markera en eller flera
#                               filer och med högerknapp välja om man vill
#                               CLIPBOARDa bara filnamnen eller även
#                               sökvägen."):
#   [x] Right-click ▸ "📋  Copy to clipboard" — a submenu with five
#       shapes: name only, name without extension, full path, full path in
#       quotes (for a command line), and the folder without the file name.
#       One marked file or fifty; one per line.
#   [x] "Folder only" collapses duplicates, so marking twenty files in the
#       same folder gives that folder ONCE and not twenty times.
#   [x] It goes into the REAL Windows clipboard (CF_UNICODETEXT), not Tk's.
#       Tk only registers itself as the clipboard OWNER and serves the text
#       on request — which means everything copied that way vanishes the
#       moment File_manager is closed.  This survives.  Tk is kept as the
#       fallback for the moment another program holds the clipboard open.
#   [x] No popup to click away: the status bar says what was copied and how
#       many, then goes back to the disk info by itself.
#   [x] The clipboard is RETRIED.  Windows' clipboard history opens the
#       clipboard the instant it changes, and while it holds it nobody
#       else can — so the second of two quick copies failed outright in
#       testing.  Ten tries, 20 ms apart, then the Tk fallback.
#   [x] The SEL ▾ toolbar menu gained "Copy names to clipboard" beside the
#       "Copy paths" that was already there.
#   [x] "Copy names" and "Copy folders" are also real actions now, so they
#       can be put on the toolbar, given a shortcut, or run from the
#       command palette — next to the "Copy paths" that was already one.
#
# DONE (2026-09-09 revision BJ — "can file manager create IMG/ISO files?
#                               That would be good."):
#   [x] Yes, now.  Tools ▸ "💿 Create ISO / IMG image…", Ctrl+Alt+I, or the
#       toolbar.  Mark files and folders, give the image a name and a volume
#       label, and it is built with a progress bar and a Cancel that deletes
#       the half-written file instead of leaving it looking finished.
#   [x] The writer is OURS (DEL 53), written from the ISO 9660 spec, because
#       there was nothing here to lean on: pycdlib is not installed, 7-Zip can
#       READ an image but never write one, and neither oscdimg nor mkisofs is
#       on the machine.  ISO 9660 level 2 plus a JOLIET tree, so "Faktura
#       Håkan 2017.rtf" survives with its å and its spaces intact.
#   [x] .iso and .img are the same bytes for a data image; the extension is
#       yours to pick.  Said out loud in the window rather than left as a
#       thing to wonder about.  It is not a bootable disc — no El Torito.
#   [x] VERIFIED, not assumed.  An image built from a tree with Swedish
#       characters, long names, four levels of nesting, an empty file and a
#       2 MB binary was extracted with 7-Zip and every file compared by
#       SHA-256 — and Windows itself mounted it (label TESTDISC, CDFS, every
#       name intact).  A second test drives the real window end to end.
#   [x] The one that cost an hour: an EMPTY file takes NO sectors.  Reserving
#       one for it makes the volume one sector longer than the bytes written,
#       and every reader then says "unexpected end of archive" about an image
#       that is otherwise perfect.
#   [x] A single file over 4 GB cannot go in one ISO extent; it is left out
#       and reported by name rather than silently truncated.
#
# DONE (2026-09-09 revision BI — "it also seems to have trouble with locked
#                               files.  At a MOVE I can understand it, but at
#                               a COPY that should not be a problem."):
#   [x] NOTHING WAS EVER LOCKED.  His files are READ-ONLY (-r--r--r--), and
#       that is a different thing entirely.  Reading one is fine — proved by
#       reading his actual "Faktura Brattex.rtf" straight through.  What
#       happens is this: shutil.copystat faithfully copies the read-only
#       attribute to the destination, so the SECOND copy of the same tree
#       meets a read-only file where it wants to write, and Windows refuses.
#   [x] Worse, the message pointed at the wrong file.  The log line printed
#       the SOURCE while the exception carried the DESTINATION, so
#       "Copy failed for <source>: Permission denied: '<source>'" read exactly
#       like a locked source — which is why it looked like a locked-file bug
#       for a day.  It now names the file the error is really about.
#   [x] And the overwrite branch SWALLOWED the failure: os.remove() on a
#       read-only file raises WinError 5, that was caught and ignored, and the
#       copy then died one step later on the same file.  Replaced with
#       _force_remove(), which clears the attribute and retries — for files
#       and for whole trees.
#   [x] _open_sequential() clears it too, for the case where the old file is
#       overwritten in place.  The attribute is put straight back afterwards:
#       copystat re-applies the source's, so a read-only file stays read-only.
#       Clearing it is not a liberty — it is exactly what "Overwrite old" asked
#       for.
#   [x] A MOVE of read-only files left every original behind with a warning.
#       Same fix: deleting the original is what "move" means.
#   [x] The error text no longer sends him looking for a program that has the
#       file open when nothing does — it says READ-ONLY and where to clear it.
#       A file that really IS locked still says so; both are tested.
#   [x] Inline rename, Up/Down: the ".." row was a valid step target, and
#       start_rename("..") returns without a word — so after a rename that
#       moved the file in the sort order, edit mode simply never came back.
#       ".." is now stepped OVER, and if the next row cannot be found by name
#       the row now in that position is used, because landing somewhere beats
#       dropping out of edit mode in silence.
#   [x] Editing the TYPE column had no Up/Down bindings at all — the same
#       keyboard walk, dead in one of the two columns.  It has them now, and
#       the arrows re-open the column you were actually in.
#
# DONE (2026-09-09 revision BH — "has something changed?  ENTER and
#                               double-click on a PY = open with a text
#                               editor.  Then I cannot start programs without
#                               putting them in Tower first."):
#   [x] MY FAULT, from revBE.  Turning DefaultHub on for a plain Enter was
#       right for a .jpg and a .pdf — and wrong for a .py, because the table's
#       "text" kind lists .py, .bat and .ps1 and sends them to Meditor.  Both
#       halves of that are correct on their own: a .py IS a text file to every
#       other program in the tree, and Enter in a FILE MANAGER on a program
#       means RUN it.  The mistake was letting one answer serve both.
#   [x] Enter / double-click on .py .pyw .exe .com .bat .cmd .ps1 .msi .lnk
#       .vbs .wsf .jar now STARTS it, checked before DefaultHub is consulted.
#       F4 still edits, Shift+Enter still shows it in the built-in viewer, and
#       everything that is not a program is completely unaffected.
#   [x] A .py is started with **pythonw.exe**, not through the Windows
#       association.  His association is `python.exe "%1"`, which throws a
#       console window up behind every one of his GUI programs; Tower and the
#       open-with block both go out of their way to use pythonw, so this does
#       too.  `_real_python()` is the console counterpart, and neither one may
#       ever be sys.executable — in a build that is File_manager.exe itself,
#       which would start a second File Manager instead of Python.
#   [x] Right-click ▸ **▶ Run** and **▶ Run in a console (see output)**.  The
#       console one keeps the window open after the script ends (cmd /k), so
#       the error from a script that "does nothing" can actually be read —
#       which is otherwise the one thing pythonw takes away.
#   [x] Settings ▸ General: "Enter and double-click RUN a program".  On by
#       default.  Off, a .py follows DefaultHub to the editor again — a real
#       preference, spelled out, rather than a surprise.
#   [x] Test `test_run_py.py`: a throwaway .py that writes a stamp file is
#       activated for real and the stamp is waited for — proof it RAN, not a
#       mock of the intention.  Five cases: the hub really does say Meditor,
#       Enter runs it with pythonw anyway, the setting sends it back to the
#       editor, an ordinary text file is untouched, and F4 still edits.
#
# DONE (2026-09-09 revision BG — "odd that two rules can be in conflict…
#                               then there must be a conflict warner; and a
#                               Rules button after Folders sort like…"):
#   [x] HIS QUESTION FIRST, because it is the whole misunderstanding: "surely
#       the first rule fires and the second is never asked about?"  The rules
#       are not a CHAIN, they are a LOOKUP.  Folder paths NEST — a rule on
#       X:/1---Python also covers X:/1---Python/0---Python/Py — so ONE single
#       transfer can be described by several rules at once, and the program
#       has to CHOOSE one.  Nothing "fires first"; something is picked.  That
#       is why two rules can disagree about the same copy.
#   [x] CONFLICT WARNER, at the top of the rules window: which pairs of rules
#       cover the same ground and then say different things, and why each pair
#       matters.  Rules on folders that can never both apply are not reported
#       — a warner that cries wolf is worse than none.  The nastiest case gets
#       its own words: two rules in DIFFERENT Workspaces are not safe, because
#       with only one of them loaded the other is not out-ranked but ABSENT,
#       and a broad rule then decides alone.
#   [x] NEW "⚖ Rules" BUTTON on the Workspace bar, straight after "Folders
#       sort like files".  Dim when nothing governs the two folders in the
#       panels, LIT (blue, bold, with a count) when something does — so a rule
#       is visible BEFORE it has done something you did not want, which it
#       never was.  Also on Ctrl+Alt+W and in the toolbar list.
#   [x] Clicking it shows every rule for that pair BOTH WAYS ROUND — left→right
#       and right→left — each marked USED / beaten / skipped-because-its-
#       Workspace-is-not-loaded.  A rule for the other direction is just as
#       much "about these two folders", and being shown only your own
#       direction is how the other one stays invisible.
#   [x] And when there is NO rule: two green buttons make one for this exact
#       pair on the spot, with the folders already filled in — no queueing a
#       transfer first just to be asked the question.  A rule made here starts
#       with NO Workspace, which is the setting that cannot surprise him.
#   [x] The button re-checks only when the folder PAIR changes.  The panels
#       rebuild every 1.5 s, and a button recolouring itself on each of those
#       would be a light flickering in the corner of his eye all day.
#   [x] Fixed in passing: three `log.error(...)` calls in a program that has
#       no logger called `log` — only `_log()`.  Each sat in an `except`
#       block, so a handled error raised NameError from inside the handler and
#       became a crash.  ("could not show <file>" was one of them.)
#
# DONE (2026-09-09 revision BF — "my newest queue rule is work dir → Py,
#                               backup-rename.  It does not do that.  It
#                               overwrites."):
#   [x] FOUND IT, and the rule he wrote is not the guilty one — it never got
#       a say.  A second rule reads  {ROOT} → {ROOT}  ·  Overwrite all  ·
#       Workspace "Grund": the whole tree to the whole tree.  Standing in
#       Grund, his precise rule (work dir → Py, Workspace "Python") is thrown
#       out by the Workspace test before anything else is looked at, the
#       catch-all is the only one left, and the file he meant to keep is
#       replaced instead of renamed.  In Workspace Python it has always
#       worked — which is exactly why it looked random.
#   [x] Nothing on screen ever said so.  The queue note read "auto-rule:
#       Overwrite all" without naming the rule, so a rule doing the opposite
#       of what he had just written down was indistinguishable from a bug.
#       The note now names the folders and the Workspace behind the decision.
#   [x] NEW  "🔎 Which rule wins?"  in the conflict-rules window.  Two folders
#       (pre-filled with the panels as they stand) and it lists EVERY rule
#       covering that pair, in the order they are considered, with the reason
#       each one lost: USED / beaten by a more precise rule / skipped because
#       its Workspace is not loaded.  That last line is the whole answer to
#       "my rule does nothing".
#   [x] THE MOST SPECIFIC RULE NOW WINS, not the first in the list.  Order
#       cannot express what he means: a rule naming both exact folders IS the
#       more precise answer whatever date it was made.  Specificity is how
#       much of the two paths a rule pins down; a named Workspace breaks a
#       tie and the list order breaks what is left, so two equally precise
#       rules behave exactly as before.
#   [x] A rule that covers a whole drive or the whole tree AND destroys the
#       old file is now flagged in the list with what it really means: "it
#       governs every folder underneath".
#   [x] NOT changed, deliberately: a Workspace on a rule still decides WHEN
#       that rule applies.  Making a precise rule out-rank the Workspace test
#       would quietly break every per-Workspace rule he has.  The two ways
#       out are his to pick — clear the Workspace box on the work dir → Py
#       rule so it applies everywhere, or narrow the {ROOT} → {ROOT} one.
#
# DONE (2026-09-08 revision BE — "File manager cannot open jpg, pdf and the
#                               like; that is what DefaultHub is for"):
#   [x] And it was: DefaultHub's table was consulted ONLY when "Enter and
#       double-click use MY programs" was ticked, and that setting is off by
#       default.  So a plain Enter on a .jpg walked straight past the line
#       that says "images belong to SeeView" and handed the file to a Windows
#       association this machine does not have.  Nothing opened, nothing said
#       why.
#   [x] The two are now SEPARATE switches, because they are not the same kind
#       of promise.  "Enter and double-click follow DefaultHub" is ON by
#       default — that table is the one place he writes down which program
#       owns a file type for the whole tree.  "Enter and double-click also use
#       MY OWN openers" (the per-type opener and the F4 program) stays OFF, so
#       a double-click still cannot fire a program he set once and forgot.
#       Shift+F4 and Ctrl+F4 remain the way OUT to Windows and skip both.
#   [x] A target is only a NAME, and the name was looked up in `<home>/Py`
#       alone.  It now uses DefaultHub's "py_roots" list, so a target in
#       `1---Musik/Py` or in its own folder under `1---Annat` resolves too.
#       When that list is empty the same folders are found automatically, and
#       the house-keeping folders are skipped on purpose: `0---Retired` and
#       `0---Claude_work_dir` hold copies that are deliberately NOT his live
#       programs, and one of those staging folders holds 117 of them.
#   [x] ALL the .py folders are searched before ANY build folder, or a stale
#       build in the main tree would win over the live source of a music
#       program.
#   [x] "Could not open file: …" was a useless answer — it says what did not
#       happen and leaves you where you started.  Now it says WHY (either the
#       program DefaultHub names could not be found, or nothing owns that
#       extension anywhere) and offers the way on: the built-in viewer where
#       it can really render the file, otherwise Windows' own "Open with" box.
#
# DONE (2026-09-08 revision BD — "can I not mark several folders and press
#                               Alt+Enter to see their individual size?"):
#   [x] Alt+Enter with MORE THAN ONE item marked no longer shows a single
#       message box about one of them.  It opens a list: one row per marked
#       item with that item's OWN size (human + exact bytes), how many files
#       and folders are inside, and when it was last changed — with a total
#       underneath.  Click a heading to sort; "Copy list" puts the whole table
#       on the clipboard.  One item marked still gives the old box.
#   [x] The folders are measured in a BACKGROUND thread and the rows fill in
#       as the numbers land, so twenty folders with a million files between
#       them do not freeze the window.  The window is not modal — a measure
#       can take a while and you should be able to keep working.  Closing it
#       (Escape, ✕ or Close) STOPS the walk instead of leaving a thread
#       grinding through a disk nobody is waiting for.
#   [x] Junctions and symlinks are skipped, or a reparse point walks the same
#       tree twice and reports a folder as bigger than the disk.
#   [x] NEW MODE: "Folders show a SIZE too" (Settings → Display, off by
#       default).  Alt+Shift+Enter has always measured the folders in the
#       active panel ON DEMAND; this is the standing version — every folder
#       listing measures itself from now on.  Also on the toolbar / shortcut
#       list as "Folder sizes: always on / off" if you want it on a key.
#   [x] The measured numbers are CACHED per folder path and written straight
#       back after each rebuild.  The auto-refresh watcher rebuilds the list
#       every 1.5 s, and without the cache the Size column would flicker
#       between empty and a number for as long as you stood there.
#   [x] The automatic pass measures only folders whose cell is still empty,
#       and it never cancels a measurement already running — a second PRESS
#       of Alt+Shift+Enter means stop, an automatic pass does not.
#
# DONE (2026-09-08 revision BC — "either it is in the background or it is
#                               permanently on top; the one blocks the other"):
#   [x] NEW: "⏱ Top" on the Task Queue toolbar, beside 📌 On top.  In front
#       NOW, and back down the moment another window is clicked — whatever you
#       click next is the top window.  The middle setting that was missing:
#       📌 is over everything for ever, no pin at all is buried the first time
#       you touch the file manager, and neither is what you want while you are
#       actually watching a transfer.
#   [x] It does NOT change the 📌 tick and is not remembered — it lasts until
#       the next click, which is the point.  If 📌 is on, ⏱ leaves it alone;
#       a one-off must never quietly undo a setting.
#   [x] Two ways of noticing "you clicked something else", because one is not
#       enough: a 250 ms foreground-window poll for other PROGRAMS, and a
#       <Button-1> on the file manager itself — the queue never takes the
#       keyboard, so the file manager was already the foreground window when
#       the button was pressed and the poll alone could never see it.  Bound
#       with add="+", or it would replace what the file manager already has
#       on <Button-1>.
#
# DONE (2026-09-08 revision BB — "I clicked the File manager away while the
#                               task queue was busy"):
#   [x] REPORTED, as a serious problem: closing the window while the queue was
#       still working took the whole queue with it, silently.  Asked for two
#       things: (1) be ASKED before closing while it is working, and if the
#       answer is yes, pause the transfer at a suitable place first; (2)
#       everything not finished must be saved and come back at the next start,
#       paused, with the Task Queue temporarily in front, until it is done.
#   [x] The X now asks — but the BYTES STOP FIRST.  The moment the X is
#       clicked the queue is paused, so the copy stands down at the next block
#       boundary (that is the "suitable place": no half-written block, and
#       _copy_file_chunked is written to be stopped there).  Only then does
#       the question appear, and "▶ Keep working" puts it back exactly where
#       it stood, pause and all.  ESCAPE = keep working, so a stray click on
#       the X costs nothing.
#   [x] Three answers, not Yes/No — "No" to "close anyway?" means nothing:
#         ▶ Keep working  ·  💾 Close — keep the queue  ·  🗑 Close and drop it
#   [x] On the way out the running file is CANCELLED, not left paused.  A
#       cancel deletes the part-written destination file; a pause leaves it
#       sitting there under the right name, where next time it looks like a
#       file that is already there.  The close waits up to 5 s for that to
#       happen and then goes anyway rather than hanging.
#   [x] NEW: Helpfiles/redigerare/task_queue.json.  The unfinished list is
#       written there as it changes (debounced — _update_ui fires many times a
#       second while a copy runs, the LIST changes a few times an hour), so a
#       power cut costs at most the last few seconds of queueing, not the
#       queue.
#   [x] At the next start those jobs come back PAUSED, with the Task Queue
#       brought to the front (always-on-top, still never taking the keyboard),
#       and a green banner saying how many and offering "▶ Start now" /
#       "🗑 Drop them".  Not one byte moves until Start is pressed.
#   [x] They come back through the ORDINARY add path, so every one of them is
#       measured and re-scanned against the disk as it is NOW: files deleted,
#       moved or already copied in the meantime are picked up exactly as they
#       would be for a job queued by hand this minute.  A job whose sources
#       are all gone is dropped and said so, not queued to fail.  The row that
#       was mid-transfer says "⚠ Was interrupted"; the others "↺ From last
#       session".
#   [x] CHANGED, and it is the point of the whole thing: queueing a job no
#       longer lifts a pause.  A queue you paused — or one restored paused —
#       stays paused until ▶ Start or the Pause button says otherwise.  It
#       used to resume itself the moment you dragged another file onto a panel.
#
# DONE (2026-09-08 revision BA — "let THIS one go first"):
#   [x] REPORTED: the queue has ↑ and ↓, and neither of them helps while a
#       9 GB transfer is running — reordering the WAITING list does nothing
#       about the fact that everything waits.  Asked for a "do this now"
#       button: mark one or more jobs and have them go before whatever is
#       being sent, "alternatively both things could be sent at the same
#       time, so it becomes a bus lane."
#   [x] NEW: 🚌 "Do it now" on the Task Queue's bottom row (a toggle — press
#       it again to put the rows back in the normal queue).  It is the bus
#       lane, not a queue jump: the picked jobs start in the SECOND worker,
#       ALONGSIDE the running one, so a transfer half-way through a 9 GB file
#       is never thrown away to make room.
#         · a SMALL bus job makes the big transfer stand aside for the second
#           or two it needs (the fast lane already did this by size);
#         · a BIG one runs beside it and the two share the disk — standing the
#           big job down for a job that is itself minutes long would only be
#           the old queue with the order swapped round.
#       The size rule, the job type and the fast-lane on/off switch are all
#       overruled: the button is an instruction, so it must not silently do
#       nothing.
#   [x] The one rule NOT waived: a job still may not overtake an EARLIER job
#       holding the SAME file.  "Copy X, then move X" queued in that order
#       stays in that order, or the copy would find nothing left to copy.
#       Such a row keeps saying "⏳ after #n" and takes the lane the moment
#       the other one is out of the way.
#   [x] FIXED on the way: the two lanes shared ONE set of progress numbers, so
#       with two jobs really running at once the bar and the ETA jumped
#       between them ten times a second and neither reading meant anything.
#       The second lane now has its own strip (file, %, speed, its own ✖) and
#       the big transfer's bar is its own again.
#
# DONE (2026-09-07 revision AZ — "10 GB from C to C and the whole computer was
#                               locked for twenty minutes"):
#   [x] REPORTED: a 10 GB C→C copy left the machine almost unusable.  Ctrl+Alt+
#       Del took 30 SECONDS to paint.  Tower's Notes would not open at all.
#       The throttle was supposed to give a long-running file LESS power so
#       other work could carry on — instead the longer it ran, the worse it
#       got.  Asked for "at the very least a checkbox not to slow down, but
#       find out why it locks up like that."  Three separate faults:
#
#       1. THE THROTTLE WAS MEASURING SOMETHING THAT ISN'T THERE.  It paced on
#          how long fo.write(block) took.  A buffered write returns as soon as
#          the block has been memcpy'd into the Windows file cache — tens of
#          MICROSECONDS — so `work` was ~0, the computed sleep was ~0, and the
#          cap did nothing whatsoever.  Measured here: 200 MB "copied" in 0.06
#          seconds at a claimed 3.4 GB/s, with not one byte of it on the disk.
#          The cap only began to bite once write() itself started blocking —
#          i.e. once the machine had ALREADY seized.  Precisely backwards.
#       2. SLEEPING IS THE WRONG MECHANISM ANYWAY.  A sleeping copy hands
#          nobody a single disk request; one drive serves one queue, and the
#          4 MB write already in flight is still in front of Explorer's 8 KB
#          read.  All the sleep does is make the copy last LONGER, so the
#          queue it is sitting in front of stays clogged for longer — which is
#          exactly "the bigger the file, the more painful it gets".
#       3. NOTHING BOUNDED THE WRITE-BEHIND CACHE.  10 GB of buffered writes
#          become gigabytes of dirty pages; Windows then stalls every process
#          that writes anything and evicts mapped pages to find room — so
#          LogonUI.exe and a cold python.exe had to be read back off the very
#          disk the copy had saturated.  That is the 30-second Ctrl+Alt+Del.
#          (C: is a DRAM-less Patriot P300 at 76 % full.  Once its SLC write
#          cache is spent, sustained writes fall off a cliff while it folds —
#          so it drains far slower than it accepts.  The hardware is why this
#          hurts HERE and not on the other two drives, but the bug above is
#          what turned a slow copy into a locked machine.)
#
#   [x] FIXED, with the mechanism Windows actually provides: BACKGROUND I/O
#       PRIORITY (SetThreadPriority THREAD_MODE_BACKGROUND_BEGIN) on both copy
#       threads.  The copy asks for its disk I/O at the lowest priority, so
#       anything YOU do overtakes it instead of queueing behind it.  It costs
#       nothing on an idle machine — with nothing competing, nothing overtakes
#       — and it takes effect on the next request, not after sixty seconds.
#   [x] FIXED: the write cache is flushed every 64 MB (Settings ▸ Transfers,
#       0 = never), so the dirty backlog can no longer run away.  Same bytes
#       written; it just refuses to let the debt grow without limit.
#   [x] Reads and writes now use FILE_FLAG_SEQUENTIAL_SCAN, so a 10 GB copy
#       stops evicting the rest of the machine from RAM on its way past.
#   [x] The percentage cap is now OFF by default (one-time migration turns it
#       off for anyone still on the stock Polite numbers).  When it IS on it
#       finally works: real throughput is measured against the fastest
#       uncapped stretch of the file instead of against a write() call that
#       never touched a disk.
#   [x] On one drive (C→C) the read-ahead is cut to a single block.  It was
#       written for two devices — "source and destination are nearly always
#       different devices" — and on ONE device it only interleaves reads into
#       the write stream and deepens the queue.
#   [x] NEW: "⚡ Full speed" tickbox ON THE TASK QUEUE TOOLBAR, the asked-for
#       override.  Buried in Settings is no use while a copy has the machine
#       on its knees.  It is LIVE: it reaches the file that is already being
#       written, not just the next job.  Unticking it restores whatever was in
#       force before, including hand-tuned numbers.
#   [x] Settings ▸ Transfers rewritten around the two settings that matter,
#       with the percentage cap demoted to the bottom and labelled for what it
#       is.  The three presets set all of it.
#
#       MEASURED, 3 GB C→C, with a 4 KB write+fsync sampled every 50 ms
#       alongside it as a stand-in for "open a program":
#           old (Full speed)   32.0 s   p95 stall 1800 ms   worst 10848 ms
#           background I/O     52.3 s   p95 stall   47 ms   worst   709 ms
#           flush only         54.3 s   p95 stall   54 ms   worst   382 ms
#           BOTH  (= Polite)   42.2 s   p95 stall   47 ms   worst   175 ms
#       The two together are both the fastest of the three fixes and the
#       smoothest.  Against the old behaviour: 1.3x the wall clock, and the
#       worst stall 62x shorter.  And the old 32 s is not even honest — it is
#       "copy 30 s + the machine drains for another 3-12 s afterwards".  At
#       800 MB, which the cache still swallows whole, the two are neck and
#       neck (0.99x) — this only ever mattered on the big ones.
# DONE (2026-09-06 revision AY — "Go to:" — paste a path, land there):
#   [x] ASKED FOR: "en ruta för att mata in t.ex. C:/Program Files/Common
#       Files/VST3/Psylus Audio för att komma direkt dit.  Den kan vara efter
#       folders sort like files, och då det är väldigt till höger så räcker
#       det att det påverkar aktivt högerfönster."
#   [x] NEW  A path box at the far right of the Workspace bar, after "Folders
#       sort like files" (DEL 51).  Type or paste a folder, press Enter, and
#       the RIGHT panel is there.  It is packed side="right" in its own frame,
#       so however many Workspace buttons the bar carries it can never be
#       pushed off the end.
#   [x] It takes whatever was on the clipboard, because a copied path is never
#       just a path: the double quotes Explorer's "Copy as path" wraps it in,
#       single quotes, forward slashes, %ProgramFiles% and ~, file:/// out of
#       a browser, UNC, and a bare "D:" for that drive's root.  A path that is
#       not absolute — ".." or a plain sub-folder name — is read from where
#       the right panel stands now, like a shell.  Name a FILE and it lands in
#       that file's folder with the cursor already on the file.
#   [x] Keys in the box: Enter go · Ctrl+Enter go in a NEW right tab · Tab
#       complete the name being typed (the box itself is completed — no popup)
#       · Down or the ▾ button = the last 20 places it landed on, saved in
#       settings["goto_history"] · Esc clears, and on an empty box hands the
#       keyboard back to the file list.  Ctrl+Shift+G jumps into the box from
#       anywhere and is re-mappable like every other shortcut ("goto_box").
#   [x] A path that does not exist opens NO dialog.  The box goes a steady
#       dark red, the status line says why — and says so when the PARENT
#       folder does exist, which is what a typo in the last name looks like —
#       and the red is gone on the next keystroke.  Nothing blinks: the caret
#       is a tk.Entry one with insertofftime=0, and there is no timer.
#   [x] The typed text lives in a StringVar on the frame, not in the widget,
#       because the Workspace bar is destroyed and rebuilt whenever a
#       Workspace changes — a half-typed path used to be exactly the sort of
#       thing that would vanish under you.
#   [x] Going there records the folder the panel is LEAVING in the drive
#       memory first, the same as the drive menu does, so a folder reached
#       through the box is still there when you hop volumes and come back.
#
# DONE (2026-09-03 revision AX — Print / export listing takes over from
#                               Dir_lister AND File-sizes, both being retired):
#   [x] ASKED FOR: "dir lister-programmet... är det något i det som inte redan
#       finns i file manager?"  Four things were, so they are here now and the
#       program itself goes to 0---Retired.  Print / export listing (Ctrl+P):
#   [x] NEW  "Levels:" next to "Include subfolders".  The checkbox was all or
#       nothing — an os.walk with no bottom — so "three levels down C:\" was
#       not a listing anyone could ask for.  0 keeps the old unlimited walk,
#       and a saved setting from before this has no "depth" key, so it reads
#       as 0 and nothing changes for it.  1 == the folder itself, which is
#       the same listing as leaving the checkbox off.
#       The folder's own entries are collected BEFORE the walk is pruned, so
#       the last level still NAMES the subfolders it refuses to open.
#   [x] NEW  "Name filter:" — comma-separated wildcards (*.exe,*.dll).  Files
#       only: filtering a folder away would take everything under it with it,
#       silently.  The Search window has had a glob for years, but its hit
#       list has no Save, no Copy and no Export, so it was never a way to get
#       a filtered listing out of the program.
#   [x] NEW  "Compact tree" as a fourth Include choice — one line per folder
#       with its files after it, Dir_lister's own shape.  A build tree fits on
#       a screen instead of a page per folder.  It renders as TXT, CSV, HTML
#       and PDF like everything else: _table() is now the single source all
#       four writers read, so the next mode does not have to be added to four
#       renderers.
#   [x] NEW  "Version" column, and a [V2.1.3] at the end of a compact-tree
#       line.  _version_token() looks in the shown files, then in the ones the
#       filter hid, then in the folder's own name.
#       FIXED WHILE PORTING IT: Dir_lister's regex let a version run on
#       through letters and underscores, so "Setup_v1_then_v2.exe" came out
#       as "V1thenv2".  After the first number only more numbers may follow
#       now, which also makes v1_2_3 read as V1.2.3 instead of V123.
#   [x] NEW  "Find:" over the preview — shows only the lines containing a
#       word (Dir_lister's search panel).  Save and Print always write the
#       FULL listing; Copy deliberately follows the screen, so a search can be
#       copied out on its own, and the status line says "showing 12 of 340
#       lines" so a narrowed preview can never be mistaken for the real one.
#   [x] ASKED FOR next: "Är File sizer också något som egentligen redan finns
#       i file manager... eller som borde finnas där?"  It was, apart from two
#       lines, so those are here now and File-sizes.py goes too:
#   [x] NEW  "Size in:" — Auto, or one fixed unit for the whole column.  Auto
#       reads best ("834 KB", "1.5 GB") and adds up to nothing: sorted, 9 KB
#       lands above 8 MB, and no spreadsheet can sum a column of mixed units.
#       A fixed unit writes bare numbers and puts the unit in the HEADING
#       instead — "Size (MB)" — because a column of bare numbers with no unit
#       anywhere is worse than either.
#   [x] NEW  the summary line now carries the TOTAL SIZE, not just the count:
#       "1 204 items · 3.4 GB · generated ...".  Counting rows answers "how
#       many things are here", never "how big is this folder", which is the
#       question File-sizes existed to answer.  Deliberately NOT added as a
#       row at the bottom of the CSV — that is a data table, and a total row
#       in it breaks every sum written against it.
#   [x] Depth is greyed out while subfolders are off, the column boxes are
#       greyed out in tree mode, and the unit picker is greyed out when there
#       is no Size column — a control that is ignored should look it.
#   [x] FIXED, and it was there before this: Save as… / Copy / Print… / Close
#       were HALF A BUTTON tall (11px of 26) at the window's own default size,
#       and vanished altogether the moment the window was made any smaller.
#       Same trap as the Settings footer in revAU: the preview was packed
#       expand=True BEFORE the button row, and pack hands out space in the
#       order things are packed, so the last row got whatever was left — which
#       was nothing.  The row is now packed side="bottom" FIRST, and the
#       preview shrinks instead.  The window also opens 900x620; the depth box
#       and the name filter had pushed the option rows past the old 760.
#   [x] 79 assertions in test_print_listing.py drive the real window against a
#       sandbox tree — including the button row at three window sizes, which
#       is what would have caught the row above years ago.
#   [x] STILL MISSING from File-sizes: it scanned on a background thread, and
#       this preview does not — a listing of a whole drive with no depth limit
#       blocks the window while it walks.  Worth doing if it ever bites.
#
# DONE (2026-09-03 revision AW — Relocator: many source folders, and folders
#                                to stay out of):
#   [x] ASKED FOR: "'Look in sub-folders too' needs a way to add one or more
#       paths to exclude.  I am going to keep the backup folder in the same
#       folder as the folders with the backup files I want sent to it — I must
#       be able to exclude the backup folder."  And: "good if several
#       'From this folder' folders could be added, so it does not turn into
#       many near-identical rules."
#   [x] NEW  rule key "sources": a LIST of source folders.  One rule now covers
#       four download folders instead of four rules that all have to be edited
#       four times.  Read through _relocator_sources(); a rule written before
#       this has only "source" and still works, a blank entry still means
#       "whichever folder the active panel is showing", and _collect writes
#       BOTH keys so a rule saved here is still readable by an older build.
#       A file that turns up under two of the folders is moved ONCE (the scan
#       de-duplicates on the normalised path).
#   [x] NEW  rule key "exclude": a list of folders the rule never looks in.
#       A full path excludes that folder and everything under it; a bare name
#       (no backslash and no drive letter) excludes EVERY folder called that at
#       any depth — "Backup" on one line instead of twenty paths.  Excluded
#       folders are PRUNED from the walk, not filtered out afterwards, so a big
#       backup tree costs nothing to skip.  C:\\Work\\Backup2 is NOT swallowed
#       by an exclude on C:\\Work\\Backup (the separator is part of the test).
#   [x] FIXED on the way, and this one moved files: "already at the
#       destination" only ever compared the file's IMMEDIATE parent, so a rule
#       recursing into a destination that sits INSIDE its source picked its own
#       delivered files up again from one level down (dest\\old\\x.bak).  It now
#       tests the whole destination subtree.  That is the exact shape of the
#       backup-folder-inside-the-source case, and it was broken with or without
#       an exclude list.
#   [x] A source folder that is missing, or that IS the destination, is now
#       dropped from the list instead of killing the rule — with several
#       folders that is one bad line, not a broken rule.  Both are counted and
#       the "why did this find nothing" line says so.
#   [x] THE EDITOR SCROLLS.  It was already 920px of a 1080px screen on the
#       "newer" kind, and these two lists grow, so the fields sit on a canvas
#       and Save / Cancel / 🔎 Test it live in a FIXED footer packed first —
#       the revAU lesson, applied before it could bite.  The window is
#       vertically resizable, re-measures itself whenever a row is added or a
#       kind is switched, and the wheel works over the fields.
#   [x] Tested: 13 checks on real folders (multi-source, overlap, both exclude
#       kinds, the Backup2 near-miss, missing folders, old single-source rules,
#       blank = active panel), 19 in the editor window, 12 on the rules list and
#       the JSON round trip, plus malformed rules through describe() and scan().
#       All green.  Scripts in the scratchpad: test_reloc.py,
#       test_reloc_gui.py, test_reloc_list.py.
#
# DONE (2026-09-03 revision AV — the General tab now scrolls):
#   [x] The revAU note below left this open, and it is the same fault one tab
#       over: General asks for 1874px and the capped window gives it 861, so
#       twelve controls sat under the bottom edge and could not be reached at
#       all — both default-sort dropdowns, the cursor-trace tick and its
#       "Open the log…" button, both Task Queue ticks, the backup folder box
#       and its browse button, Size grouping, reader extensions, "the built-in
#       reader (F3) can EDIT and save", and "Colour completely-empty folders
#       differently".
#   [x] Rebuilt on the SAME canvas + scrollbar scaffold the Transfers tab uses.
#       The inner frame keeps the name tab_gen, so the ~570 lines that build the
#       tab are untouched; the scrollbar is packed BEFORE the canvas, or the
#       expanding canvas would leave it 1px wide ([[tk-packer-scrollbar-trap]]
#       again — the same trap that hid Save in revAU).
#   [x] The wheel helper now takes its handler as an argument and binds BOTH
#       scrolling tabs.  It deliberately SKIPS Spinbox and Combobox: those
#       scroll their own value on the wheel, and silently changing a setting
#       while scrolling past it is worse than not scrolling.  Still bound widget
#       by widget rather than bind_all, which would take the wheel away from the
#       rest of the program.
#   [x] Measured after: nothing is cut off on any tab, the scrollregion is the
#       full 1902px, and the scrollbar reports 17px wide and mapped.  Nothing
#       moves or redraws on its own — the tab is static until you scroll it
#       ([[blink-sensitivity]]).
#
# DONE (2026-09-03 revision AU — Settings had no Save button):
#   [x] REPORTED: "I see no save button when I change the F3/F4 program.  The
#       lowest thing is update."  Save and Cancel were not missing — they were
#       never DRAWN.  pack hands out space in the order slaves were packed, not
#       in screen order.  _show_settings packs the notebook first with
#       expand=True and the shared button row a thousand lines later, and the
#       height cap at the end of the function makes the window shorter than the
#       tallest tab wants (measured: 1953px wanted, 940px of desktop on a 1080p
#       screen).  So the notebook took all 928 available pixels and the button
#       row was left 1 pixel tall with winfo_ismapped() == 0.  The last control
#       on screen was "Add / update" — the opener-list button INSIDE the Custom
#       openers tab, which saves nothing but that one line.
#   [x] FIXED: the button row is packed FIRST, side="bottom", and the notebook
#       is then re-packed after it (nb.pack_configure(after=btn_row)) so the
#       notebook is last in line and takes what is left instead of everything.
#       Measured after: footer mapped=1, h=41, Save at y=899 of a 940px window,
#       and every control on the Custom openers tab still fits (tab wants 831,
#       gets 861).  Escape and the window ✕ still cancel as before.
#   [ ] STILL OPEN, same cause, different tab: the General tab wants 1874px in
#       an 861px slot and does NOT scroll, so 12 controls sit below the edge and
#       cannot be reached at all — both default-sort dropdowns, the cursor-trace
#       tick and its "Open the log…" button, both Task Queue ticks, the backup
#       folder box and its browse button, the Size-grouping tick, the reader
#       extensions box, "the built-in reader (F3) can EDIT and save", and
#       "Colour completely-empty folders differently".  The Transfers tab
#       already has the canvas + wheel pattern to copy (see _thr_wheel).
#
# DONE (2026-09-03 revision AT — you could not click a profile's tabs away):
#   [x] REPORTED: "today (maybe always) I cannot click away tabs from
#       profiles".  Not a bug — a lock sitting on the wrong thing.
#       _render_tab_bar drew the close cross only when
#           can_close = len(tabs) > 1 and (not ws_active or is_temp or unlocked)
#       so the moment a Workspace was loaded on that side, every base tab of it
#       lost its cross entirely.  The only way out was the "Unlock saved tabs"
#       tickbox out on the Workspace bar — obvious once you know, invisible if
#       you do not.  And it guarded nothing: _close_tab never rewrites a saved
#       Workspace's base list (only an explicit Save / Update does), so closing
#       a profile tab was already harmless.
#   [x] THE CROSS IS GONE from the tab strip, on his instruction ("I see no X
#       now, so remove them completely").  It was an 8-pixel target one
#       millimetre from the tab you meant to click.
#   [x] Closing lives in the tab's RIGHT-CLICK menu now: "Close this tab",
#       "Close the OTHER tabs on this side (n)" and "Close the tabs to the
#       RIGHT (n)".  The two bulk items count what they will actually take,
#       skip locked tabs, and ask once before acting.  Ctrl+W is unchanged.
#   [x] Protection is a per-tab LOCK you set yourself: right-click a tab and
#       pick "Lock this tab".  A locked tab shows a padlock and a steady gold
#       border and refuses to close by any route.  It has nothing to do with
#       which Workspace the tab belongs to — that still only decides the amber
#       "temporary" tint.
#   [x] The lock travels with the Workspace: new keys <side>_lock and
#       <side>_extra_lock, written by Save, by Update, by the debounced tab
#       order save and by the half-save, read back by _ws_load.  An older
#       workspaces.json simply has no lock lists and loads all-unlocked.
#   [x] "Unlock saved tabs" on the Workspace bar became "Ignore tab locks" —
#       same variable, honest name: locked tabs close anyway while it is
#       ticked, and the locks themselves are left alone.
#
# DONE (2026-09-02 revision AR — why opening anything of his own was slow,
#                                and a watch that says when a program has
#                                fallen behind its source):
#   [x] MEASURED, not guessed.  "It can take MINUTES to open a PDF.  An MP3
#       takes 20 seconds."  Three checks before a line was written:
#         • os.startfile() is ASYNCHRONOUS — it returns as soon as the shell
#           has started the process.  Whatever you wait after that belongs to
#           the program being started, not to this one.
#         • the Windows associations on this machine ALREADY run the right
#           program directly — .pdf is 'PDFull.exe "%1"'.  There is no detour
#           to remove: "let the file manager start the program and hand it the
#           file" is exactly what already happens.
#         • nine of his ten programs are PyInstaller ONE-FILE builds.  A
#           one-file .exe is a self-extracting archive: EVERY launch unpacks
#           the whole bundle into %TEMP%/_MEIxxxxxx before the program runs,
#           and the scanner then reads everything just written.  A left-over
#           _MEI folder in TEMP proved it.
#       Then the same script was built BOTH ways and timed:
#           one-file    13.7 MB exe                 startup 1075 ms
#           one-folder   3.1 MB exe + data folder   startup  104 ms
#       Ten times, on a bundle of only 14 MB, and the gap grows with size.
#       PDFull is 171 MB and WhyBrowse 197 MB.  The size of the bundle IS the
#       startup time, and it is paid on every launch from anywhere — Tower,
#       the desktop, a double-click here.
#
#   [x] REMOVED AGAIN: the first attempt (revAQ) added a table that opened
#       your file types with the .py instead of the .exe, which dodges the
#       unpacking but leaves the actual programs slow everywhere else.  Issu's
#       call, and the right one: fix the builds, do not route around them.
#       Every trace of that route is gone.
#
#   [x] ADDED: SETTINGS ▸ MY PROGRAMS — the build watch.  "Is the program I
#       run still the program I wrote?"  It compares each source .py against
#       the program built from it and reports two things: sources that have
#       moved on since their build, and programs still built ONE-FILE.
#         • IT NEVER BUILDS ANYTHING.  Building is minutes of work and
#           hundreds of megabytes, and a build that dies halfway leaves a
#           program that will not start — that does not belong behind a file
#           manager's Save button.  It writes the build list out instead, for
#           Exe-bygg, whose job that is.
#         • Each generated line carries --contents-directory "<Name>_data".
#           That matters: Exe-bygg hard-codes --contents-directory "." (line
#           438), and with "." two one-folder programs built into the same
#           folder write their DLLs on top of each other.  Its own payload
#           folder is what lets an .exe keep sitting exactly where the
#           associations, Tower and every shortcut already point at it.
#         • A one-folder build is judged by its NEWEST file, not by the .exe
#           stub — the stub often does not change when only the payload does,
#           which would have made every rebuild look like no rebuild at all.
#         • 1---Blandat holds 130 .py files and only a handful are programs,
#           so nothing is watched until you tick it ("Watch everything already
#           built" ticks the obvious ones in one go).
#         • The startup check runs on a worker thread a few seconds in, says
#           ONE status line, and says nothing at all when there is nothing to
#           say.  Nothing pops up and nothing blinks.
#
#       ONE-FOLDER IS NOT FOR EVERYTHING.  Build one-folder for what you RUN
#       and zip that folder for what you SHIP.  A one-file .exe only looks
#       tidier: it charges you the unpacking on every launch, for ever, to
#       save whoever you gave it to a single unzip, once.
#
# DONE (2026-09-02 revision AP — the Home key was the culprit all along, and
#                                there is now a log so the next one is not a
#                                guessing game):
#   [x] FIXED: THE HOME KEY, PRESSED ONCE, JUMPED TO THE FIRST FILE.  This is
#       the real "I start programs when I want PARENT", and it took him saying
#       "instead of Enter I sometimes press Home, and the cursor moves to the
#       top file... sometimes" to find it.  Home has a "Home, Home" move: press
#       it a SECOND time, standing on the first row, and the cursor drops past
#       the folders to the topmost FILE.  The test for "second time" was "is
#       the cursor already on row 0?" — which is not the same question.  After
#       a Tab into a panel that is standing on the ".." dots the cursor is
#       ALREADY on row 0, so the very FIRST Home press counted as the second
#       one and jumped to the first file below "..".  Press Enter after that
#       and you have started a program when you meant to go up a level.  It now
#       takes a real previous HOME PRESS — recent (5 s) and still standing on
#       the same row — and every other way of placing the cursor (Tab, a click,
#       entering a folder) clears that stamp.  Measured before and after: one
#       Home press after Tab landed on prog00.py before, stays on ".." now,
#       while the genuine second and third presses still do exactly what they
#       always did.
#
#   [x] ADDED: THE CURSOR TRACE LOG — Helpfiles/0---Empty/
#       File_manager_cursor.log, ON BY DEFAULT.  Three separate causes for
#       "the cursor is not where I left it" had already been found by reading
#       the code, and it still happened, so the guessing stops here.  Every
#       call that can move a panel cursor writes ONE line, and the line holds
#       the full state of BOTH panels at that moment: which row is blue (s=),
#       where the keyboard cursor is (f=), which row is weakly marked (g=),
#       how many are marked (m), the cursor pin and its age, and how many rows
#       the list has.  Tab, clicks, activation, promote/demote, every rebuild
#       (with WHICH branch picked the row — via=pin / dotdot / same-name /
#       same-position / DEFAULT-CURSOR), the folder watcher firing, copy and
#       move, the Home key, and Enter itself — which prints what it is about
#       to act on and shouts if the selection and the keyboard cursor
#       disagree.  Reading a line:
#
#         ENTER-KEY [on_enter_key:10889] *L A s=.. f=.. g=- m0 pin=..(0.2s) n=10
#          ^event    ^which code          ^^ ^  ^    ^    ^
#          |         |                    || |  |    |    `- weakly-marked row
#          |         |                    || |  |    `- tree.focus()
#          |         |                    || |  `- the blue selection
#          |         |                    || `- folder the panel is in
#          |         |                    |`- which panel
#          |         |                    `- "*" = the ACTIVE panel
#          |         `- method:line doing it
#          `- what happened
#
#       It prunes itself: anything older than trace_hours (default 48) is
#       dropped at startup and again every half hour, with a 40 MB hard cap as
#       a backstop so a runaway loop can never fill the disk.  Costs 0.03 ms a
#       line, measured.  Settings ▸ General ▸ "Cursor trace log" turns it off
#       or changes the window; NET ▾ menu ▸ "Cursor trace log…" opens it.
#
# DONE (2026-08-31 revision AO — the cursor stays where you put it, the
#                                clash bar answers to Enter, and a phone
#                                actually receives files):
#   [x] FIXED: "I move a file from right to left, Tab to the left panel, the
#       .. row goes from grey to blue, I press Enter — and I am on a FILE a
#       little below ..".  Three separate faults, all in the same place:
#         • DEMOTING A PANEL TWICE ERASED ITS GREY CURSOR.  _demote_panel
#           stripped every inactive_sel tag and then re-added one from the
#           panel selection — which the FIRST demote had already cleared, so
#           the second pass left no cursor mark at all.  That happens all the
#           time: change_directory() calls focus_set(), whose FocusIn demotes
#           the other side, and the next Tab demotes it again.  A panel with
#           no selection still has a keyboard cursor (tree.focus), so that row
#           is what gets greyed now, and demoting is idempotent.
#         • _panel_default_cursor REFUSED to answer "..".  It was written to
#           avoid landing on the parent dots, which is right when there is no
#           cursor at all — but it also overrode a cursor that was DELIBERATELY
#           on "..", sliding it down onto the first file.  That is the file
#           just below .. that Enter kept opening.  It now returns the row the
#           keyboard cursor is already on, dots included, before falling back.
#         • THE AUTO-REFRESH POLL COULD MOVE THE CURSOR BETWEEN TAB AND ENTER.
#           It rebuilds the whole list every 1.5 s, and a rebuild that landed
#           in that gap re-derived the cursor from scratch.  Every deliberate
#           cursor placement (Tab, a click, entering a folder) now leaves a
#           PIN — the row name plus a timestamp, good for two seconds — and a
#           rebuild honours it.  Moving the cursor by hand drops the pin at
#           once, so it can never drag you back.
#       On top of that, _promote_panel now guarantees the invariant that was
#       missing: the blue row, the keyboard cursor and the row Enter acts on
#       are one and the same, it is scrolled into view, and no grey ghost row
#       is left sitting beside it.
#
#   [x] ADDED: A KEY FOR THE PARENT FOLDER — BACKSPACE (and Alt+Up).  There
#       was none at all.  The only ways up were the toolbar ↑ and pressing
#       Enter on the ".." row, so going up meant AIMING at one exact row, and
#       every miss RAN whatever the cursor happened to be on.  Reported as "I
#       start programs all the time, when I want PARENT" — and that is the
#       real cause of it, not the cursor logic.  Backspace is the Total
#       Commander key and is rebindable (Settings ▸ Configure shortcuts, "Go
#       up one directory (parent)"); Alt+Up is the Explorer one and is bound
#       as a fixed extra.  Both are ignored while the keyboard is in a rename
#       box or any other text field, so Backspace still deletes a character
#       there.
#
#   [x] FIXED: THE WEAKLY-MARKED ROW IS NOW, BY CONSTRUCTION, THE ROW TAB
#       TURNS BLUE.  That is the rule the whole thing rests on, and it used to
#       be maintained in three separate places — demote, refresh, and the
#       post-copy clean-up — which could disagree.  When they disagreed the
#       row that lit up on Tab was not the row you had been looking at.  One
#       helper, _sync_inactive_cursor(), now owns it and guarantees: an
#       inactive panel shows EXACTLY ONE grey row, tree.focus() points at that
#       same row, and no real (blue) selection is left over on the inactive
#       side.  A marked (red) row keeps its own colour and is never greyed —
#       the red already says where it is.  Verified by hammering it: 12 rounds
#       of park-the-cursor / leave / disrupt / Tab-back, across four different
#       kinds of disruption, demanding grey == blue == focus every time.
#       MEASURED, old build vs new, same harness: ONE extra interaction with
#       the already-active panel (a click, a FocusIn, opening the drive menu —
#       anything that re-activates the side you are already on) wiped the other
#       panel grey cursor, and Tab then landed on the FIRST FILE BELOW ".." —
#       5 of 5 rounds wrong before, 0 of 5 after.  The reason it only bit
#       roughly every fourth time in real use is that the auto-refresh poll
#       PUTS THE GREY BACK, so whether you got caught depended on whether a
#       poll happened to run between your last click and your Tab.
#
#   [x] CHANGED: THE NAME-CLASH BAR NOW ARMS ITS FIRST ANSWER.  It was built
#       to keep its hands off the keyboard so the arrows stayed in the file
#       list; the cost was that answering it always meant the mouse or a
#       three-key chord.  When it appears the keyboard cursor now lands on
#       "1  Overwrite old", so a plain ENTER answers it; ←/→ walk along the
#       row and wrap round the ends, Home/End jump to either end, and Esc —
#       or ↑/↓ — hands the keyboard straight back to the file list.  The armed
#       choice is drawn white-on-solid (static; nothing blinks).  "⚖ Always do
#       this here…" is the last stop on the ring; ✖ Cancel-the-job stays a
#       deliberate mouse click.  With several jobs waiting the bar re-arms
#       after each answer, so a run of clashes is a run of Enters.  It never
#       grabs the keys while you are typing in a rename box or a dialog field,
#       and Ctrl+Alt+1…5 still work from anywhere.  Settings ▸ General ▸ "The
#       bar arms its first answer" turns it off for the old behaviour.
#
#   [x] FIXED: PHONES / PORTABLE DEVICES RECEIVED NOTHING.  "Copy to here"
#       looked like it started and then nothing happened.  Folder.CopyHere()
#       and MoveHere() are ASYNCHRONOUS — they hand the job to the shell and
#       return at once — and every transfer here runs on a worker thread that
#       called CoInitialize().  The thread was dying the moment CopyHere
#       returned, and a single-threaded apartment going away takes the copy it
#       started with it.  Nothing was ever transferred, yet the status line
#       said "Handed to Windows — watch its copy dialog", so there was nothing
#       to see and nothing to blame.  The transfer now stays on its thread,
#       PUMPS the apartment message queue (an STA that does not pump deadlocks
#       the shell own callbacks) and watches the destination until the item
#       lands — growing a local file, or appearing on the device.  The clock
#       is pushed forward whenever something actually happens, so a big file
#       gets all the time it needs while a genuinely stuck transfer still
#       gives up.  The same fault, and the same fix, applied to Move-to-panel,
#       Move-to-device and Delete-on-device.
#
#   [x] FIXED: the tally is now checked instead of assumed.  A batch where the
#       shell quietly refused every file used to report success; it now says
#       how many of how many made it, names what was not found and what never
#       arrived, and points at the usual cause (a locked phone, or one plugged
#       in as "Charging only").  One transfer at a time, too — they are real
#       blocking work now, so a second click while one is running is refused
#       instead of starting a second transfer on the same device.
#
#   [x] FIXED: "I mark files in the LEFT panel, click Copy to here, and it
#       tells me to mark them in the RIGHT panel."  The window was tied for
#       ever to whichever panel happened to be active when it opened, and said
#       so only in that error.  It now has a Panel: ◀ Left / Right ▶ switch at
#       the top right, and if the chosen side has nothing marked while the
#       other one does, it takes the files from there and moves the switch to
#       match — so it follows the files instead of arguing about them.  Every
#       confirmation now names the panel it is about to use.
#
# DONE (2026-08-29 revision AN — every drive remembers where you were, and the
#                                name-clash question is answerable three ways):
#   [x] ADDED: DRIVE MEMORY.  Going to an external drive, off to another one,
#       and back again always dropped you in the ROOT — every single time, so
#       the whole walk down had to be repeated.  Each panel now records the
#       folder it stands in per VOLUME (the left and right panel remember
#       separately), and picking that volume from the drive menu goes straight
#       back there.  The drive menu SAYS where it will go ("D:  💾 Backup
#       ⤷ Photos/2026" — this header is one big docstring, so no backslashes
#       in it), the ↖ toolbar button still jumps to the real root, a
#       folder that no longer exists falls back to the root, and the memory
#       survives a restart.  Off in Settings ▸ General ▸ Navigation.
#       "⇉ Same folder as other panel" deliberately ignores the memory — it
#       means the OTHER PANEL's folder, not a remembered one.
#
#   [x] FIXED: "the task-queue button gets marked, but not clearly, and the
#       queue does not come up — and when it does it takes my arrow keys."
#       Both halves of that, and neither answer forced on you:
#       Settings ▸ General ▸ "When a copy hits a name clash" now has three
#       ways, because which one is right depends on what you are doing:
#         • BAR (new, default) — a red strip inside the MAIN window, above the
#           status bar.  It names the file, shows both sizes and dates and
#           says which is newer, and carries the five answers as buttons.  It
#           is part of the file manager, so it can never cover the panels,
#           never end up behind another program, and NEVER takes the keyboard:
#           the arrow keys stay in the file list the whole time it is up.
#           Ctrl+Alt+1…5 answer it without the mouse.  It does not blink.
#         • DIALOG — the old stop-and-ask, one file at a time.  Nothing is
#           ever missed; it interrupts.
#         • QUEUE — the quiet way: the job waits and the ⚡ button becomes a
#           bold red "⚠1 ANSWER" (it used to be a grey ⚠ that looked like the
#           grey ⚡ it replaced — that was the "not so clearly" part).
#
#   [x] ADDED: two ways to be ASKED LESS without freezing one answer for ever:
#         • "Do not ask when the two files are identical" (same size AND same
#           date).  Off by default.  Such a file is skipped silently — nothing
#           is overwritten and nothing is lost, because what is there IS the
#           file being copied.  Folders are never treated this way.
#         • A saved auto-rule can now be written down one, two or three
#           folders UP, or for any folder at all — set for the source and the
#           destination separately, in the Task Queue's ⚖ Auto-rule bar and as
#           a default in Settings.  A rule always covered its sub-folders; the
#           problem was that saving into a working folder makes a NEW dated
#           sub-folder every day, so a rule on the exact folder was dead by
#           morning.  Saved "1 level up" the rule sits on the working folder
#           and covers every dated folder ever made under it.  Re-opening the
#           queue finds a widened rule and puts the pickers back where it is,
#           so changing the scope MOVES the rule instead of leaving a stale
#           narrow one beside it.  The rule editor grew a "▲ up" button per
#           path for the same job.  Rules can still be tied to one Workspace.
#
#   [x] FIXED: COPYING OUT OF A SUB-FOLDER INSIDE AN ARCHIVE BROUGHT THE
#       SUB-FOLDER WITH IT.  Standing in a zip's "Icons" folder, marking one
#       file and pressing F5 put  <destination>/Icons/<file>  there — the
#       folder came along uninvited.  Marking a FILE means the file; marking
#       the FOLDER (from outside it) is how you ask for the folder.
#       Every backend recreates a member's full archive-internal path, so the
#       folder you are STANDING IN is now stripped: archive_extract_members()
#       takes a strip_prefix, extracts into a scratch folder on the
#       destination's own volume (so lifting the files out is a rename, not a
#       second copy) and lifts what sits under the prefix up.  One code path
#       for zip / tar / 7z / rar / the 7-Zip fallback instead of five.
#       An existing folder at the destination is MERGED, not replaced; an
#       existing file is replaced, which is what the plain extract already did.
#
#   [x] CHANGED: UNPACK GOES TO THE OTHER PANEL — including archives found by
#       picking whole FOLDERS, which always extracted where they lay.  A
#       second drive unpacks far faster than the one being read from, and if
#       you do want them where they lie, that is one click away: point the
#       other panel at that folder.  An archive picked by name already went to
#       the other panel and still does.  When the other panel is on FTP or
#       inside an archive it is no destination: folder-found archives fall
#       back to where they lie, by-name archives to this side, and the
#       confirmation says which.  Settings ▸ Transfers ▸ Unpacking turns the
#       whole thing back to the old behaviour.
#
#   [x] FIXED: THE RELOCATOR SAID "nothing" AND NEVER SAID WHY.
#       Reported as "F(re)email.exe matches nothing — the brackets?".  It is
#       not the brackets: fnmatch escapes round ones, and the pattern always
#       matched.  The real reason was the "newer" rule's own rule — a file is
#       only sent when the destination ALREADY HAS an older copy to be newer
#       than — so the FIRST build of a program is skipped however exactly its
#       name is spelled.  Three things, so this cannot bite again:
#         • Every rule that comes back empty now says WHY, in words, on its own
#           line in the ⤴ popup:  "1 file(s) matched, but the destination has
#           no copy of it yet — tick …".  Also covers: the copy over there is
#           already as new, outside the age limits, nothing answers to the
#           pattern, source folder missing, source == destination.  The line
#           only takes up room when there IS one.
#         • The tick that decides this ("Also send files the other folder does
#           not have at all") lived at the bottom of the RETIRE box, under a
#           heading about where the replaced copy goes.  It picks which files
#           travel, so it now has its own heading — "Files the destination does
#           not have at all ▸ Also send those" — with the consequence spelled
#           out both ways round.
#         • A pattern that IS a whole filename now matches that filename
#           literally as well as through fnmatch.  Round brackets were never
#           the problem, but square ones are a character class, so a rule
#           naming a real  Report[2].exe  matched nothing and said nothing.
#           Wildcards are untouched — this only ever matches more, never less.
#
#   [x] FIXED (found while testing the above): A SMALL JOB COULD BE ANSWERED
#       AND THEN NEVER RUN.  Answering a name clash woke the big lane only,
#       and almost every job is a small one, which lives in the FAST lane —
#       so the queue sat there looking idle with the work still in it.  On top
#       of that the fast worker had a lost-wakeup race: between deciding it
#       had nothing to do and lowering its "I am running" flag, anything that
#       queued a job was told a worker already existed — the very thread that
#       was leaving.  Both closed: resolving a clash wakes both lanes, and the
#       fast worker looks once more after the flag is down.
#
# DONE (2026-08-25 revision AM — the queue could be neither steered nor
#                                trusted, and it copied at a third speed):
#   [x] FIXED, and this was the bad one: A JOB COULD OVERTAKE AN EARLIER JOB
#       HOLDING THE SAME FILE.
#           queue  COPY  film.mkv  1 → 2      (waits, something big is running)
#           queue  MOVE  film.mkv  1 → 3      (instant, so it jumped the queue)
#       A same-drive move is a rename, which the sort scores as free (1.0) and
#       a copy as expensive (5.0) — so the move went first, film.mkv left
#       folder 1, and the copy that was asked for FIRST had nothing to copy.
#       Now: same file = first come, first served, whatever it costs.  It is
#       enforced where the jobs are STARTED, in both lanes — the fast lane was
#       where the overtaking actually happened, running alongside the big
#       transfer — and again in the sort, so the list shows the true order
#       instead of a promise it will not keep.  Jobs that share nothing are
#       reordered as freely as before.  A folder counts as holding the files
#       inside it.
#   [x] FIXED: "I cannot remove anything, I cannot reorder anything" — the
#       ↑ ↓ 🔒 ✖ row was PACKED LAST, under a list that takes all the space
#       it can get.  With a job running (progress strip) and a clash parked
#       (conflict banner) the whole row was allocated ONE PIXEL: the buttons
#       existed and were simply never on screen.  Packed from the bottom now,
#       with a minimum window size so it cannot be squeezed away again, and
#       the window opens at 820x560 instead of 780x400.  (Close had the same
#       fault sideways — a long hint label ate its width.)
#   [x] NEW: 🗑 Remove — take jobs OUT of the list.  ✖ Cancel leaves the row
#       sitting there marked ✖, which is no help when the list holds two jobs
#       you queued by mistake.  Several rows can be picked at once (the list
#       was single-select), Del does the same, and the job that is RUNNING is
#       never pulled out from under itself.
#   [x] NEW: the list says WHY a job is not moving — "⏳ after #2" when an
#       earlier job holds the same file, and "⧉ same as #2" when you have
#       queued the very same thing twice (he did, hoping it would jump).
#   [x] FIXED: A 12 GB COPY RAN AT ROUGHLY A THIRD OF THE DISK'S SPEED.  The
#       throttle that keeps the machine usable started after 5 seconds on one
#       file (→60%), tightened after 15 (→30%), and capped the whole job after
#       30 (→50%).  A 6 GB file is past all three before it has begun, so the
#       caps applied to practically the whole transfer — measured here at 2.9x
#       slower than the same copy unthrottled.  The thresholds now arrive LATE
#       and stay GENTLE (60s → 80%, 5min → 60%, 10min → 70%), there are three
#       ready-made presets in Settings ▸ Transfers (⚡ Full speed · 🙂 Polite ·
#       🐢 Background — Background IS the old behaviour), and a one-time
#       migration lifts a settings file that still carries the old numbers.
#   [x] NEW: read-ahead.  One thread reads the next block while the other
#       writes the last, instead of the two taking turns on one thread, and
#       the block is 4 MB rather than 1.  Source and destination are nearly
#       always different devices, so this is time that was simply being spent
#       waiting.
#   [x] NEW: the progress bar MOVES during a big file.  It counted FILES, so
#       two 6 GB files meant 1/2 … 2/2 with nothing in between — and no speed
#       and no ETA either.  Bytes are now reported per block, with MB/s.
#   [x] NEW: a line in the MAIN window's status bar while the queue works —
#       what is moving, how far, how fast, how long left, and how many jobs
#       are behind it.  It takes itself away the moment the queue is quiet.
#       ("It ends up in the Task queue, but I do not see the task queue.")
#   [x] NEW: Alt+F9 ON FOLDERS.  Mark one or several folders and every archive
#       inside them is queued — Unpacker's drag-a-folder-in, without the
#       dragging.  Those extract WHERE THEY LIE (sub-folders included), while
#       an archive picked by name still goes to the other panel as before.  A
#       split set is still one job.  The Task Queue shows itself when an
#       unpack is queued (Settings ▸ Transfers ▸ Unpacking to turn that off).
#   [x] FIXED: "rename the folder to UNPACKED-…" did not know the prefix his
#       own FTP flow writes.  DOWNLOADING- was stripped, DOWNLOADED- was not,
#       so the folder he most wanted marked became
#       UNPACKED-DOWNLOADED-Some.Film.2026 — stacked instead of replaced.
#       (Still off unless asked for: Settings ▸ Transfers ▸ Unpacking.)
#
# DONE (2026-08-25 revision AL — "Run all" runs the rules IN ORDER, one at a
#                                time, each one looking again for itself):
#   [x] FIXED: "Run all" scanned EVERY rule first and then threw the whole lot
#       into the Task Queue at once, so every rule saw the folders as they were
#       BEFORE any rule had run.  A CHAIN of rules could therefore never work:
#           1.  dist      →  Exe-redo
#           2.  Exe-redo  →  1---Blandat
#       Rule 2 looked in Exe-redo before rule 1 had put anything there, found
#       nothing, and the only way through was to run each rule by hand.
#       The rules now run ONE AT A TIME, top to bottom: a rule is started, the
#       queue is allowed to FINISH it, and only then is the next rule looked at
#       — with fresh eyes.  A rule is re-scanned only when a rule before it
#       actually moved something; while nothing has changed, the count already
#       taken still stands (no folder is read twice for nothing).
#   [x] NEW: THE ORDER IS YOURS.  ▲ / ▼ beside every rule — in the ⤴ popup and
#       in the rules window — move it up and down, and the list is numbered
#       1., 2., 3. …  That number IS the running order, and it is what the
#       rules file remembers.
#   [x] NEW: a small "Relocator — running" window follows the chain: one line
#       per rule, ▶ while it works, ✓ when it is through, "— nothing" when it
#       had nothing to take, and a "⏹ Stop after this rule" button.  Closing
#       the window does not stop anything — the chain reports to the status bar
#       instead.  If the queue parks a job (a name clash it must ask about) the
#       chain WAITS for the answer rather than starting the next rule too early.
#
# DONE (2026-08-23 revision AK — unpacking grew up: Unpacker can retire):
#   [x] FIXED: the queued unpack was ZIP-ONLY.  _run_unpack() opened
#       zipfile.ZipFile, so "unpack in the background" meant zip and nothing
#       else, while the all-format F10 ran outside the queue in its own
#       progress box.  Both now go through the SAME queue task, which uses
#       archive_extract() — every format the program reads.
#   [x] NEW: SPLIT ARCHIVES ARE ONE JOB (DEL 20b).  movie.rar + .r00…r42,
#       film.part01.rar…, big.7z.001…, pack.zip + .z01… — whichever piece you
#       select, the set is entered from its FIRST file, the size counts the
#       whole set, and dropping 43 pieces in makes one job, not 43.  A part is
#       an archive as far as F10 is concerned, but "notes.001" with nothing
#       around it is still just a file.
#   [x] NEW: IT WAITS FOR A DOWNLOAD TO FINISH instead of failing on a
#       half-arrived release.  An FTP client writes  movie.r37.part  while it
#       fetches that part; an .sfv in the folder, when there is one, is the
#       authority on what is still owed and names the missing files.  The job
#       stays PENDING with "⏳ movie.r37 is still on its way (14s)" in the
#       queue, looks again every N seconds and gives up after M minutes —
#       both in Settings ▸ Transfers ▸ Unpacking.
#   [x] NEW: a failed or cancelled extraction TAKES BACK EXACTLY WHAT IT
#       WROTE.  The destination is photographed first, so the clean-up can
#       never touch a file that was already there.
#   [x] NEW (both off unless asked for): put the files in a folder named after
#       the archive — unless the archive already brings one, so never
#       Film/Film/ — and afterwards move the archive (the WHOLE split set) to
#       the trash and/or rename the folder it came from to UNPACKED-… , with
#       the DOWNLOADING-/FETCHING- prefixes stripped rather than stacked.
#       Nothing is deleted outright: the archive goes to the same tiered trash
#       as the Del key and comes back the same way.
#   [x] NEW: ARJ, LZH/LHA, ACE, Z and .zipx are recognised at last — 7-Zip
#       could always read them; they were simply not on the list.
#       Ported from Issu's Unpacker, which this makes largely redundant: what
#       is left there is the drop-zone window itself and the smart video
#       rename (which his own config has switched off).
#
# DONE (2026-08-23 revision AJ — you could not MAKE a Relocator rule):
#   [x] FIXED: the ⤴ popup only offered "✎ Edit rules…", which reads as
#       "change what is already there" — so once the first rule existed there
#       was no visible way to make a new one (＋ New rule was one window
#       further in, and nothing said so).  The popup now has "＋ New rule"
#       right beside it, opening a blank rule editor.
#   [x] The empty state gained two more starters: the publish rule ("Files
#       NEWER than the copy over there → send them over") and a plain empty
#       rule, next to the two that were already there.
#
# DONE (2026-08-23 revision AI — the Yes/No boxes spoke Swedish):
#   [x] FIXED: every confirmation in the program answered JA / NEJ (and
#       Avbryt) instead of Yes / No.  tkinter's messagebox IS the Windows box,
#       so its buttons follow the SYSTEM language — nothing in the program's
#       own text was wrong, which is why it survived a dozen English sweeps.
#       All 41 askyesno() calls and the one askyesnocancel() now go through
#       _ask_yes_no() / _ask_yes_no_cancel(), built here: Enter answers Yes
#       (what the native box did), Escape answers No, Left/Right step between
#       the buttons, and the grab is handed back to the dialog underneath.
#       showinfo / showerror are deliberately left alone — their only button
#       reads OK in Swedish too.
#
# DONE (2026-08-23 revision AH — the Relocator learns to PUBLISH):
#   [x] NEW: a third rule kind — "Files NEWER than the copy over there".  The
#       mirror of the "superseded" rule: instead of sweeping the OLD copy away,
#       it sends the NEW one over.  Each file is compared with the one of the
#       same name at the destination and only travels if it is newer (by more
#       than a two-second slack, so a FAT timestamp cannot fake it).  A tick
#       adds "…and the ones the other folder has never seen at all".
#   [x] NEW: RETIRE THE COPY IT REPLACES.  Such a rule can name a third folder:
#       the file already at the destination is renamed Backup<code>- (the same
#       code pool as every other backup in the program) and MOVED there BEFORE
#       the new one lands.  That order is the whole point —
#         · there is a good copy at every instant, never a half-written one;
#         · Windows lets a RUNNING .exe be renamed but never overwritten, so
#           this is the only way to replace a program while it is open;
#         · nothing is deleted, so a bad build is one drag back.
#       The retire runs in a worker thread and the copy is only queued once it
#       is done — two queue tasks could be re-ordered (or overtaken by the fast
#       lane), which would put them in exactly the wrong order.  It goes into
#       the undo history as a move, and a file whose old copy could NOT be
#       moved aside (locked, in use) has its replacement SKIPPED and is
#       reported, rather than being written over.
#   [x] NEW: the age filter got its other half — "changed within the last N
#       days" beside "older than N days".  On  dist → Exe-Redo, *.exe  that is
#       the difference between 91 files (every build ever made) and 2 (the ones
#       rebuilt this week).
#       Together these make the build → stage → install chain two rules:
#         dist       →  Exe-Redo     ·  *.exe          ·  retire to Backup-radera
#         Exe-Redo   →  1---Blandat  ·  <the programs>  ·  retire to Backup-radera
#       Adding or dropping a program is one word in the Name pattern(s) box;
#       moving a folder is one of the three folder rows.
#
# DONE (2026-08-22 revision AG — the Customization tab, and the queue that
#       kept jumping in front):
#   [x] FIXED: the boxes in Settings had BLINKING carets.  They were
#       ttk.Spinbox / ttk.Entry, and those have no -insertofftime at all —
#       setting it through the ttk STYLE is accepted and then ignored
#       (measured: two photographs 0.2 s apart, the caret is still there in one
#       and gone in the other).  A ttk entry cannot be made steady after the
#       fact, so every one of them is now a classic tk widget built through
#       _mk_spinbox() / _mk_entry().  _no_blink() no longer swallows the
#       failure either — it writes a line in the log naming the widget, which
#       is how this crept in unnoticed in the first place.
#   [x] NEW: the "Columns" tab is now "CUSTOMIZATION", and holds a second
#       half: FILE COLOURS BY EXTENSION.  Sixteen ready-made groups
#       (executables, Python, source, web, config, text, documents,
#       spreadsheets, presentations, images, audio, video, archives, disc
#       images, subtitles, leftovers) — all shipped switched OFF, so the
#       default look is exactly the one that has always been there.  One
#       button ("Use the suggested colours") turns the lot on; every group can
#       be renamed, given any extensions you like and any colour (twenty
#       ready-made swatches, or the full Windows colour box), and "＋ Add a
#       group" makes new ones.  A live "example.py" beside each row shows what
#       it will look like, in the same white as the file list.
#       A colour LABEL (Ctrl+G) still wins over an extension colour, and the
#       folder blue, the red/purple marking colours and the grey inactive
#       cursor are never touched.  Colours apply on the next refresh, not at
#       the next start.  Saved in settings.json as ext_color_groups.
#   [x] FIXED: the Task Queue window POPPED IN FRONT of the file manager on
#       every copy where the name was already taken — which is most copies,
#       when the same programs keep going to the same folders.  It now stays
#       where it is: the ⚡ toolbar button turns into ⚠ with the count, and the
#       status line says what is waiting.  The old behaviour is one tick in
#       Settings ▸ General ("Bring the Task Queue window to the FRONT when a
#       job is waiting for you"), off by default.  That tick replaces the old
#       "Show the Task Queue window automatically on each copy / move / pack"
#       one, which NO CODE HAS EVER READ — it did nothing at all.
#       (A smart-queue conflict rule for a folder pair, or the new "(2)
#       suffix" answer, stops those jobs being parked in the first place.)
#
# DONE (2026-08-22 revision AF — the network batch: marked tabs, a queue that
#       no longer locks the program, the (2)-suffix answer, and the Relocator):
#   [x] NEW: NETWORK TABS ARE MARKED.  A tab pointing at a UNC path (the
#       two-backslash TOWER-Media kind) or at a mapped network drive is
#       drawn in teal and carries a 🌐 in its label — active or
#       not — with "Network location" in its hover text.  A mapped
#       drive letter is recognised through
#       GetDriveTypeW (DRIVE_REMOTE), cached per letter so a slow or absent
#       server can never hold up a repaint of the tab strip.  The amber "○"
#       temporary marking still wins on colour (that one is about losing the
#       tab); the globe is in the label either way.
#   [x] FIXED: THE PROGRAM LOCKED UP WHILE A COPY TO THE NETWORK DRIVE WAS
#       BEING QUEUED.  Queueing did two things on the MAIN thread: add up the
#       size of every source, and ask the destination whether each name was
#       already taken.  Both are one round trip PER FILE, so on a network
#       share the whole window stood still until the server had answered for
#       every one of them.  Now the task appears in the queue immediately,
#       marked "🔎 Checking…", and a worker thread does the measuring; nothing
#       runs the job until the answer is in, and the "file already exists"
#       alert is raised when the scan comes back rather than before it starts.
#       Free space is cached per volume for five seconds as well — smart_sort
#       asked the server for it once per pending task, twice a second, while
#       the queue was waiting for anything at all.
#   [x] FIXED: AFTER A MOUSE-CLICK RENAME THE ARROW KEYS WERE DEAD.  Choosing
#       "Backup-rename old" (or any other answer) in the clash dialog left the
#       row looking selected while the keyboard was nowhere — TAB TAB was the
#       only way back.  A Toplevel takes the keyboard and closing it does not
#       give it back, so the rename now puts the cursor on the file under
#       whatever name it ended up with and hands the list its focus.  Escaping
#       out of a rename does the same, and so does the F2 / right-click name
#       box (which goes through _refresh_and_refocus now, not refresh_panels).
#   [x] NEW: "SAME FILE, ONE (2) APART".  Copying  Notes (3).py  into a folder
#       that already holds  Notes.py  is not a name clash, so nothing used to
#       stop and ask — and the folder filled up with numbered near-duplicates
#       of the same program.  The queue now spots those on the way in and asks
#       ONCE per job: keep the old file as Backup<code>- and let the new one
#       take the plain name, replace the old one outright, or keep the (2).
#       The job is held until it is answered (a small file would otherwise be
#       through the fast lane first).  "Always do this, from this folder to
#       that one" remembers the answer per folder pair in twin_rules.json;
#       TOOLS ▾ ▸ "(2)-suffix answers…" lists them with a way out.
#   [x] NEW: THE RELOCATOR  ⤴  (DEL 50) — "these files, from here, belong
#       THERE", carried out through the Task Queue.  LEFT-click the arrow for
#       the list of rules with how many files each one would move right now
#       (counted off the UI thread) and a ▶ beside each; RIGHT-click it to run
#       every enabled rule at once.  Two kinds of rule:
#         • pattern     — wildcards, e.g.  Backup???-*  → the backup folder,
#                         or  Bildningspodden*.mp3  in Downloads → the podcast
#                         folder.  Optionally only files older than N days,
#                         optionally into sub-folders.
#         • superseded  — files in folder X that a NEWER copy in folder Y has
#                         replaced, matched by name with any " (3)" taken off,
#                         moved to folder Z.  (X is Temp, Y is where the
#                         Python files live, Z is where the old ones end up.)
#       A blank source folder means "wherever the active panel is", each rule
#       carries its own clash policy, and "drop the (2) on arrival" makes
#       Notes (3).py land as Notes.py.  Rules live in relocator.json; the
#       button also sits on Ctrl+Alt+X and in TOOLS ▾.
#   [x] NEW: a Workspace can be COPIED to a new name (right-click ▸
#       "Duplicate…").  The safe way to split one that has grown too many
#       tabs: duplicate it, then delete the Cubase tabs from one copy and the
#       VST tabs from the other.
#   [x] NEW: press HOME TWICE and the cursor drops to the topmost FILE — the
#       row just below the last folder — without leaving the Home key.  A
#       third press goes back to the top.  (Ctrl+Down still does it in one.)
#
# DONE (2026-08-19 revision AE — the zip-copy crash, and the ★ button
#       leaving both panels looking dead):
#   [x] FIXED: copying files OUT of a zip crashed the Tk callback with
#       "Item IAC6 not found" (logged 08:57, and once before on 2026-08-16
#       21:12 — an old fault, not something revAD introduced).
#       _refresh_archive_view() rebuilt the list but never renewed _marked,
#       so the red marks kept the iids of rows that had just been deleted.
#       Every NAVIGATION path inside an archive already cleared the marks
#       first; the one that did not was the IN-PLACE refresh — exactly the
#       one _archive_copy_done() runs, which then called
#       _clear_marks_and_selection() straight into the dead iids.
#       Now the archive view carries the marks across by NAME, the same way
#       refresh() has always done for a real folder.  On top of that,
#       _set_mark_tag / _clear_mark_tag — the choke point every mark repaint
#       goes through — simply do nothing when the row is gone, so no future
#       caller can bring the program down this way again.
#   [x] FIXED: pressing ★ left BOTH panels looking inactive, with the other
#       side's grey cursor row the loudest thing on screen.  Clicking a
#       ttk.Button moves the keyboard onto the button (ttk's own <Button-1>
#       binding runs `focus %W`, so -takefocus cannot stop it); the file list
#       loses its focus ring and ttk repaints its selection in the washed-out
#       unfocused colour.  The ★ action now refreshes through
#       _refresh_and_refocus() — the helper that already existed for exactly
#       this after a copy or move — so the keyboard goes straight back to the
#       active list and its <FocusIn> re-demotes the other panel.  The colour
#       labels (Tags menu) got the same treatment; a menu steals focus too.
#
# DONE (2026-08-19 revision AD — the ★ flag column):
#   [x] NEW: a ★ column of its own between Type and Size, and a ★ toolbar
#       button just before 🗑 that puts the tick on (or takes it off) every
#       selected file and folder.  Room for the button came from TOOLS ▾ /
#       NET ▾ / SEL ▾, which were all set wider than their own labels.
#       The point is the working folder you empty a bit at a time — send a
#       file off, tick it when it comes back, and the column shows what is
#       still outstanding without anything having to be deleted to keep
#       track.  An all-flagged selection is cleared by the same button; a
#       MIXED one is filled in, not inverted.
#       Clicking the ★ header sorts the flagged rows to the top, and the
#       Filter box learned  *  (only flagged) and  -*  (only unflagged).
#       Also on Ctrl+Alt+M and right-click → Tags → "Flag / unflag", with
#       "Clear ALL ★ flags…" in the same menu.
#       The flags live in the existing tags.json, INSIDE TagStore — which is
#       why they follow a rename or a move and disappear with the file for
#       free: every remap() / clear() / prune() call the program already
#       made now keeps them right too.  An existing toolbar.json is migrated
#       once so the button appears there as well.
#
# DONE (2026-08-16 revision AB — Shift+Page marks what it passes):
#   [x] FIXED: Shift+Page Up / Shift+Page Down jumped the cursor a big step
#       (CURSOR_JUMP_BIG rows) but left every file and folder it flew past
#       UNMARKED, so the natural "mark a screenful at a time" move did
#       nothing.  Now the whole travelled range is marked — the row you
#       started on, the row you land on, and everything between them — the
#       same rule Shift+Up / Shift+Down and Shift+Home / Shift+End already
#       follow (marks are only added, never taken away; Ctrl+N or numpad -
#       still clears them, and ".." is never marked).  Plain Page Up/Down
#       (one window-full) and Ctrl+Page (small jump) still only MOVE, so
#       there is still a way to page around without touching the marks.
#
# DONE (2026-08-16 revision AA — a click is not a drag, the drive letters
#        really answer, and the listing can be files-only / folders-only):
#   [x] FIXED: "Drag & Drop – error" popped up when all you did was CLICK a
#       file to give that panel the focus.  Two causes, both fixed:
#         • tkdnd starts a real drag after only THREE pixels of movement, so
#           the smallest hand tremor during a click became a drag-and-drop.
#           The threshold is now 12 px (_set_dnd_drag_threshold, applied to
#           ::tkdnd::_dx / _dy at start-up) — comfortably past ordinary
#           click jitter, still a fraction of a deliberate drag.
#         • letting go over the SAME list then ran a copy of every selected
#           file on top of itself — which is where the error came from, and
#           why it so often named a file another program had open.  A drop
#           back into the panel the drag started in is now simply ignored,
#           and so is any item that already lives in the destination folder
#           (Explorer behaves exactly the same way).  The status bar says
#           "Already in this folder — nothing to do." instead of a popup.
#   [x] While in there: a drop no longer copies with a blocking shutil loop.
#       It goes through the Task Queue like every other transfer, so name
#       clashes, locked files, progress, pause and cancel all work, and the
#       window cannot freeze on a big file dropped in from Explorer.
#   [x] FIXED: the Alt+F1 / Alt+F2 drive-letter shortcut added in revision Z
#       never actually worked.  Tk draws Windows menu entries ITSELF (every
#       item is owner-drawn — Windows holds an empty string for each one), so
#       Windows cannot match the typed letter; Tk answers WM_MENUCHAR and
#       looks the character up in the label as a UTF-16 array.  The disk
#       icons (💽 🖴 🖧 …) are non-BMP emoji = TWO UTF-16 units but ONE Python
#       character, so every underline sat one place to the left of the drive
#       letter and the key press did nothing.  _underline_at() now returns a
#       UTF-16 code-unit index, and the drive letter has moved to the FRONT
#       of the label ("C:\\  💽  Volume  —  … free"), where the index is 0 and
#       right whichever way it is counted.  Mapped network drives in the
#       "🖧 Network location" sub-menu were broken the same way and are fixed
#       the same way.
#   [x] NEW: Print / export listing can list FILES ONLY, FOLDERS ONLY, or both
#       ("Include:" radio row), instead of always both.
#   [x] NEW: after a successful print or export the marks in the panel are
#       cleared, so the next operation cannot silently inherit them.  There is
#       a checkbox for it ("Clear the marks after a successful print /
#       export", on by default) for when the same selection is exported in
#       several formats in a row.
#   [x] The Print / export window now remembers everything you chose last
#       time — format, columns, Include, recursion, selected-only.
#
# DONE (2026-08-10 revision Z — real clipboard paste, phone "copy to panel",
#        Move on/off a device, and letter shortcuts in the drive menu):
#   [x] FIXED: Ctrl+V never worked for files copied in Explorer (or any other
#       program) — this program only ever put path TEXT on the clipboard
#       (SEL ▾ "Copy paths to clipboard") and never read the clipboard at
#       all.  New clipboard_get_files() / clipboard_set_files() talk the same
#       CF_HDROP + "Preferred DropEffect" format Explorer itself uses (plain
#       ctypes, no pywin32 dependency).  Ctrl+C / Ctrl+X / Ctrl+V now behave
#       like they do everywhere else, in BOTH directions: paste something
#       copied in Explorer into a panel here, or copy/cut files here and
#       paste them into Explorer or anywhere else.  Only lower-case Ctrl+c is
#       bound — Ctrl+Shift+C stays "Compare files" (DEL 33), untouched.
#   [x] FIXED: "Copy to panel" in Phone / portable device (DEL 47) could fail
#       with an error naming the file, because mtp_copy_out() asked the
#       device for the item with folder.ParseName(name) and that call can
#       fail on some MTP names — a problem the folder-WALKING code already
#       had to work around (see _mtp_folder_for's fallback) but that the
#       actual file transfer never got.  New _mtp_item_by_name() carries the
#       same fallback and is now used everywhere an item is fetched by name.
#   [x] NEW: "Move to panel" / "Move from panel" buttons next to the existing
#       Copy ones in the Phone / portable device window — only Copy existed
#       before, so getting files off (or onto) a phone always left a spare
#       copy behind with no built-in way to remove it.  Same Shell.Application
#       engine as Copy, MoveHere instead of CopyHere (mtp_move_out /
#       mtp_move_in), so it behaves exactly like an Explorer drag with no key
#       held down.
#   [x] NEW: Alt+F1 / Alt+F2 drive menu — every entry that has a drive LETTER
#       (the plain disks, and mapped network drives) now underlines that
#       letter and answers to it as a Windows menu mnemonic: open the menu,
#       press "X", and it jumps straight to X: — without ever leaving the
#       key bound anywhere once the menu closes.
#   [x] NEW: numeric-keypad "*" toggles mark-all / unmark-all with one key,
#       Total-Commander style — on top of the existing separate Ctrl+A /
#       Ctrl+N, not instead of them.
#
# DONE (2026-08-08 revision Y — dragging a multi-selection no longer drops a
#        file into rename mode):
#   [x] FIXED: marking several files and dragging them to another program put
#       the bottom file into inline EDIT mode.  A click on an already-selected
#       row schedules the "slow double-click" rename 650 ms later, and nothing
#       cancelled that timer once a drag began — so it fired mid-drag, on the
#       row under the pointer.  Three guards now:
#         • no rename is scheduled at all while MORE THAN ONE row is selected
#           or marked (a multi-selection means you are about to act on them,
#           not rename one of them),
#         • the first real mouse movement with the button down cancels it
#           (<B1-Motion>, with a 4-pixel dead zone so ordinary click jitter
#           still counts as a slow click),
#         • the drag-source hook, leaving the list and losing focus all cancel
#           it too — dropping into another program can no longer leave an
#           edit box behind.
#       The single-file slow-click rename itself is unchanged.
#
# DONE (2026-08-08 revision X — the ⚖ newest/oldest comparison, and a file
#        that is IN USE is now a question, not a crash):
#   [x] NEW ⚖ "which one is newest?" toggle, between ⚡ and 🗑 (DEL 48).  Leave
#       it switched on: every file NAME present in BOTH panels is coloured
#       GREEN (this side is newer), RED (older), AMBER (same time but a
#       different size — changed without the date changing) or left alone
#       (same time, same size = unchanged).  Nothing is written; the colour
#       goes when the button pops out.  Folders are never coloured (a folder's
#       date says nothing about its contents), names on one side only are left
#       alone, and timestamps within 2 s count as equal (FAT resolution).
#       Re-runs itself whenever either panel changes.  State is remembered.
#   [x] FIXED (crash report from the user): a same-drive MOVE of a file another
#       program held open raised PermissionError [WinError 32] inside the
#       worker thread and killed the whole job.  Now:
#         • per-file errors are collected, never raised — one bad file cannot
#           stop a 500-file job,
#         • Windows error numbers become plain sentences ("the file is open in
#           another program — close it and try again", "the destination drive
#           is full", "the full path is too long for Windows"…),
#         • a LOCKED file during a move asks what to do (DEL 49): "Copy now,
#           delete the original later" / Try again / Skip / Abort, with "do the
#           same for the rest".  The copy-later route copies the file across
#           (locked files can normally still be READ) and queues the original
#           for removal the moment its program lets go — retried every 30 s and
#           on every start, persisted to delete_when_unlocked.json so it
#           survives a reboot, and only ever attempted while the copy exists,
#           so nothing can be lost.  TOOLS ▾ ▸ "🔒 Locked files waiting…".
#         • the job ends with a readable report of what it could not do,
#           instead of a crash box.
#   [x] Also fixed while testing: if the copy worker ever raised, done_evt was
#       never set and the QUEUE THREAD waited on it for ever — every later job
#       silently stopped.  The worker is now wrapped so the event is always
#       released, and a failed job reports itself.
#
# DONE (2026-08-08 revision W — fast lane for small files, and the crash +
#        wild flashing after resolving a file clash):
#   [x] FIXED the crash.  Resolving a name clash could set off a focus/raise
#       feedback loop: the queue's focus watchdog called focus_force() on the
#       MAIN window, which raised it over the pinned queue, which re-pinned
#       itself, which produced more focus events…  Everything flashed and the
#       process finally died with nothing in the log (a native-level death, so
#       no Python handler ever saw it).  Four things now make that impossible:
#         • the watchdog and the bounce do NOTHING while a modal dialog holds a
#           grab (fighting a modal dialog for focus was the tug-of-war),
#         • the bounce has a re-entrancy flag + a 400 ms cooldown, and only
#           pulls focus when THIS program is the foreground app,
#         • nothing re-raises the window from a focus path — WS_EX_TOPMOST is
#           sticky, so the re-raise was pointless as well as dangerous,
#         • a runaway guard un-pins the window if it is ever raised more than
#           12 times in half a second, instead of letting it escalate.
#   [x] FIXED: a modal dialog could end up BEHIND the pinned Task Queue — you
#       would be staring at a queue you could not use while an invisible dialog
#       held the grab.  Every modal Toplevel now un-pins any always-on-top
#       window while it lives (_modal_suspend_topmost) and the "File already
#       exists" dialog lifts itself on top.
#   [x] FIXED the flashing itself: the queue's three banner strips decided
#       whether to re-pack from winfo_ismapped(), which reports 0 whenever the
#       window is not viewable — so they were re-packed on EVERY refresh, and
#       every pack is a full relayout.  They now remember their own state and
#       move only on a real change, and refreshes are coalesced to 4 per second
#       instead of one per progress report.
#   [x] Native crashes now leave evidence: faulthandler writes to
#       Helpfiles/0---Empty/File_manager_fault.log, so a hard death (Tcl panic,
#       stack overflow, access violation) is no longer invisible.
#   [x] NEW — FAST LANE.  A copy/move under Settings ▸ Transfers ▸ "Counts as
#       small up to" (50 MB default) runs in its OWN worker alongside the big
#       transfer instead of queueing behind it, marked ⚡ in the list.  The big
#       job pauses while it slips past (optional), so the small file gets the
#       whole disk and is done in a blink.  A SAME-DRIVE MOVE always takes the
#       fast lane whatever its size — it is only a rename, so nothing travels.
#       Cancel is now per-task, so stopping a 9 GB copy no longer kills the
#       little file overtaking it.
#   [x] Drive menu: letter, then volume NAME, then free space and kind —
#       "D:  8 TB Backup 1  —  1200 GB free of 7452 GB  (Fixed)".
#       A drive with no volume label set in Windows has no name to show.
#
# DONE (2026-08-08 revision V — network locations you can PICK instead of type,
#        phones/MTP, cursor jumps, New-folder suggestion, queue on top, the
#        ".." cursor bug, F3 = F4):
#   [x] NETWORK: the drive menu's old "Network drive…" text box (blinking caret,
#       and you had to know the exact \\\\server\\share) is replaced by a "🖧
#       Network location" sub-menu that LISTS what exists — mapped drive
#       letters, saved favourites, and the last 15 network paths you opened —
#       plus "🔍 Find network locations…" (DEL 46): ARP quick-scan, ping sweep
#       of the local subnet, host names resolved in the background, and a
#       host's SMB shares listed when you expand it.  Double-click opens it in a
#       panel; right-click can map a drive letter or save a favourite.  The
#       manual path field is still there, now with a FIXED cursor.
#   [x] PHONES: a phone in MTP ("File transfer") mode gets no drive letter, so
#       it could never show up in a drive list.  New "📱 Phone / portable
#       device" sub-menu + device browser (DEL 47) reads them out of the Windows
#       shell namespace: walk the phone's folders, copy files off it into the
#       active panel, copy files onto it, or hand it to Explorer.  A built-in
#       "Why is my phone missing?" checklist covers the usual causes, and
#       removable drives (phones in USB-drive mode, card readers) are listed in
#       the same place.
#   [x] Drive menu now shows what KIND each drive is (Fixed / Removable /
#       Network / CD-DVD) plus the volume label, so two look-alike drives are
#       tellable apart.  Disk overview gained the same Type column.
#   [x] Ctrl+Down = jump to the FIRST FILE (past ".." and every folder), Ctrl+Up
#       = jump to the FIRST FOLDER.  Home/End go to the ends and Page moves a
#       window-full; neither could land on the file block.  Both rebindable.
#   [x] F7 New folder is PRE-FILLED with the name the cursor stands on (a file
#       contributes its name without the extension), pre-selected so typing
#       replaces it.
#   [x] Task Queue: new "📌 On top" tick (default ON, also in Settings ▸ General)
#       so the queue stays reachable instead of being buried under the file
#       manager — the reason it always looked "in the background even when I
#       activate it" was that handing the keyboard back pulled the MAIN window
#       forward on top of it.  Arrow keys still always belong to the file list.
#       The window is also dragged back on-screen if it was left off a monitor.
#   [x] FIXED: clicking a file after another program had focus could leave the
#       cursor on the ".." dots, so Enter went UP a level instead of opening the
#       file.  Cause: the panel-activation fallback selected row 0 (= ".."), and
#       an auto-refresh threw away the inactive panel's grey cursor tag.  Now
#       each panel remembers its cursor BY NAME, the fallback never picks "..",
#       the grey cursor survives a refresh, and a plain click re-asserts the row
#       you clicked on the next idle cycle.
#   [x] NEW SETTING "F3 uses the same external program as F4" (default ON):
#       when you have chosen your own viewer/editor it now serves BOTH keys;
#       the built-in reader is only used for types no program of yours covers.
#       Shift+Enter still forces the built-in reader.
#   [x] No-blink sweep: every remaining simpledialog.askstring() (rename, hotlist,
#       tags, toolbar captions, ZIP name, map-drive letter, FTP…) now goes through
#       one _ask_text() dialog with a FIXED caret — and it can offer ready-made
#       choices, which is what the map-drive box now does with the free letters.
#       Three Swedish docstrings translated; "Settings saved" popup now
#       auto-closes after 1 second like every other success popup.
#
# DONE (2026-08-02 revision U — two-blue-cursors fix, cancel/pause/throttle a
#        running transfer, safe cross-drive move, F8 toolbar button, queue
#        window no longer a phantom taskbar entry):
#   [x] CRITICAL: only ONE panel can show the dark-blue active cursor now.  Root
#       cause of moving a 9 GB file to the wrong drive twice: activating a panel
#       by MOUSE/FOCUS changed active_panel but did NOT demote the other panel's
#       real (dark-blue) selection, so BOTH looked active and F6 acted on the
#       wrong one.  All activation paths route through _activate_side(), which
#       always demotes the other panel; the inactive cursor is now a muted GREY.
#   [x] A running copy/move can be CANCELLED mid-file (even one huge file) and
#       PAUSED.  Files are now copied in BLOCKS (_copy_file_chunked) instead of
#       one uninterruptible shutil.copy2.  A cross-drive MOVE = chunked copy then
#       delete source, so Cancel removes the half-written destination and leaves
#       the ORIGINAL intact.  Same-drive move stays an instant os.replace.
#   [x] THROTTLE so a big job never hogs the machine: after a file has run a few
#       seconds its speed is capped (defaults 60%@5s, 30%@15s, whole job 50%@30s)
#       so other programs stay responsive.  Small files run full speed.  New
#       Settings ▸ Transfers tab; keys throttle_*.
#   [x] Toolbar: the "Del" button between F7 and F9 is now the F8 (tab-pair
#       cycle) button — Delete needs no button (the Del key still deletes).
#       DEFAULT_TOOLBAR updated + one-time migration of saved layouts.
#   [x] Task Queue window is now a TOOL window (WS_EX_TOOLWINDOW): no phantom
#       second entry in the Windows taskbar that could not be closed/shown.
#       Reach it with the ⚡ button.  Still never steals the keyboard.
#
# DONE (2026-08-02 revision T — open-with-modifiers model, built-in audio
#        player, "same folder as other panel" in the drive menu):
#   [x] REDESIGNED how a file opens on double-click / Enter, by modifier:
#         • plain  → the WINDOWS DEFAULT program (predictable; no surprise
#                    external launches).  An archive still browses into it; a
#                    type in the reader-extensions list opens the built-in viewer.
#         • SHIFT  → the built-in viewer / player, whatever the type.
#         • CTRL   → the per-type opener (Settings ▸ Custom openers); if none for
#                    that type, the built-in viewer.
#       The F4 PROGRAM is no longer fired by a plain double-click (that was why
#       adding an MP3 player made three copies pile up) — it stays on the F4 key.
#       Shared entry point EditorFrame._open_file_activated(path, shift, ctrl).
#   [x] NEW: a simple BUILT-IN AUDIO PLAYER (MP3/WAV/WMA/MID… via Windows' own
#       MCI/winmm — no dependency): Play/Pause/Stop, position slider, volume.
#       Joins the existing image/PDF/text viewer; unknown codecs fall back to an
#       "open in default program" button.  (Image viewer already existed.)
#   [x] NEW: Alt+F1 / Alt+F2 drive menu gained "⇉ Same folder as other panel"
#       — jump this panel to the exact folder (and drive) the other panel shows.
#
# DONE (2026-08-01 revision S — empty-folder colour, startup WS, no-popup WS
#        update, Shift+F4 2nd editor, F8 tab-pair cycle, status-bar redesign):
#   [x] Completely-empty folders (no files AND no sub-folders) are drawn in a
#       dim blue-grey instead of the normal folder blue, so they stand out.
#       Toggle / recolour in Settings ▸ General ▸ Display (mark_empty_dirs).
#   [x] Pick a Workspace to load on start: right-click a Workspace button ▸
#       "★ Start with this workspace" (a ★ marks it; click again to turn off).
#       Loads into both panels before the first paint, so no flash.
#   [x] "Update with current tabs…" popup replaced by THREE direct, no-popup
#       context-menu items: Update BOTH / LEFT / RIGHT panels with current tabs.
#   [x] Shift+F4 now opens a SECOND external program you choose (Settings ▸
#       Custom openers ▸ "Shift+F4 — second program"), e.g. a different editor.
#       With none set it falls back to the Windows association (old behaviour).
#       Toolbar hover tips now spell out Shift+F5 / Shift+F6 / Shift+F4 / Ctrl+F4.
#   [x] F8 (was a duplicate of Delete — Del still deletes) now CYCLES tab pairs:
#       a pair links a LEFT folder with a RIGHT folder (linked by ADDRESS, not
#       tab position, so it survives moving/reordering tabs and follows its
#       folder to whichever tab shows it); F8 jumps both panels at once.  Pair 1
#       = leftmost tab each side; make more by right-clicking a tab ▸ "🔗 Tab
#       pairs".  Closing a linked tab warns before breaking the pair — unless
#       another tab on that side shows the same folder (then silent).  "Manage /
#       clear pairs…" lists them and can drop the start pair out of the cycle.
#       Pairs are remembered per Workspace.
#   [x] Bottom status bar redesigned into three clear, self-labelled sections:
#       ◧ LEFT (its path · counts · free space), a middle "which side is active
#       + selected count", and ◨ RIGHT — active side tinted, so "which path?"
#       is never ambiguous and the right section is no longer a dead constant.
#
# DONE (2026-08-01 revision R — F4 program, editable F3 reader, folder sort override):
#   [x] NEW: F4 opens the program YOU pick, not whatever Windows once remembered.
#       Settings ▸ Custom openers ▸ "F4 — external program": program + optional
#       arguments (%1 = the file) + optional extension list (empty = all files).
#       Resolution order is per-extension opener → F4 program → Windows
#       association.  Shift+F4 = Windows association regardless; Ctrl+F4 = the
#       Windows "Open with…" box, which is the way OUT of a wrong association
#       picked by accident (Windows never asks twice on its own).
#   [x] NEW: the built-in F3 text reader can EDIT and SAVE.  Opens read-only
#       (✎ Edit / Ctrl+E unlocks, Ctrl+S saves), keeps the file's own encoding
#       AND line endings, writes via a temp file + os.replace so a failure can
#       never leave half a file, refuses to save a truncated (too-large) file,
#       warns before editing binary, and asks before discarding unsaved work.
#       Switch it off in Settings ▸ General to keep F3 strictly read-only.
#   [x] NEW (DEL 45): per-folder SORT OVERRIDE.  Right-click a folder (or the
#       empty space below the list = the folder you are in) ▸ "🔀 Sort override":
#       remember the sort you are using now, or pick a preset for files and for
#       sub-folders; optional "applies to sub-folders too"; a 🔀 next to the
#       column arrow shows it is in force; clicking a header inside such a
#       folder edits THAT override instead of looking like it did nothing.
#       "🗂 All folder overrides…" lists / removes them.  folder_sorts.json.
#
# DONE (2026-08-01 revision Q — rename-Enter, reader-list, cursor, Copy/Move As):
#   [x] BUG FIX: pressing Enter to COMMIT an inline rename also bubbled up to the
#       global <Return> binding and opened the file (F3) right afterwards.  The
#       rename box's Return/Escape now return "break", so Enter just commits.
#   [x] CHANGE: double-click / Enter no longer opens EVERY text/image/PDF in the
#       reader (so .py double-click runs again).  Only the extensions in a new
#       Settings field (default "nfo, txt") open in the reader; everything else
#       opens externally.  F3 = reader always, F4 = external always.
#   [x] After a COPY (not just a move) the red marks are dropped and the
#       selection collapses to a single clearly-visible cursor row — you see the
#       cursor, not a stale block of "still marked" files.
#   [x] NEW: Shift+F5 = Copy As…, Shift+F6 = Move As… — type the destination
#       (a full path+name for one item, or a target folder for many) first.
#
# DONE (2026-08-01 revision P — WS highlight fix, tab keys, grouped Size):
#   [x] BUG FIX: Shift+arrow Workspace cycling lit TWO buttons at once — the old
#       profile stayed highlighted on the panel it wasn't reloaded on.  Cycling
#       is now a WHOLE-profile switch (loads both panels) and force-clears any
#       stray active marker, so exactly one Workspace is highlighted.
#   [x] NEW: Ctrl+Left / Ctrl+Right switch to the previous / next tab on the
#       active panel (wraps).  Alt+Left / Alt+Right move the active tab to the
#       far left / far right (the "Most" positions from the tab right-click
#       menu).  Both are re-mappable in the shortcut editor.
#   [x] NEW: Settings ▸ General ▸ Display — "Group the Size column with spaces"
#       (default ON): 9133144 → "9 133 144 KB".  Sorting still treats it as a
#       number; the change applies immediately on Save.
#
# DONE (2026-08-01 revision O — built-in text reader, F3/F4 split, nav & WS keys):
#   [x] NEW: a simple built-in TEXT reader (read-only, fixed caret, wrap toggle,
#       encoding auto-detect, big-file cap).  It joins the existing image/PDF
#       viewer in one window class, so F3 / Enter / double-click open text,
#       image or PDF inline with no external app.  Any unknown/binary file is
#       shown best-effort as text so you can always "peek".
#   [x] F3 now = built-in reader; F4 now = open in the external / associated
#       program (they used to be the same).  Double-click on a text/image/PDF
#       file opens the reader; double-click on anything else opens externally;
#       Shift+double-click (or Shift+Enter) forces the reader on ANY file.
#   [x] NEW: Ctrl+Page = fixed small cursor jump (CURSOR_JUMP_SMALL, 5 rows),
#       Shift+Page = fixed big jump (CURSOR_JUMP_BIG, 30 rows).  Plain Page
#       Up/Down still jump one WINDOW-full; all of them keep the cursor on-
#       screen (see()).  Browse archive moved off Ctrl+PageDown to
#       Ctrl+Alt+PageDown to make room (still re-mappable in the shortcut editor).
#   [x] NEW: Shift+Left / Shift+Right cycle the saved Workspaces on the active
#       panel (wrapping), so you can flip "profiles" from the keyboard.
#
# DONE (2026-08-01 revision N — Page-Up/Down cursor, focus & stale-drag fixes):
#   [x] BUG FIX: Page Up / Page Down only SCROLLED the ttk.Treeview view — the
#       keyboard cursor stayed on the original file, so the next arrow press
#       moved one step from THAT old row instead of from where you paged to.
#       Prior / Next are now bound to real cursor moves (one visible page), so
#       the arrow keys continue from the paged-to row.
#   [x] BUG FIX: after a copy/move the arrow keys "went dead" until you clicked
#       the window.  Two causes, both fixed: (1) a rebuilt list left the tree
#       with NO focus item, so ttk had nothing for the arrows to move from — the
#       cursor is now preserved across every refresh (same file, or the row that
#       took its place after a move); (2) the post-operation refresh now hands
#       the keyboard back to the active file list — but only when OUR window is
#       the foreground app, so it never yanks focus from a program you switched
#       to.
#   [x] BUG FIX: moved files stayed red-marked / highlighted.  A move now drops
#       the source marks and selection the moment it is queued.
#   [x] BUG FIX: the first click after a move could raise a "Drag & Drop – error"
#       popup — a tiny click-drag re-dragged the now-moved (non-existent) files.
#       get_all_selected() and the drag initiator now skip paths that no longer
#       exist, so a stray drag of stale rows simply cancels instead of erroring.
#
# DONE (2026-07-27 revision M — Task Queue can NEVER hold the keyboard):
#   [x] BUG FIX: after a copy/move the Task Queue window could end up owning the
#       keyboard, so the file manager appeared to lose ALL its shortcuts and
#       arrow navigation.  Root cause: the queue's Treeview/buttons are focusable
#       and the Windows "no-activate" trick is event-driven — a badly timed OS
#       focus grab (or the deiconify() fallback when the Win32 call fails) beat
#       it, and the old bounce only did panel.tree.focus_set(), which does
#       nothing while another toplevel is the ACTIVE OS window.
#   [x] Three layers now make it impossible: (1) the bounce re-asserts no-activate
#       AND pulls the MAIN window back to the OS foreground before re-seating the
#       caret; (2) a 200 ms focus watchdog runs for the life of the queue window
#       and bounces the keyboard back the instant focus lands on ANY queue widget
#       (switching to another program is left alone); (3) every queue widget is
#       takefocus=0 so Tab can never move the caret into the queue either.
#
# DONE (2026-07-26 revision L — marks survive refresh + Ctrl+N unmark):
#   [x] BUG FIX: red marks (Shift+arrow / Insert) were wiped by any in-place
#       refresh (folder watcher, post-operation), so dragging marked files often
#       carried only the single cursor row.  Marks are now remembered by file
#       name and re-applied after a refresh — a multi-file drag keeps them all.
#   [x] Ctrl+N unmarks everything (None) — the opposite of Ctrl+A (All).
#
# DONE (2026-07-26 revision K — active Workspace highlighted):
#   [x] The currently loaded Workspace button now stands out — inverted colours
#       (accent background), a ● marker, a border, and a "· L / R / LR" tag
#       showing which panel(s) it is loaded on.  The bar redraws on load, so it
#       is always obvious at a glance which Workspace is active.
#
# DONE (2026-07-26 revision J — one-tick auto-rule in the Task Queue):
#   [x] The Task Queue has an "Auto-rule" bar: after a copy/move it shows the
#       Workspace and the from→to folder pair, an "On clash" policy (default
#       Backup-rename old) and a checkbox "Always auto-resolve this" (default
#       off).  Tick it → a Smart-queue rule is saved for exactly that Workspace
#       and folder pair, so future transfers between them resolve automatically
#       (counts as no-problem, queue stays in the background).  Untick → the rule
#       is removed.  ⚖ Rules… still manages them all afterwards.
#
# DONE (2026-07-26 revision I — click-to-front queue + rules/sort discovery):
#   [x] Clicking the Task Queue now brings it to the FRONT above every other
#       program (Cubase, Thunderbird, the file manager, anything) — because a
#       no-activate window is not auto-raised by Windows, the click is caught and
#       the window raised by hand.  It still NEVER takes the keyboard.
#   [x] The Task Queue toolbar gained a "⚖ Rules…" button that opens the Smart-
#       queue conflict rules (also under TOOLS ▾) — so "from X to Y in Workspace
#       W, always Rename old" is reachable right where you expected it.
#   [x] Hover tooltips on the queue's "Smart Sort" and "Rules…" buttons explain
#       what they do (Smart Sort = quick jobs first + space-blocked jobs wait).
#
# DONE (2026-07-26 revision H — folder dive + sub-folder tree jump):
#   [x] Shift+Enter on a folder dives to the DEEPEST folder, entering the first
#       sub-folder at each level (following your folder sort) until there are no
#       more sub-folders.
#   [x] Ctrl+Enter on a folder pops up the whole sub-folder tree under it —
#       lazy-loaded, so it opens instantly — and you glide to any level with the
#       arrow keys (→ expand, ← collapse) or the mouse, then Enter / double-click
#       to jump straight there.
#
# DONE (2026-07-26 revision G — data-loss guard, keyboard, trash, tabs):
#   [x] CRITICAL DATA-LOSS FIX: the Delete key is bound globally, so pressing
#       Delete to erase a character WHILE renaming a file used to fire the file
#       delete and trash the selected file(s) — then the rename failed with
#       "file does not exist".  Delete (and Enter → open) now do NOTHING while
#       the keyboard is in a text field (inline rename, dialog box, …).
#   [x] Keyboard: a clean copy/move no longer pops the Task Queue window at all
#       (only a real conflict does), and the queue can never keep the keyboard —
#       if it is ever focused it bounces the keyboard straight back to the file
#       manager.  So the arrow keys stay in the main program after a move, with
#       no mouse click needed.
#   [x] Trash window FIX: the Restore / Purge / Empty buttons were packed after
#       an expand=True list and got squeezed to zero width — invisible and
#       unusable.  The list is now packed last, so the buttons are back.  Restore
#       renames a ~deleted~ item back to its original name.
#   [x] Right-click a tab also offers "⏮ Move to leftmost" and "Move to
#       rightmost ⏭", alongside Move left / Move right.
#
# DONE (2026-07-26 revision F — queue pops to front, file counter, auto-rules):
#   [x] Task Queue now POPS TO THE FRONT (always-on-top, no focus steal) the
#       moment a copy/move is parked on a name clash — it can no longer hide
#       behind other programs, so you can't miss it.  A clean copy still shows
#       quietly in the corner.  The ⚡ button also reliably raises it above other
#       apps now.  Once you pick a resolution it drops back behind the file
#       manager.  Throughout, the ARROW KEYS stay in the file manager — the
#       queue can be clicked but never becomes the active window (WS_EX_NOACTIVATE
#       + SetWindowPos with SWP_NOACTIVATE).
#   [x] Bottom bar has a new middle section: "<N> files · <M> folders" for the
#       active panel, switching to "✔ X of N selected" when items are marked.
#   [x] Smart-queue conflict rules (TOOLS ▾ → "Smart-queue conflict rules", or
#       the ⚖ toolbar button): say "from folder A to folder B (optionally only
#       in Workspace W), always Overwrite older / Backup old / …".  Copy/move
#       then resolves clashes automatically for that pair — no dialog.  Blank
#       source or destination means "any".  Saved in conflict_rules.json.
#
# DONE (2026-07-25 revision E — drives need-sign-in + Transfer presets):
#   [x] The drive finder now also lists a host's drives that EXIST but need
#       credentials — shown greyed out as "needs sign-in" (amber) instead of
#       being hidden.  So you can see which hard drives a network computer has
#       before you sign in; fill in user/password and Find again to use them.
#       (Empty drive letters are still skipped, so the list stays clean.)
#   [x] Transfer presets (TOOLS ▾ → "Transfer presets", or add the ⇪ toolbar
#       button): saved 1-click copy/move jobs.  Each preset stores its source
#       folders/files, a destination (local or a network path), Copy/Move, and
#       the clash policy (Overwrite old / Skip / Backup old / Rename new / …).
#       ▶ Run drops it straight into the Task Queue — no dialogs.  An optional
#       destination sub-folder, with a "add date/time" tick, gives versioned
#       backups (a fresh folder each run) — that's the "rename on the receiving
#       computer" part.  "Use current selection" fills the sources from the
#       active panel.  Saved in Helpfiles/redigerare/transfer_presets.json.
#
# DONE (2026-07-25 revision D — network drives + select-all keys):
#   [x] "Find drives on host": a scanned machine is only an IP — you can't map
#       the bare host UNC itself.  NET - Scan - right-click a host - "Find drives
#       (C$/D$...)" (or "Save as Favorite") now probes the machine's hidden admin
#       drive shares C$...Z$ (its physical drives) plus any normal disk shares,
#       lists what is reachable, and lets you TICK the drives you want and give
#       each its OWN drive letter — then Save as favourites and/or Map now.
#       Optional user/password fields unlock the hidden C$/D$ shares.
#   [x] FIXED: right-click a scanned host - "Save as Favorite" used to prefill a
#       bare host path (no share) that could never be mapped; it now opens the
#       drive finder above instead.
#   [x] Select-all keys in the file list: Ctrl+A marks every row; Shift+End
#       marks from the cursor to the last row; Shift+Home to the first row.
#
# DONE (2026-07-25 revision C — Task Queue never takes the keyboard):
#   [x] The Task Queue window now carries the WS_EX_NOACTIVATE style: you can
#       click it and its Resolve buttons, but it NEVER becomes the active window,
#       so the arrow keys always stay in the main file manager — never in the
#       queue.  Even the ⚡ button now raises it without stealing focus.
#   [x] After you pick a conflict action (Overwrite / Skip / …) the queue drops
#       back behind the file manager and the keyboard returns to the active
#       panel automatically — no extra click to get the arrow keys back.
#
# DONE (2026-07-25 revision B — move fix + tab reordering + conflict surfacing):
#   [x] BUG FIX: moving a FOLDER left the (now empty) source folder behind, so a
#       move looked like a copy.  The engine moves files one by one to allow
#       per-file conflict handling; it now prunes the emptied source folders
#       afterwards (only truly-empty dirs, so a Skipped file keeps its folder).
#   [x] Right-clicking a tab now also offers "◀ Move left" / "Move right ▶" to
#       reorder the tab within its panel (disabled at the ends).
#   [x] Reordering a tab inside a Workspace auto-saves the new order ~60 s after
#       the LAST move (debounced — a burst of moves writes once, not per move).
#       A pending save is also flushed on program close so it is never lost.
#   [x] When a queued copy/move hits a name clash the task is parked; the Task
#       Queue window now ALWAYS surfaces (in the background, keyboard stays in
#       the file manager) so a waiting conflict can't be mistaken for success.
#
# DONE (2026-07-25 revision — tabs, sorting, backup rename, background queue):
#   [x] Home / End keys jump to the first / last row of the file list
#       (Ctrl+Home / Ctrl+End do the same).
#   [x] Tabs now know whether they belong to a saved Workspace.  Tabs opened
#       after a Workspace is loaded are TEMPORARY (amber "○" marker) and can
#       always be closed; saved tabs are protected — their ✕ only appears when
#       the "Unlock saved tabs" checkbox on the Workspace bar is ticked.
#   [x] Half-save: while you are in a Workspace, the extra (temporary) tabs you
#       open are auto-remembered IN THAT WORKSPACE (its *_extra list), so they
#       come back the next time you load it — no manual re-save needed.  Loading
#       a Workspace reopens base + extras by default; right-click ▸ "Load base
#       tabs only" reopens just the base and forgets the extras.  An explicit
#       Save / Update bakes everything into the base.
#   [x] Panel scrollbars are packed with priority, so the vertical scrollbar
#       stays visible even when a panel is dragged very narrow (was clipped).
#   [x] Independent sort for FILES and FOLDERS: left-click a column header
#       sorts files (filled ▲/▼), right-click a header sorts folders
#       (hollow ▵/▿).  So you can keep files newest-first and folders A→Z.
#       The default order is configurable (Settings ▸ General) — factory
#       default is files by Modified (newest first), folders by Name.
#   [x] Per-tab sort is remembered for the whole session.  It is NOT persisted
#       on its own — re-save the Workspace to keep it; otherwise a fresh tab
#       falls back to your configured default.
#   [x] Delete no longer leaves files hiding on disk under their own name (the
#       "parallel universe").  Delete now RENAMES the item in place to
#       ~deleted~<date>~<name> — freeing the original name at once (reuse it here
#       or in any other tool) and hiding the ~deleted~ item.  A start-up sweep
#       PHYSICALLY purges old trash (to the Recycle Bin): small files (< a size
#       you set, default 5 MB) after N weeks, larger files after N hours (max
#       30).  The 🗑 window Restores / Purges selected / Empties all now; Ctrl+Z
#       restores the last delete.  All thresholds live in ⚙ Deletion settings,
#       and "Use the in-place trash" can be turned off for a plain Recycle-Bin
#       delete.
#   [x] Renaming onto an existing name no longer just fails with "Could not
#       rename".  It shows the same "file already exists" dialog as copy/move —
#       Overwrite old / Backup-rename old / Rename new (adds _1) / Skip — via the
#       new EditorFrame.rename_path().  (F2, slow-click, and continuous rename
#       all route through it.)
#   [x] FIXED the "parallel universe": a file you delete is only MARKED (hidden,
#       still on disk).  (1) Renaming onto such a hidden file now frees the name
#       silently instead of nagging.  (2) If another program overwrites/recreates
#       a file at a marked path, the mark is dropped and the file reappears —
#       File Manager no longer hides a file that genuinely exists.
#   [x] Sorting: the cursor now stays in view after re-sorting (the selected row
#       is scrolled back into view); and the FIRST click on Modified or Size
#       sorts DESCENDING (newest / largest first), which is what you expect.
#   [x] The Task Queue window no longer steals the keyboard.  When it pops up
#       after a copy/move it is shown with Win32 SW_SHOWNOACTIVATE, so focus
#       never leaves wherever it was — the file manager keeps the keyboard and
#       TAB works immediately, with no click needed.  It takes focus only when
#       you click it, or open it deliberately with the ⚡ button.  Switch to
#       another program and that program keeps focus — the queue never grabs it.
#   [x] FIXED a real auto-refresh bug: the folder watcher rescheduled its poll
#       only on its two early-return branches, so after the first (baseline)
#       check it went silent — panels then updated ONLY when you navigated away
#       and back.  It now re-arms every cycle (via a main-thread _finish step),
#       so an edit on disk shows up in the panel within ~1.5 s with no manual
#       "go to parent and back".
#   [x] The title bar and About now show a BUILD STAMP (the running file's own
#       modified time), so you can tell at a glance whether the app you have
#       open is the latest build.  IMPORTANT: a running program never reloads its
#       own code — after the .py is updated you must CLOSE and REOPEN it to get
#       the new build (the file on disk is current immediately; the live process
#       is not).
#   [x] Backup-rename now runs on the WHOLE selection — it honours Insert-key
#       marks (red) as well as the ordinary highlight (via get_all_selected).
#   [x] "File already exists" (F5/F6) gained a third real choice: "Backup-rename
#       old" keeps the existing file renamed Backup<code>-… so the incoming file
#       can take the name with nothing lost — alongside overwrite-old and
#       rename-new.  An "Apply to all remaining conflicts" checkbox turns any of
#       those into a bulk action; the Task-Queue conflict banner has the matching
#       "Backup-rename old" button.
#   [x] Task-Queue rows are now sectioned by DAY (Today / Yesterday / weekday +
#       date headers) and each row shows the clock time (HH:MM) it was queued or
#       finished — no more per-row second counters.
#   [x] Backup-rename (Ctrl+Shift+B menu / right-click "Backup rename…"):
#       prefixes each selected file with Backup<CODE>-  where <CODE> is a
#       3-char code (000…ZZZ) that is unique PER original filename, tracked in
#       Helpfiles/redigerare/backup_codes.json so repeats never collide.
#       Confirmation dialog offers Yes / No / Yes + move (move to the
#       Settings-defined backup folder).  Different programs never get bundled
#       under one name — each file keeps its own base name.
#   [x] The Task Queue window is now "background" the way it should be: it opens
#       automatically but in a screen corner, is NON-modal, never covers the file
#       panels and never steals focus, so the manager stays fully usable while
#       tasks run.  Click the manager and it drops behind; the ⚡N toolbar button
#       shows the pending count and brings it back.  (Settings ▸ General can hide
#       it entirely if you prefer only the ⚡ button.)
#   [x] Tab strips scroll horizontally: mouse-wheel over the strip, or the thin
#       scrollbar that appears only when the tabs overflow; the active tab is
#       always scrolled into view.
#   [x] Click a tab to flash its full path in the status line; hover a tab for
#       the same path as a tooltip; right-click a tab to copy its path.
#
# DONE (earlier revision — Total Commander parity pass):
#   [x] Multi-Rename tool (Ctrl+M) — placeholders, counters, regex, undo
#   [x] File compare (line diff + byte/hex diff) with colour marking
#   [x] Directory synchronize — compare two trees, copy only differences
#   [x] Quick View panel (Ctrl+Q) — live text / hex / image preview
#   [x] Branch view (Ctrl+B flat, Ctrl+Shift+B flat with folders)
#   [x] Extended archives — RAR, 7z, TAR, GZ, BZ2, XZ, ISO, CAB
#   [x] Directory hotlist (Ctrl+D) — favourite local folders
#   [x] Checksums — CRC32 / MD5 / SHA1 / SHA256, create + verify .sfv/.md5
#   [x] Split / combine files
#   [x] Command bar in the main window — CMD or PowerShell, with history
#   [x] Command library — saved commands, per-command shell, run in sequence
#   [x] Duplicate finder — by name / size / content hash
#   [x] Configurable keyboard shortcuts (Helpfiles/redigerare/keymap.json)
#   [x] Configurable toolbar — add/remove/reorder buttons, own commands and
#       pinned folders (Helpfiles/redigerare/toolbar.json)
#   [x] Network share discovery — \\\\server\\Film found and opened directly,
#       from one host or every host in the LAN scan
#   [x] Command palette (Ctrl+Shift+P) — fuzzy search over every command
#   [x] Visual disk usage treemap (Ctrl+Alt+D) — WinDirStat style, with
#       drill-down and colour by file type
#   [x] File-type hooks into your own programs — right-click "Send to",
#       per-extension tools defined in tools.json
#   [x] Deletions are in the undo history: marking is undoable (Ctrl+Z
#       puts it back), carrying it out is recorded but honestly marked
#       as not undoable
#   [x] Column widths are remembered when you drag them; the Tags
#       column takes no space in folders with nothing tagged
#   [x] Quick View no longer squashes the left panel — the two file
#       panels stay equal, and rebalance when it closes
#   [x] Delete now MARKS instead of deleting: crash-safe list written
#       immediately, "Carry out deletion" when you mean it, optional
#       automatic carry-out after N days (default 8, off by default)
#   [x] Date handling is a choice: unpacking and copying can keep the
#       original date or stamp today. Fixed a real bug — ZIP always
#       lost the original date, unlike TAR/GZ/7z
#   [x] Attributes on the whole selection, with tri-state for flags the
#       selection disagrees about, plus setting the date deliberately
#   [x] Tags re-attach after renames made outside the program, matched
#       by size + content signature, refusing to guess when ambiguous
#   [x] Sort folders by date, not just alphabetically, with a
#       "folders first" toggle (Total Commander cannot do this)
#   [x] Save every found network share as a favourite in one step, then
#       reconnect them all with one button (NetRadar-style)
#   [x] Custom file tags (Ctrl+G) — colour labels in a sidecar database,
#       filterable with tag: in the filter box, following their files
#       through renames and moves
#   [x] Fuzzy duplicate detection — visually similar images (perceptual hash)
#       and acoustically similar audio (spectral fingerprint via ffmpeg), so
#       the same picture at another size or the same track at another bitrate
#       is found. Exact hashing misses all of those.
#   [x] Operation log with multi-step undo (Ctrl+Z) — copy / move / rename /
#       new folder, reverted newest-first, refusing anything that would
#       destroy data
#   [x] Print / export directory listing — TXT, CSV, HTML, PDF
#   [x] Automatic panel refresh when the folder changes on disk
#   [x] Window size + position remembered between sessions
#   [x] Crash catcher with diagnostic dump
#
# FUTURE IDEAS — to think about once everything else is finished:
#   [ ] Split the RIGHT side into two stacked panels (top / bottom), each with
#       its own tabs, so a copy/move from the left can go to BOTH right panels
#       at once.  Chosen direction = "full top/bottom split of the right side".
#       This is a large change (tabs, workspaces, sorting, active-panel, copy
#       targets, disk info, DnD all assume exactly left+right today).  Full
#       design notes + a build plan are in the file next to this script:
#           File_manager_TODO_split-right-panel-top-bottom.md
#   [ ] WebDAV and cloud storage (OneDrive, Google Drive)
#   [ ] Record deletes in the undo log alongside the pending-delete list, so
#       one history covers everything. (Unpack is deliberately NOT undoable —
#       see below.)
#
# NOT TO DO — decided against, deliberately left alone:
#   [ ] Thumbnail view (grid of image previews instead of a list)
#       Quick View (Ctrl+Q) already previews the file under the cursor, which
#       covers the same need without a second view mode to maintain.
#   [ ] Plugin architecture (viewer / filesystem / packer / content plugins)
#       Everything plugins would have provided is built in already: viewers,
#       archive formats, extra columns, and "Send to" for outside tools.
#   [ ] Undo for unpack
#       Removing what an extraction produced cannot be done safely — it would
#       have to delete files that may since have been edited, and it cannot
#       tell those apart from the ones it created.
#
# ══════════════════════════════════════════════════════════════════════════
"""

# ══════════════════════════════════════════════════════════════════════════
#  DEL 01 — Imports, paths, constants, help text
# ══════════════════════════════════════════════════════════════════════════

import tkinter as tk
from tkinter import ttk, filedialog, messagebox, simpledialog
import os
import sys
import zipfile
import threading
import queue
import json
from datetime import datetime, timedelta
import ctypes
import platform
from pathlib import Path
import shutil
import tempfile
import subprocess
import webbrowser
from ftplib import FTP, FTP_TLS, error_perm
import socket
import ipaddress
import concurrent.futures
import base64
import time as _time
import re as _re   # used for DnD path parsing
import dataclasses
import enum
import hashlib
import tarfile
import difflib
import fnmatch
import traceback
import zlib
import stat            # the READ-ONLY attribute (revBI)
import struct          # the ISO 9660 writer (DEL 53)
import errno
import string as _string
import random as _random

# ── Optional: tkinterdnd2 (drag-and-drop with host OS) ────────────────────
# Install with:  pip install tkinterdnd2
try:
    from tkinterdnd2 import TkinterDnD as _TkinterDnD, DND_FILES as _DND_FILES
    _HAS_DND = True
except ImportError:
    _TkinterDnD = None
    _DND_FILES  = None
    _HAS_DND    = False

# ── Paths ──────────────────────────────────────────────────────────────────
# When frozen to an EXE, sys.executable is the program — otherwise this file.
# Either way, everything stays relative to the program itself.
def _find_home(start):
    """The folder that holds Helpfiles, searching upward from `start`.

    Helpfiles is a SIBLING of the program's folder, not a child of it, so the
    answer is "the nearest folder above me that contains Helpfiles". The same
    three lines then work from Py\\, from Folder-exe\\<Name>\\ and from the old
    layout where the .py sat directly beside Helpfiles - and a group like
    Chess\\ that keeps its own world finds its own.

    Capped at four levels: a stray Helpfiles far up the tree must not be
    adopted by accident. Nothing found means behave exactly as before and use
    the program's own folder, which is what keeps a working copy under test
    away from his live data.
    """
    # Py\ and Folder-exe\<Name>\ are ALWAYS direct children of home, so
    # their own name settles it. This runs BEFORE the walk: a stray
    # Helpfiles inside Py\ used to win the walk and silently became every
    # program's home - that is how Notes lost a day (2026-09-04).
    if os.path.basename(start).lower() == "py":
        return os.path.dirname(start)
    if os.path.basename(os.path.dirname(start)).lower() == "folder-exe":
        return os.path.dirname(os.path.dirname(start))
    # Otherwise: the nearest folder above me that HAS a Helpfiles. Capped at
    # four levels so a stray one far up is not adopted by accident; nothing
    # found means behave as before, which keeps a test copy off live data.
    d = start
    for _ in range(4):
        if os.path.isdir(os.path.join(d, "Helpfiles")):
            return d
        parent = os.path.dirname(d)
        if parent == d:
            break
        d = parent
    return start


def _program_home():
    """Where Helpfiles and Icons live, as .py and as a frozen build alike."""
    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__)))


def _own_dir():
    """The folder this program's own file sits in.

    Its neighbours are the FIRST place to look for another of his programs -
    they are kept together, whether that folder is 1---Blandat, the Py folder
    under 0---Python, or one of his own making. _program_home() is the DATA
    root, and in the 0---Python layout that is one level ABOVE the programs,
    so a lookup that starts there walks straight past the program standing
    right next to it.
    """
    if getattr(sys, "frozen", False):
        return os.path.dirname(os.path.abspath(sys.executable))
    return os.path.dirname(os.path.abspath(__file__))


PROGRAM_HOME_AWARE = True   # Tower checks for this before offering the swap

APP_ROOT = Path(_program_home())

HELP_DIR      = APP_ROOT / "Helpfiles" / "redigerare"
LOG_DIR       = APP_ROOT / "Helpfiles" / "0---Empty"   # logs only
HELP_DIR.mkdir(parents=True, exist_ok=True)
LOG_DIR.mkdir(parents=True, exist_ok=True)

# *************** DEL 02b - PORTABLE PATHS (STORED RELATIVE TO HOME) ********
# ALL TEXT IN THE PROGRAM IS ALWAYS IN ENGLISH - NEVER SWEDISH!
#
# A path that points INSIDE my own tree is stored as a token, not as a drive
# letter, so the whole collection can be moved to another disk without every
# saved folder, tag and rule pointing at a tree that is not there any more:
#
#       X:\1---Python\0---Python\Py\Tower.py   ->  {HOME}\Py\Tower.py
#       X:\1---Python\1---Blandat\Chess.py     ->  {ROOT}\1---Blandat\Chess.py
#       D:\Filmer\...                          ->  unchanged, not mine
#
# {HOME} is the folder holding Helpfiles, Icons, Py and Folder-exe - what
# _program_home() computes.  {ROOT} is one level above it.  Everything else
# stays absolute, which is the point: a movie drive does not move when my
# tree does.
#
# In memory every path is absolute exactly as before.  Only the JSON on disk
# is written in tokens, and only at the few boundaries listed below.  The
# 109 MB oplog is NOT one of them - walking it on every file operation would
# cost far more than it could ever save, and it is a history of what was
# done, not a setting that has to survive a move.
#
# Dictionary KEYS travel too.  folder_sorts and tags are keyed by the path
# itself, lower-cased, so a key left behind would quietly lose every sort
# override and every colour label the day the tree moves.  On the way back a
# key that was stored lower-cased is lower-cased again, because that is the
# exact form the lookups build.

FM_HOME_TOKEN = "{HOME}"
FM_ROOT_TOKEN = "{ROOT}"
# This program imports the regular-expression module as _re, so that
# is the name to use here too.
_FM_DRIVE_RE  = _re.compile(r"^[A-Za-z]:[\\/]")


def _fm_home() -> str:
    return str(APP_ROOT)


def _fm_root() -> str:
    return os.path.dirname(str(APP_ROOT)) or str(APP_ROOT)


def fm_pack(p):
    """Absolute path -> token form, but only inside my own tree."""
    if not isinstance(p, str) or not p or p.startswith("{"):
        return p
    if not _FM_DRIVE_RE.match(p):
        return p
    try:
        ap = os.path.abspath(p)
    except Exception:
        return p
    # HOME before ROOT: a path under home is also under root, and the closer
    # of the two is the one that survives a move of home alone.
    for base, token in ((_fm_home(), FM_HOME_TOKEN), (_fm_root(), FM_ROOT_TOKEN)):
        try:
            rel = os.path.relpath(ap, base)
        except ValueError:                  # another drive - cannot be relative
            continue
        if rel == os.curdir:
            return token
        if rel != os.pardir and not rel.startswith(os.pardir + os.sep):
            return token + os.sep + rel
    return p


def fm_unpack(p):
    """Token form -> absolute path.  Anything else is handed back untouched.

    A tail that was stored lower-cased comes back lower-cased: folder_sorts
    and tags are keyed by normcase(abspath(...)), and a key that differs only
    in case matches nothing at all.
    """
    if not isinstance(p, str) or not p.startswith("{"):
        return p
    for token, base in ((FM_HOME_TOKEN, _fm_home()), (FM_ROOT_TOKEN, _fm_root())):
        if p == token:
            return base
        for sep in ("\\", "/"):
            if p.startswith(token + sep):
                tail = p[len(token) + 1:].replace("/", os.sep)
                out  = os.path.join(base, tail)
                if tail and tail == tail.lower():
                    try:
                        return os.path.normcase(out)
                    except Exception:
                        return out
                return out
    return p


def _fm_walk(obj, fn):
    """A new structure with fn applied to every string, keys included."""
    if isinstance(obj, dict):
        return {(fn(k) if isinstance(k, str) else k): _fm_walk(v, fn)
                for k, v in obj.items()}
    if isinstance(obj, list):
        return [_fm_walk(v, fn) for v in obj]
    if isinstance(obj, tuple):
        return tuple(_fm_walk(v, fn) for v in obj)
    if isinstance(obj, str):
        return fn(obj)
    return obj


def fm_pack_tree(obj):
    """A COPY with every path inside my tree written as a token."""
    try:
        return _fm_walk(obj, fm_pack)
    except Exception as exc:
        _log(f"Could not make the paths portable: {exc}")
        return obj


def fm_unpack_tree(obj):
    """A COPY with every token expanded against this tree."""
    try:
        return _fm_walk(obj, fm_unpack)
    except Exception as exc:
        _log(f"Could not expand the stored paths: {exc}")
        return obj


SITES_PATH       = HELP_DIR / "ftp_sites.json"
SETTINGS_PATH    = HELP_DIR / "settings.json"
NET_FAVORITES_PATH = HELP_DIR / "net_favorites.json"
WORKSPACES_PATH  = HELP_DIR / "workspaces.json"
HOTLIST_PATH     = HELP_DIR / "hotlist.json"          # favourite local folders
COMMANDS_PATH    = HELP_DIR / "commands.json"         # saved shell commands
KEYMAP_PATH      = HELP_DIR / "keymap.json"           # user keyboard shortcuts
TOOLBAR_PATH     = HELP_DIR / "toolbar.json"          # user toolbar layout
OPLOG_PATH       = HELP_DIR / "oplog.json"            # operation log (undo)
TOOLS_PATH       = HELP_DIR / "tools.json"            # "Send to" tool hooks
TAGS_PATH        = HELP_DIR / "tags.json"             # colour labels on files
PENDING_DELETE_PATH = HELP_DIR / "pending_delete.json"  # marked for deletion
BACKUP_CODES_PATH = HELP_DIR / "backup_codes.json"    # used Backup<CODE> per filename
TRANSFER_PRESETS_PATH = HELP_DIR / "transfer_presets.json"  # saved 1-click copy/move jobs
CONFLICT_RULES_PATH = HELP_DIR / "conflict_rules.json"  # auto conflict policy per source→dest
TWIN_RULES_PATH  = HELP_DIR / "twin_rules.json"       # "(2) suffix = same file" answers
RELOCATOR_PATH   = HELP_DIR / "relocator.json"        # Relocator tidy-away rules
FOLDER_SORTS_PATH = HELP_DIR / "folder_sorts.json"    # per-folder sort OVERRIDE (DEL 45)
# Sources that were COPIED because they were locked, and whose original must be
# deleted as soon as the program holding it lets go (DEL 49).
UNLOCK_DELETE_PATH = HELP_DIR / "delete_when_unlocked.json"
# Transfers that had not finished when the program last closed.  The queue is
# no longer something you lose by closing a window (revision BB).
QUEUE_STATE_PATH = HELP_DIR / "task_queue.json"
# Queues saved BY HAND, one JSON file each: "park this lot and pick it up
# tomorrow" (revision BN).  Same record format as task_queue.json, so a saved
# queue and a carried-over one load through exactly the same code.
QUEUE_DIR        = HELP_DIR / "queues"

# A deleted file is RENAMED to this prefix (in place) so the original name is
# freed at once and the file is recognisable as trash to every tool.  It is
# hidden from the panels and physically purged later, by age.
TRASH_PREFIX = "~deleted~"

# The character painted in the ★ column, and on the toolbar button that sets
# it.  Change it here and both follow — "*", "✔", "●" all work.
FLAG_CHAR = "★"
LOG_PATH         = LOG_DIR  / "File_manager.log"
CRASH_PATH       = LOG_DIR  / "File_manager_crash.log"
TRACE_PATH       = LOG_DIR  / "File_manager_cursor.log"
# Native-level crashes (Tcl panic, stack overflow, access violation) never
# reach a Python except-hook, so faulthandler dumps them here instead.
FAULT_PATH       = LOG_DIR  / "File_manager_fault.log"
_FAULT_FH        = None      # kept open for the life of the process

# Default start directory (used until user pins a permanent one)
DEFAULT_START_DIR = str(APP_ROOT)

# The running program's own file — used for the build stamp below.
if getattr(sys, "frozen", False):
    _SELF_FILE = os.path.abspath(sys.executable)
else:
    _SELF_FILE = os.path.abspath(__file__)


def _build_stamp() -> str:
    """Modification time of the running program file (the .py, or the .exe when
    frozen).  Shown in the title bar and About so you can tell AT A GLANCE which
    build is actually running — a running program never reloads its own code, so
    after I update the file you must close and reopen it to get the new build."""
    try:
        from datetime import datetime as _dt   # local import: datetime is set up below
        return _dt.fromtimestamp(os.path.getmtime(_SELF_FILE)).strftime("%Y-%m-%d %H:%M")
    except Exception:
        return "?"

# ── About / style colours ──────────────────────────────────────────────────
C_BG    = "#1e1e2e"
C_BG2   = "#242436"
C_BG3   = "#2a2a3d"
C_ACCENT = "#7eb8f7"
C_FG    = "#e0e0f0"
C_FG_DIM = "#8888aa"
C_SEP   = "#3a3a5c"

# ── File-type map (English) ────────────────────────────────────────────────
_EXT_TYPE = {
    ".jpg": "Image",  ".jpeg": "Image", ".png": "Image",  ".gif": "Image",
    ".bmp": "Image",  ".webp": "Image",
    ".py":  "Python", ".pyw": "Python",
    ".txt": "Text",   ".log": "Text",   ".md":  "Text",
    ".pdf": "PDF",
    ".zip": "ZIP",    ".rar": "RAR",    ".7z":  "Archive", ".tar": "Archive",
    ".gz":  "Archive",
    ".exe": "Program", ".msi": "Installer",
    ".doc": "Word",   ".docx": "Word",
    ".xls": "Excel",  ".xlsx": "Excel",
    ".ppt": "PowerPoint", ".pptx": "PowerPoint",
    ".mp3": "Audio",  ".wav": "Audio",  ".flac": "Audio", ".ogg": "Audio",
    ".mp4": "Video",  ".avi": "Video",  ".mov": "Video",  ".mkv": "Video",
    ".html": "Web",   ".htm": "Web",    ".css": "Web",    ".js":  "Web",
    ".json": "JSON",  ".xml": "XML",    ".csv": "CSV",
    ".bat": "Batch",  ".cmd": "Batch",  ".ps1": "PowerShell",
    ".dll": "Library", ".sys": "System",
    ".pyc": "Python",
    ".db":  "Database", ".sqlite": "Database", ".sqlite3": "Database",
    ".mdb": "Database", ".accdb":  "Database",
    ".bak": "Backup",   ".old":    "Backup",  ".tmp": "Backup",
    ".ini": "Config",   ".cfg":    "Config",  ".conf": "Config",
    ".yaml": "Config",  ".yml":    "Config",  ".toml": "Config",
    ".ttf": "Font",     ".otf":    "Font",    ".woff": "Font",
    ".iso": "Disc image", ".img":  "Disc image", ".cab": "Archive",
    ".lnk": "Shortcut",
    ".srt": "Subtitle", ".sub":    "Subtitle", ".ass": "Subtitle",
}

# ── Built-in viewer file types ──────────────────────────────────────────────
_VIEWER_IMAGE_EXTS = {".jpg", ".jpeg", ".png", ".gif", ".bmp", ".webp"}
_VIEWER_PDF_EXTS   = {".pdf"}
# Audio types the simple built-in player handles (via Windows' own MCI/winmm —
# no extra dependency).  mp3/wav/wma/mid play natively; the rest are tried and
# fall back to "open in default program" if Windows has no codec.
_VIEWER_AUDIO_EXTS = {".mp3", ".wav", ".wma", ".m4a", ".aac",
                      ".ogg", ".flac", ".mid", ".midi", ".mp2"}
# Plain-text file types the built-in text reader opens on F3 / double-click.
# (F3 opens ANY file as text as a last resort; these just get auto-routed so a
# double-click on them uses the reader instead of the external program.)
_VIEWER_TEXT_EXTS  = {
    ".txt", ".text", ".log", ".csv", ".tsv", ".nfo", ".diz", ".me",
    ".srt", ".sub", ".vtt", ".ass", ".ssa",
    ".md", ".markdown", ".rst", ".ini", ".cfg", ".conf", ".toml",
    ".json", ".xml", ".yaml", ".yml", ".properties", ".env", ".reg",
    ".py", ".pyw", ".js", ".ts", ".css", ".html", ".htm", ".php",
    ".c", ".h", ".cpp", ".hpp", ".cc", ".java", ".cs", ".go", ".rs",
    ".rb", ".pl", ".lua", ".sql", ".bat", ".cmd", ".ps1", ".sh",
    ".m3u", ".m3u8", ".list", ".gitignore",
}

# ── Fixed cursor-jump sizes (rows) ──────────────────────────────────────────
# Plain Page Up / Page Down jump one WINDOW-full of rows (depends on the window
# size).  Ctrl+Page and Shift+Page jump these FIXED numbers of rows instead, so
# the step is always the same no matter how tall the window is.  Tweak freely.
CURSOR_JUMP_SMALL = 5     # Ctrl+PageUp  / Ctrl+PageDown  (moves only)
CURSOR_JUMP_BIG   = 30    # Shift+PageUp / Shift+PageDown (marks what it passes)

HELP_TEXT = """\
File Manager — Help
===================

Overview
--------
File Manager is a dual-panel file manager for Windows.  The left and right
panels let you browse, copy, move, and manage files side by side, similar
to Norton Commander / Total Commander.

Command line
------------
  File_manager.py <folder>     show that folder in the active panel
  File_manager.py <file>       show its folder, cursor on the file

  A copy that is already running TAKES the path instead of a second window
  opening — that is what lets my other programs say "open this folder" and
  have it land here rather than in Explorer.  The lock is a bound socket
  (port 50598), not a lock file, so it can never survive a crash and lock me
  out of my own program.

Keyboard Shortcuts
------------------
  All of these can be changed:  TOOLS ▾ → Configure shortcuts  (Ctrl+Alt+K).
  Your changes are saved in Helpfiles/redigerare/keymap.json and take effect
  immediately — no restart needed.

  Files and folders
  -----------------
  Tab          Switch active panel (left ↔ right)
  Enter        Open file with the WINDOWS DEFAULT program (same as double-click).
               Exceptions: an archive browses into it; a type in your reader-
               extensions list (Settings) opens in the built-in viewer.
               On a folder: enter it.
  Shift+Enter  Open in the BUILT-IN viewer / player on ANY file (text / image /
               PDF / audio).  On a folder: dive to the deepest first sub-folder.
  Ctrl+Enter   Open with the PER-TYPE opener you set (Settings ▸ Custom openers);
               if none for this type, the built-in viewer.  On a folder: pop up
               its whole sub-folder tree to jump into.
  Alt+Shift+Enter
               Measure every folder in the active panel and put the total in
               the Size column (Total Commander's key for it).  Folders are
               listed with an EMPTY size cell, so until you do this, sorting
               folders by size has nothing to sort on.  Junctions are not
               followed, so a build folder's Helpfiles link is not counted.
               Press again while it runs to stop it.
  F1           This help
  F2           Rename selected item
  F3           View in the built-in viewer (text / image / PDF / audio; any file
               is shown best-effort as text).  The text reader can also EDIT and
               save: press ✎ Edit (Ctrl+E), then Ctrl+S
  F4           Open in the external program YOU picked (Settings ▸ Custom
               openers ▸ "F4 — external program"); Windows' association when
               you have picked none
  Shift+F4     Open in a SECOND program you picked (Settings ▸ Custom openers ▸
               "Shift+F4 — second program"), e.g. a different editor; falls
               back to the Windows association when no second program is set
  Ctrl+F4      Windows' own "Open with…" box — how you undo a wrong
               association you once picked by accident
  F5           Copy to the other panel
  Shift+F5     Copy As… (type the destination path / name first)
  F6           Move / rename (move if target ≠ source folder, else rename)
  Shift+F6     Move As… (type the destination path / name first)
  F7           Create new folder
  F8           Cycle the Left+Right tab pairs (see "Tab pairs" below)
  Delete       Delete selected file or folder
  Alt-F5       Pack selection (ZIP, 7z, TAR, TAR.GZ, TAR.BZ2, TAR.XZ)
  Alt-F9       Unpack selection (ZIP, RAR, 7z, TAR, GZ, BZ2, XZ, ISO, CAB)
  Ctrl+Alt+I   Create an ISO / IMG image from what is marked.  Folders go in
               whole.  .iso and .img are the same bytes for a data image, so
               the extension is yours to pick; Windows mounts it directly.
               Not a bootable disc.
  Alt-F1       Drive / location menu for the left panel  (incl. "⇉ Same folder
               as other panel" and your favourites).  With the menu open,
               just press the drive LETTER — C, D, X … — to jump there.
  Alt-F2       Drive / location menu for the right panel  (same letter keys)
  Alt-F3       Disk overview window
  Alt-Enter    Properties.  With SEVERAL items marked it opens a list instead
               of a message box: one row per item with its OWN size (folders
               are measured in the background), sortable, plus a total and a
               "Copy list" button.
  Alt+Shift+Enter
               Measure the folders in the active panel and put the numbers in
               the Size column (press again to stop).  Settings → Display has
               the standing version of it: "Folders show a SIZE too", which
               measures every folder listing automatically.
  Enter        On a PROGRAM (.py, .pyw, .exe, .bat, .cmd, .ps1, .msi, .lnk …)
               it RUNS it.  A .py is started with pythonw, so no console
               window appears behind your own programs; right-click ▸ ▶ Run in
               a console when you need to read the output.  F4 opens the same
               .py in the editor.  Turn it off in Settings ▸ General.
  Enter        On anything else: open the file.  Which program opens it is
               DefaultHub's table
               (Helpfiles/DefaultHub/defaults.json) — the one place that says
               images go to SeeView, PDFs to PDFull, and so on for every
               program in the tree.  Turn that off, or reach past it, in
               Settings ▸ General.
  Shift+F4     The second program you set — and Windows' association when
               there is none.  Ctrl+F4 is Windows' own "Open with" box.
               Both deliberately ignore DefaultHub: they are the way OUT.
  Ctrl+Alt+W   "⚖ Rules" — the clash rules for the two folders the panels are
               standing in, both ways round.  The same button sits on the
               Workspace bar after "Folders sort like files" and LIGHTS UP
               when a rule covers the pair.  Make a rule for the pair straight
               from there; the full list is under Tools ▸ Smart-queue conflict
               rules, which also warns about rules that overlap and disagree.
  Ctrl-R       Refresh both panels
  Home / End   Jump to the first / last row  (Ctrl+Home / Ctrl+End too)
  Ctrl+Down    Jump to the FIRST FILE — straight past ".." and every folder,
               in whatever order the list is currently sorted
  Ctrl+Up      Jump to the FIRST FOLDER — the row just below ".."
  PageUp/Down  Move the cursor one WINDOW-full of rows (the view follows it)
  Ctrl+Page    Fixed small jump (5 rows by default) — moves only, no marking
  Shift+Page   Big jump (30 rows by default) that MARKS every file and folder
               it passes on the way, start and end row included
  Shift+←/→    Cycle the saved Workspaces (whole profile, both panels)
  Ctrl+←/→     Switch tab (previous / next) on the active panel
  Alt+←/→      Move the active tab to the far left / far right
  Double-click Same as Enter: plain = Windows default; Shift+double-click =
               built-in viewer/player; Ctrl+double-click = per-type opener
               (else the built-in viewer)

  Tabs and search
  ---------------
  Ctrl-T       Duplicate current tab (opens a clone in the same panel)
  Ctrl-W       Close current tab  (kept in history — see Ctrl-Shift-T).
               Right-click a tab for close / close others / lock.
  Ctrl-Shift-T Reopen last closed tab
  Ctrl-F       Open Search window

  Tools
  -----
  Ctrl-M       Multi-Rename tool
  Ctrl-Alt-Shift-B  Backup rename (prefix Backup<code>- , optional move)
  Ctrl-Q       Quick View panel on / off
  Ctrl-B       Branch view — flat list of the whole tree (files)
  Ctrl-Shift-B Branch view including folders
  Ctrl-D       Directory hotlist
  Ctrl-Shift-C Compare files
  Ctrl-Shift-S Synchronize directories
  Ctrl-Shift-D Find duplicate files
  Ctrl-Shift-K Checksums (create / verify)
  Ctrl-Alt-S   Split file into parts
  Ctrl-Alt-C   Combine split parts back together
  Ctrl-P       Print / export folder listing
  Ctrl-L       Command bar on / off
  Ctrl-Alt-L   Command library
  Ctrl-Shift-P Command palette — search every command
  Ctrl-Z       Undo history
  Ctrl-Alt-D   Disk usage treemap
  Ctrl-G       File tags
  Ctrl-Alt-M   Flag / unflag the selection (the ★ column)
  Ctrl-PageDn  Browse the selected archive
  Ctrl-Alt-R   Toggle automatic refresh
  Ctrl-Alt-N   Browse network shares
  Ctrl-Alt-K   Configure keyboard shortcuts
  Ctrl-Alt-B   Configure toolbar
  Escape       Close dialogs

  Note: a shortcut that another program has registered as a GLOBAL hotkey
  never reaches this program — Windows gives it to that program first.
  Total Commander's own Ctrl+Alt+T is the usual example, which is why this
  program does not use it.  If a shortcut seems dead, that is normally why;
  assign a different one under TOOLS ▾ → Configure shortcuts.

Multi-Rename Tool  (Ctrl+M)
---------------------------
  Renames many files at once from a template.  Select the files first, then
  press Ctrl+M.  The preview list shows every old → new name before anything
  is written, and problems are marked in red — the Rename button stays
  disabled until they are resolved.

  Placeholders:  [N] name   [N2-5] characters 2-5   [E] extension
                 [C] counter (Start / Step / Digits fields, or [C:10:2:4])
                 [P] parent folder   [d] date   [t] time
                 [Y] [M] [D] [h] [m] [s]   [G] size in bytes
  Search / replace runs after the template, with optional regular expressions.
  Case: unchanged / lowercase / UPPERCASE / Title Case / First letter upper.

  "Undo last rename" puts every name in the batch back the way it was.
  Renaming happens in two phases via temporary names, so swapping two names
  (a→b and b→a in the same batch) works correctly.

Backup Rename  (Ctrl+Alt+Shift+B, or right-click ▸ Backup rename…)
------------------------------------------------------------------
  Mark (Insert) or select one or more files — the whole selection is used —
  and each file is renamed to:

      Backup<CODE>-<original name>          e.g.  Backup07F-File_manager.py

  <CODE> is a 3-character code (000…ZZZ) drawn at random but kept UNIQUE for
  each original filename, so backing up File_manager.py again and again never
  produces two files with the same name.  The used codes are remembered in
  Helpfiles/redigerare/backup_codes.json, per filename — so renaming several
  DIFFERENT programs in one go never mixes their names up: each keeps its own.

  The confirmation dialog shows the full plan and offers three choices:
     Yes         rename in place
     Yes + move  rename AND move the results to a folder you set once
                 (Settings ▸ General ▸ "Yes + move" folder)
     No          cancel
  A backup rename is in the Undo history (Ctrl+Z).

Tabs, Workspaces and per-tab sort
---------------------------------
  Each panel has its own row of tabs.  ＋ opens a clone of the current tab and
  ↩ reopens the last closed tab (Ctrl+Shift+T).  Click a tab to flash its full
  path in the status line; hover it for the same as a tooltip.

  RIGHT-CLICK a tab for everything you do TO a tab: close it, close the other
  tabs, close the tabs to the right, lock it, copy its path, move it along the
  strip, add it to an F8 pair.  There is no ✕ on the tabs — it was a tiny
  target sitting right next to the tab you meant to click.  Ctrl+W still
  closes the active tab.

  LOCK (right-click ▸ "🔒 Lock this tab") is what protects a tab.  A locked tab
  carries a 🔒 and a gold border and refuses to close — by right-click, by
  Ctrl+W and by a bulk close — until you unlock it.  The lock is saved WITH the
  Workspace, so a profile can pin the folders you never want to lose while its
  other tabs stay disposable.  "Ignore tab locks" on the Workspace bar closes
  locked tabs anyway for one clear-out, without unlocking them.

  DUPLICATE and MOVE TO THE OTHER SIDE (right-click a tab):
    • "Duplicate this tab" adds one more copy of it LAST on the same side —
      same folder, same sort, same lock.  You stay on the tab you were on.
    • "Move to the RIGHT / LEFT panel" takes the tab off this side and adds it
      last on the other one, which then shows it.
    • A LOCKED tab is COPIED instead of moved — the lock means "this tab stays
      here" — and the menu line says so before you click ("Copy to … (locked
      🔒 — this tab stays here)").  The copy is locked too.  Unlock the tab
      first to really move it.  The last tab on a side is copied the same way,
      because a side always keeps one tab.
    • Moving a tab that an F8 pair links asks first, like closing it does.
    • The new tab is never a Workspace BASE tab: with a Workspace loaded it
      arrives as an amber extra (remembered by the half-save, lock included).
      Moving a base tab away works like closing it — the saved Workspace only
      changes on Save / Update.

  A Workspace (the bar under the toolbar) saves the whole set of tabs — their
  per-tab sort order and their locks too — under a name.

    • Tabs that belong to a loaded Workspace are its BASE tabs.  Closing one
      does NOT touch the saved Workspace: only Save / Update writes the base
      list, so a tab you close is back the next time you load the profile.
    • Tabs you open AFTER loading a Workspace are EXTRA (temporary) — tinted
      amber with a "○" marker, and always closable.  These extra tabs are
      auto-remembered IN the Workspace as you work (half-save), so they come
      back next time you load it — you do NOT have to re-save for that.
    • Loading a Workspace (left-click, or right-click ▸ "Load … base + extra
      tabs") reopens the base tabs AND the remembered extras.  Right-click ▸
      "Load base tabs only" reopens just the base and forgets the extras.
    • Right-click a Workspace ▸ "Update BOTH / LEFT / RIGHT panels with current
      tabs" bakes what is open now into the base set (no popup — three direct
      choices, pick the side you want).
    • Right-click a Workspace ▸ "★ Start with this workspace" makes it load
      automatically every time the program starts (a ★ marks it on the bar).
      Click it again to turn start-up loading off.

"Go to:" — paste a path, land there  (Workspace bar, far right)
---------------------------------------------------------------
  The box at the right-hand end of the Workspace bar takes a path and sends
  the RIGHT panel straight to it — no walking down five folders, no drive
  menu, no dialog.  It stands over the right panel, so it belongs to it.
  Ctrl+Shift+G puts the keyboard in the box from anywhere.

    Enter        go
    Ctrl+Enter   go, but in a NEW tab on the right (the current one stays)
    Tab          complete the name being typed, as far as it is unambiguous
                 (the box itself is completed — nothing pops up)
    Down / ▾     the last 20 places the box actually landed on
    Esc          clear the box; on an empty box, keyboard back to the list

  It reads whatever Windows put on the clipboard:

    "C:\\Program Files\\Common Files\\VST3"   Explorer's "Copy as path" adds
                                           the quotes — they are stripped
    C:/Program Files/Common Files          forward slashes are fine
    %ProgramFiles%\\Common Files            environment variables, and ~
    file:///C:/Temp                        dragged out of a browser
    \\\\server\\share\\folder                  UNC
    D:                                     a bare drive letter = its root
    ..   or   Subfolder                    read from where the right panel
                                           stands NOW, like a shell
    a FILE instead of a folder             lands in its folder with the
                                           cursor already on the file

  A path that does not exist never opens a dialog: the box turns a steady
  dark red and the status line says why (and whether the parent folder does
  exist).  The red goes as soon as you type again — nothing blinks, nothing
  has to be clicked away.

Tab pairs — F8 jumps BOTH panels at once
----------------------------------------
  A tab PAIR links one LEFT tab with one RIGHT tab.  Pressing F8 jumps the left
  panel to the pair's left tab AND the right panel to its right tab in a single
  keypress — so you can, say, move a file from folder X (left) to Y (right),
  press F8, and be lined up to copy it from the right to Z (left), with no
  hunting for tabs.

    • A pair is linked by FOLDER (address), not by tab position — so it keeps
      working after you move or reorder tabs, and simply follows its folder to
      whatever tab shows it.
    • Pair 1 is the start pair = the leftmost tab on each side.  F8 walks
      Pair 1 → 2 → 3 → … and wraps.
    • Make a pair by right-clicking a tab ▸ "🔗 Tab pairs":
        – "Add THIS tab to a pair (as left/right)" ▸ New pair, or an existing
          Pair 2 / 3 / …  (a new pair takes the other panel's current tab for
          its other side);
        – "Save current Left + Right tabs as a new pair" captures both at once.
    • "Manage / clear pairs…" lists them, clears any, and can drop the start
      pair (1) out of the cycle so F8 walks only your own pairs.
    • Closing a tab that a pair links warns you first (it would break the
      pair) — UNLESS another tab on that side already shows the same folder,
      in which case the link just rides along on that tab and the close is
      silent.
    • Tab pairs are remembered inside the Workspace, so they come back with it.

Sorting — files and folders independently
-----------------------------------------
  LEFT-click a column header sorts the FILES  (filled arrow ▲ / ▼).
  RIGHT-click a column header sorts the FOLDERS (hollow arrow ▵ / ▿).
  So you can keep files newest-first while folders stay A→Z, for example.
  Click again on the same header to reverse that group's direction.

  The default order for a fresh tab is set in Settings ▸ General (factory
  default: files by Modified newest-first, folders by Name).  When you change
  the sort on a tab it is remembered for the rest of the session; to keep it,
  re-save the Workspace — otherwise a new tab falls back to the default.

When the folder a tab is standing in is deleted
----------------------------------------------
  It does not matter who deleted it — the other tab, another profile, another
  program.  The tab walks UP: one level at a time until it reaches a folder
  that still exists, which is where you would have gone yourself.  It is never
  thrown across the disk into the user folder; that happens only when the whole
  DRIVE has gone (a USB disk pulled out), because then there is nothing above
  to walk to.

  EVERY affected tab moves, on both sides, not only the one you are looking at
  — one delete can take the ground out from under three of them, and finding
  that out one by one as you click them is finding out too late.  The strip
  redraws itself and the status line says where the tab landed.  A tab you
  switch to whose folder went while it was sitting there opens one level up as
  well, without a word.

  A folder that is THERE but cannot be read (no rights, a disk error) is not a
  deleted one: the panel stays where it is and says why.

Task Queue — visible but never in the way
-----------------------------------------
  Copy / move / pack / unpack run in a queue, so the file manager never freezes
  while they work.  The queue window opens automatically in the bottom-right
  corner of the screen: it is NON-modal and NEVER takes the keyboard — the
  keyboard stays wherever it was, so TAB and arrow navigation keep driving the
  FILE LIST the instant a copy is queued, with no click needed.  That rule is
  absolute: the arrow keys always belong to the main program.

  The ⚡ button — four states, four colours  (in the FILE MANAGER's toolbar)
    Everything about where the queue sits is on that one button.  LEFT-click
    steps through the four states; the bolt changes colour so you can see which
    one you are in without opening anything:

      1  🟢 green    Open, no priority.  An ordinary window — the file manager
                     and any other program may cover it.
      2  🟠 orange   Open, always above the FILE MANAGER, and nothing else.
                     Switch to a browser and the browser covers it.
      3  🔴 red      Open, above EVERYTHING, for good.  The aggressive one.
      4  ⚡ plain    Closed.  Original colour — nothing is on screen.

    RIGHT-click the ⚡ button closes it from any state.  The state is
    remembered, and the button always shows what is actually on screen: after a
    restart the first click gives you state 1.  The number on the button is
    still the count of pending tasks, and a job WAITING for an answer still
    turns it into a red ⚠N ANSWER, whatever state it is in.

    Why state 2 exists: "above the file manager" used to be done by pinning the
    queue above the whole desktop, which put it on top of the browser and
    everything else as well.  State 2 makes the queue an OWNED window of the
    file manager instead — Windows then draws it above its owner and nowhere
    else, which is what was actually wanted.

    The queue's own toolbar shows the state (🟢 / 🟠 / 🔴) but does not set it;
    its ✖ and Escape close the window, which is state 4.
  The ⚡N toolbar button also shows how many tasks are pending; if a monitor
  change ever left the window off-screen it is pulled back onto the desktop
  when shown.
  Prefer it fully hidden?  Leave the button on state 4 and press it when you
  want to look.  (The queue window is a tool window — it does NOT appear as a
  second entry in the Windows taskbar, so it can never become a phantom you
  cannot close; the ⚡ button is how you show or hide it.)

  When a file is IN USE by another program
  ----------------------------------------
  A move cannot rename a file that something else holds open — Cubase on a
  .wav, a player on a video.  That used to stop the whole job dead.  Now you
  are asked, once, and can apply the answer to every other locked file in the
  same job:
    Copy now, delete the original later   the file can still be READ, so it is
        copied across immediately and the original is queued to be removed the
        moment the other program lets go.  Nothing is at risk in the meantime:
        the original simply stays where it is until the delete really succeeds,
        and the delete is only ever attempted while the copy exists.
        The queue is written to disk at once, so it survives a crash or a
        reboot and is retried on every start (and every 30 seconds).
        See TOOLS ▾ ▸ "🔒 Locked files waiting to be removed…".
    Try again      for when you just closed the other program.
    Skip this file leave it where it is; the rest of the job continues.
    Abort the job  stop here.
  Whatever happens, the job now FINISHES and ends with a plain-language report
  listing every file it could not handle and why ("the file is open in another
  program", "the destination drive is full", "the path is too long for
  Windows"…) — instead of an error box with a Windows error number.

  Fast lane — small files never wait behind a big one
  ---------------------------------------------------
  A copy or move that is SMALL (under Settings ▸ Transfers ▸ "Counts as small
  up to", 50 MB by default) does not join the back of the queue at all.  It
  runs in its own worker, side by side with whatever big transfer is already
  going, and is marked ⚡ in the list.  While it runs, the big job PAUSES for a
  moment (turn that off in the same place if you would rather share the disk),
  so the small file gets the whole drive and is over in a blink — then the big
  one carries on from exactly where it stopped.

  A SAME-DRIVE MOVE always takes the fast lane no matter how large it is: it
  is only a rename, so not a single byte travels and it finishes instantly.
  Moving a 9 GB file within one drive therefore never waits for anything.

  Pack and unpack stay in the ordinary queue — those are CPU work and would
  fight the big transfer instead of slipping past it.
  There are TWO small lanes, each with its own worker: ⚡ is automatic (the
  size rule) and 🚌 is filled only by hand, so a big job in the bus lane never
  holds up the tiny ones in the ⚡ lane.
  Inside the lane the SHORTEST job runs first, exactly as in the main queue —
  dropping a 35 GB transfer into the lane does not put it in front of three
  73 KB ones already waiting there.  The lane has ONE worker, so its jobs run
  one after another; they are never handed over to the main lane, because two
  streams onto one disk is the worst case there is.  When the main queue runs
  out of work it simply goes quiet and the lane carries on by itself.
    🚌 (bottom row)   in / out of the lane.  It says "🚌 Out of lane" when
                      everything you have picked is already in it.
                      RIGHT-CLICK it to empty the whole lane in one press.
                      It also moves the automatic ⚡ jobs out: they go to the
                      normal queue (marked 🛣) and stay there whatever their
                      size.  Right-click the row > "Let the program choose the
                      lane again" undoes it.
    🚌 paused        hold the lane.  A job already running in it stops at the
                      next block boundary — nothing half-written, nothing
                      thrown away — and the MAIN lane carries on.  Untick it
                      and the job picks up exactly where it stopped.
    🚌 only           the opposite: the MAIN lane stands down and the bus lane
                      gets the disk to itself.
    🗑 Out of queue   nothing to do with the lane — it takes the job off the
                      list altogether.

  Which job runs next — shortest first
  ------------------------------------
  The queue reorders itself so the work in it disappears as FAST as possible:
  it estimates how long each job will take (its bytes, weighted by type — a
  pack has to compress every byte, an unpack has to write them all out again,
  a cross-drive move is a copy plus a delete) and runs the shortest first.  A
  same-drive move goes before all of them whatever its size, because it is a
  rename and no bytes travel at all.  The point is a SHORT list: if something
  does crash, there is less half-done work to sort out.
  Jobs you drag by hand, or lock with 🔒, stay where you put them.

  The ✖ Cancel button on the progress bar belongs to the BIG job; a ⚡ job is
  measured in milliseconds and is left alone.

  Stop, pause or slow a running job
  ---------------------------------
  A running copy/move can be interrupted at any time — even a single huge file:
    • ✖ Cancel (on the progress bar) STOPS the current job.  A cross-drive MOVE
      is done as copy-then-delete, so cancelling just removes the half-written
      destination file and LEAVES THE ORIGINAL untouched — nothing is lost by a
      mistaken 9 GB move.
    • ⏸ Pause / ▶ Start hold the whole queue and let it go again.
    • A big copy GIVES WAY instead of slowing down.  Its threads run at Windows
      background I/O priority, so anything you do — opening a program, even
      Ctrl+Alt+Del — jumps ahead of it on the disk queue, and its write cache is
      flushed every 64 MB so the backlog cannot grow into gigabytes and stall
      every other program on the machine.  Neither costs you anything while you
      are not using the computer: with nothing competing, nothing overtakes it
      and the copy runs at full speed.
      There is also an outright percentage cap, OFF by default — making a copy
      sleep hands nobody a disk request, it only makes the copy last longer, so
      it is the wrong answer to "the machine is unusable".  Turn it on only when
      you want a copy to crawl.  All of it lives in Settings ▸ Transfers.
    • ⚡ Full speed on the Task Queue toolbar turns all of that off for a copy
      that is ALREADY RUNNING, if you would rather have the disk to yourself.
    • Smart Sort already runs the quick jobs first (same-drive moves, then small
      copies), so a 1 KB file is not stuck behind a huge one that has not
      started yet.

  The list is grouped into DAY sections (Today / Yesterday / weekday + date),
  and every row shows the clock time (HH:MM) the task was queued — or, once it
  has finished, the time it completed.

When a file already exists (F5 / F6)
------------------------------------
  Copying or moving onto an existing file asks what to do, with four choices:
     Overwrite old      replace the existing file with the new one
     Backup-rename old  keep the old file, renamed Backup<code>-… , and let the
                        new file take the original name — nothing is lost
     Rename new         keep both; the incoming file gets a  (2)  suffix
     Skip               leave the existing file, don't copy this one
  Tick "Apply to all remaining conflicts" first to make your choice apply to
  every remaining clash in the operation.  The Task-Queue conflict banner has
  the same options as one-click bulk buttons.

Compare Files  (Ctrl+Shift+C)
-----------------------------
  Select two files in one panel, or one file in each panel, and the two are
  shown side by side with the differences colour-marked:
    olive = changed line    green = only in the right file
    red   = only in the left file
  ▲ / ▼ jump between difference blocks.  "Binary (hex)" switches to a
  byte-for-byte hex comparison and reports the first differing offset.
  Both panes scroll together.

Synchronize Directories  (Ctrl+Shift+S)
---------------------------------------
  Compares the two panel folders (optionally the whole tree beneath them)
  and lists every file as: only left, only right, left newer, right newer,
  different, or equal.  Tick what you want and copy in either direction —
  only the differences are transferred, which is what makes this useful for
  backups.  "Compare by content" hashes the files for an exact answer instead
  of trusting size and timestamp.  Double-click a row to compare that pair.

Find Duplicate Files  (Ctrl+Shift+D)
------------------------------------
  Scans one or two folders and groups identical files.  Match by content
  (a hash — files are grouped by size first, so only real candidates are
  hashed), by name + size, or by name only.  "Select all but newest/oldest"
  picks every redundant copy for you.  Deleting goes through the Recycle Bin,
  and the program refuses to delete every copy in a group.

  Find similar — what exact hashing misses
  ----------------------------------------
  Two extra methods catch the files that are the same to you but different to
  the byte:

  Images (same picture, any size)
     Compares what the picture LOOKS like, so the same photo at 4000 px and
     at 200 px, or saved again as a low-quality JPEG, lands in one group.
     It does not see through cropping or rotation — that is the honest limit
     of the method.  Needs Pillow.

  Audio (same track, any bitrate)
     Compares the shape of the sound over time, so the same track as FLAC, as
     320 kbps MP3 and as a 96 kbps OGG lands in one group.  A different
     amount of silence at the start does not matter — the two are slid
     against each other to find the best alignment.  Only the first 90
     seconds are used.  Needs ffmpeg (Helpfiles/1---Movie/ffmpeg.exe or on
     the PATH).

  The Similarity slider sets how alike is alike enough.  88% is a good
  starting point: in testing, re-encodes of the same track scored 99-100%
  while two different tracks in the same style scored 76%.  Raise it if you
  get matches you disagree with, lower it if something obvious is missed.

  Both are slower than hashing, because every file has to be examined rather
  than just read — the progress line shows how far along it is, and Stop
  works at any time.

Opening files: F3 (built in) and F4 (your own program)
------------------------------------------------------
  F3 — the BUILT-IN reader.  Text, images and PDFs open inside this program;
  anything else is shown best-effort as text so you can always peek.

  The text reader also EDITS.  It opens read-only on purpose — F3 means "look
  at this", so a stray key press can never touch a file.  Press ✎ Edit (or
  Ctrl+E) to unlock it, edit, and Ctrl+S to save.  Details worth knowing:
    • the file is written back in the SAME encoding and with the SAME line
      endings it was read with, so a CRLF .nfo does not silently become LF;
    • it saves to a temporary file and then moves it over the original, so a
      failure half-way can never leave you with half a file;
    • a file too large to load completely can NOT be edited (saving would cut
      the rest off) — use F4 for those;
    • a binary file asks for confirmation first, because saving it as text
      would corrupt it;
    • closing with unsaved changes asks before it throws them away;
    • turn the whole thing off in Settings ▸ General if you want F3 to stay
      strictly read-only.

  F4 — an EXTERNAL program, and you decide which.  Windows only asks
  "open with…" once and then remembers forever, which is how one stray choice
  (picking Notepad that one time) turns into "F4 always opens the wrong
  program" with no obvious way back.  So this program decides for itself:

    Settings ▸ Custom openers ▸ "F4 — external program"
        Program     your editor, e.g. C:\\Tools\\MyEditor\\editor.exe
        Arguments   optional; %1 is the file name (leave empty and the file
                    is simply appended)
        Only for    optional list like  txt, nfo, log  — leave it EMPTY and
                    the program is used for every file
    Below it, the per-type list gives one program per extension, and those
    win over the F4 program (e.g. .pdf → SumatraPDF, everything else → your
    editor).

  Escape hatches:
    Shift+F4   open with the Windows association, ignoring all of the above
    Ctrl+F4    Windows' own "Open with…" box — this is how you undo an
               association you once picked by accident

Quick View Panel  (Ctrl+Q)
--------------------------
  A preview pane that follows the cursor as you move through a folder.
    Auto   picks the right view per file type
    Text   any text file, with encoding detection
    Hex    byte view for binary files
    Image  scaled to fit the pane (needs Pillow); PDFs show page 1 (PyMuPDF)
  Folders show a summary of their contents.  Everything is loaded in the
  background and size-capped, so browsing large files stays responsive.

Branch View  (Ctrl+B / Ctrl+Shift+B)
------------------------------------
  Shows every file in the current folder AND all its subfolders as one flat
  list — useful for finding or acting on files spread across a deep tree.
  Names become relative paths.  Ctrl+Shift+B also includes the folders.
  Press again to switch back, or simply navigate somewhere else.

Archives
--------
  Read / extract:  ZIP, RAR, 7z, TAR, GZ, BZ2, XZ, ISO, CAB
  Create:          ZIP, 7z, TAR, TAR.GZ, TAR.BZ2, TAR.XZ

  Press Enter on an archive to browse its contents, extract all or extract
  here, and test it for errors.  Alt+F5 packs, Alt+F9 unpacks.
  ZIP and TAR work with no extra software.  7z uses py7zr and RAR uses
  rarfile when they are installed; anything else (and ISO / CAB) goes through
  7-Zip, so installing 7-Zip from www.7-zip.org covers every format.
  You can also drop 7z.exe in Helpfiles/redigerare/.
  If 7-Zip is missing and the Ninite installer is in Helpfiles/0---Ninite/
  (7-zip.exe), the program offers to run it and notices by itself when
  7-Zip is installed - no restart needed.

Checksums  (Ctrl+Shift+K)
-------------------------
  Calculates CRC32, MD5, SHA1, SHA256 or SHA512 for the selected files and
  saves them as a standard .sfv / .md5 / .sha256 file.
  Selecting an existing checksum file and pressing Ctrl+Shift+K verifies it
  instead: every entry is re-hashed and reported as OK, FAILED or MISSING.

Split / Combine  (Ctrl+Alt+S / Ctrl+Alt+C)
------------------------------------------
  Split cuts a large file into numbered parts (.001, .002 …) at a size you
  choose, and writes a small .crc file alongside them.
  Combine joins them back together — select any part and the join always
  starts from .001.  When the .crc file is present the result is verified,
  so a missing or damaged part is reported rather than silently accepted.

Directory Hotlist  (Ctrl+D)
---------------------------
  Your favourite local folders, each with a name you choose.  Open one in the
  active panel, or explicitly in the left or right panel.  Folders that no
  longer exist are marked in red.  This is separate from Network Favourites
  (\\\\server\\share) and from Workspaces (saved panel layouts).

Command Bar  (Ctrl+L)
---------------------
  A command line at the bottom of the window that runs in the active panel's
  folder.  Choose CMD or PowerShell per command; output appears inline.
    Up / Down   walk through the command history (saved between sessions)
    cd <folder> navigates the panel itself
    cls         clears the output
    🗔 New window  runs it in a real console window instead
  History is remembered across restarts.

Command Library  (Ctrl+Alt+L)
-----------------------------
  Commands you use often, each stored with the shell it belongs in.
  Select a row and press Space to tick it; "Run checked in sequence" then
  runs them one after another, each waiting for the previous to finish.
  Placeholders expanded before running:
    %P  active panel folder        %p  other panel folder
    %N  selected file name         %F  selected file, full path
    %M  all selected names         %L  all selected full paths
    %E  extension                  %B  name without extension

Print / Export Listing  (Ctrl+P)
--------------------------------
  Exports the folder contents as TXT, CSV, HTML or PDF, with a live preview.
  Choose which columns to include, whether to recurse into subfolders, and
  whether to list only the selected items.  "Print…" sends it to the default
  printer.  PDF export uses reportlab, falling back to PyMuPDF.

  Include:  list "Files and folders", "Files only" or "Folders only" — so a
  listing can be a pure file list or a pure folder tree without hand-editing
  the result afterwards.

  "Compact tree" is the fourth choice: one line per folder with its files
  listed after it, so a whole build tree fits on a screen instead of taking a
  page per folder.  It reads

      Folder-exe\\Tower    Tower.exe, Tower.ico    [V2.1.3]

  Levels:  next to "Include subfolders", how far down to go.  0 means all the
  way down, which is what the checkbox on its own always did.  1 is the start
  folder only, 2 adds its subfolders, and so on — that is how you list three
  levels of a big drive without waiting for a listing 400 000 lines long.

  Name filter:  comma-separated wildcards, e.g.  *.exe,*.dll  or  Backup* .
  It applies to FILE names only; folders are never filtered away, because
  hiding a folder would silently hide everything underneath it.

  Size in:  "Auto" gives every row the unit that reads best — 834 KB, 1.5 GB.
  That is right for reading and wrong for everything else: sorted, 9 KB lands
  above 8 MB, and no spreadsheet can sum a column of mixed units.  Pick a
  fixed unit (Bytes / KB / MB / GB / TB) and the cells become bare numbers
  with the unit in the heading instead — "Size (MB)" — which is the column
  you want in a CSV.

  The line under the title gives the TOTAL: "1 204 items · 3.4 GB".  It counts
  files only, so folders do not add a phantom size, and it follows the filter
  and the depth limit — the total is always the total of what you can see.
  There is deliberately no total row at the bottom of the CSV: that file is a
  data table, and a total row inside it breaks every sum written against it.

  Version:  a column (and, in the compact tree, a [V2.1.3] at the end of the
  line) with the version stamp found in the name.  It looks in the files
  first, then in files the filter hid, and last in the folder's own name.
  V2, v1.2, V2026-09-03 and v1_2_3 are all understood; a word that merely
  ends in a digit, like "Preview3", is not a version.

  Find:  narrows the PREVIEW to the lines containing a word.  Save and Print
  always write the complete listing; 📋 Copy is the one that follows what is
  on screen, so a search can be copied out on its own.

  Once a print or an export has gone through, the marks in the panel are
  cleared — the selection has done its job, and the next operation no longer
  inherits it by accident.  Uncheck "Clear the marks after a successful
  print / export" if you want to export the same selection several times.

  Every choice in this window (format, columns, Include, recursion, levels
  and the name filter) is remembered for next time.

Deleting  (F8 marks, the 🗑 window carries it out)
--------------------------------------------------
  Delete never removes anything straight away. It MARKS what you selected:
  the items disappear from the panel, but they are still on disk, untouched.

  The 🗑 toolbar button shows how many are waiting and opens the list, with
  when each was marked and how long it has been waiting:

    ↩  Put back            unmark — it reappears in the panel, untouched
    🗑  Carry out deletion  deletes the selected marked items, for real
    🗑  Carry out ALL       deletes everything in the list

  "For real" means the Recycle Bin, or permanent removal, according to YOUR
  Windows setting for that drive — this program does not override it. If you
  have told Windows not to use the Recycle Bin on a drive, files from that
  drive go for good.

  Crash-safe
    The list is written to disk the instant you mark something, not when the
    program closes. A crash or a power cut cannot lose it — the marks are
    still there next time you start, and so are the files.
    Stored in Helpfiles/redigerare/pending_delete.json.

  Carrying it out by itself
    TOOLS ▾ → Dates & deletion can turn on: "At start-up, carry out deletions
    marked more than N days ago" (8 by default). It is OFF unless you switch
    it on, so nothing is ever deleted without you having asked for it.
    Anything younger than the limit is left alone.

File Dates — what changes them  (TOOLS ▾ → Dates & deletion)
------------------------------------------------------------
  Two operations can be told what to do with the "Modified" date:

    Unpacking   keep the dates stored inside the archive (default), or give
                everything you unpack today's date instead.
                Note: ZIP used to lose the original date whatever you wanted
                — Python's ZIP reader does not restore timestamps, while TAR,
                GZ and 7z do. That is fixed; all formats now follow this
                setting alike.
    Copying     the copy keeps the original's date (default), or is dated now
                as if freshly made.

  These never change a file's date, whatever you set:
    •  Renaming a file or folder
    •  Moving it — the file keeps its date. Only the folder it left and the
       one it arrived in get a new date, and that is Windows doing it, not
       this program.
    •  Changing attributes (read-only, hidden, system, archive)
    •  Packing — the archive stores the original dates

  To set a date deliberately, use "Change attributes…" below.

Attributes and Dates  (right-click → Change attributes…)
--------------------------------------------------------
  Read-only, Hidden, System and Archive, on the whole selection at once —
  not just one file.

  Where the selected items disagree about a flag, its box starts marked
  "(mixed — left unchanged)" and is not touched. Click it and it says
  "(will be applied to all)" — so setting Read-only on ten files cannot
  quietly clear Hidden on the three that had it.

  "Also set the modified date" stamps a date and time of your choosing
  (YYYY-MM-DD and HH:MM:SS), with a "Now" button for the current moment.

  "Also apply to everything inside selected folders" works down the tree.

The ★ flag  (the ★ toolbar button, or Ctrl+Alt+M)
-------------------------------------------------
  A single tick you put on a file or a folder by hand, shown as ★ in its own
  narrow column between Type and Size.  It means whatever you want it to mean
  — most usefully "I have dealt with this one".

  It exists for the working folder you empty a bit at a time: send a file off
  somewhere, tick it when the answer comes back, and the column tells you at
  a glance what is still outstanding — without you having to delete anything
  to keep track.

  Setting it
    Select one or more items and press the ★ button (it sits just before 🗑),
    or Ctrl+Alt+M, or right-click → Tags → "Flag / unflag".
    If everything selected is ALREADY flagged the same action clears them;
    with a MIXED selection it fills the gaps rather than inverting each row,
    because "make these all done" is nearly always what was meant.

  Finding them again
    Click the ★ column header to sort every flagged row to the top.
    Or type in the Filter box:
       *     show only the flagged items
       -*    show only the ones still WITHOUT a ★ — what is left to do
    Right-click → Tags → "Clear ALL ★ flags…" wipes the lot in one go.

  The flag is NOT the red multi-select marking (Insert / Shift+arrows), and
  it is not one of the colour labels below — it survives closing the program,
  changing folder and restarting, and it follows a file when you rename or
  move it here, exactly as the colour tags do.  A COPY does not inherit it.
  It is stored beside the tags, in Helpfiles/redigerare/tags.json, so no file
  is ever modified to carry it.  FTP panels and the inside of an archive have
  no flags — there is nothing on disk there to attach one to.

File Tags  (Ctrl+G)
-------------------
  Colour labels you put on files and folders, independent of where they sit.
  A file can carry several; the Tags column shows them and colours the row.

  Right-click → Tags lists every label with what the selection already has:
    ✓  every selected item has it        –  only some of them do
  Clicking a label adds it to everything selected, or removes it if they all
  had it already.  "Clear tags from selection" wipes them.

  Finding them again
    Type  tag:Work  in the Filter box to show only what carries that label —
    it matches partial names too, so  tag:wo  finds "Work".
    Or open TOOLS ▾ → File tags to see every tagged file in one list, from
    anywhere on the disk, and jump straight to it.

  Managing labels
    Add, rename, recolour or delete labels in the same window.  Renaming a
    label updates every file that carries it; deleting one removes it from
    those files but never touches the files themselves.
    "Remove tags from missing files" cleans up after files deleted elsewhere.

  Tags follow their files
    Because tags are stored beside the files rather than inside them, they
    are keyed by path — and a rename or move would normally break that link.
    It does not here: renaming (single, dialog or Multi-Rename) and moving
    through the file manager both carry the tags along, including every
    tagged file inside a folder you move.
    A COPY deliberately does not copy the tags — the new file is a new thing
    until you tag it yourself.
    Moving or renaming a file OUTSIDE this program (in Explorer, say) does
    break the link — but it can usually be repaired. When a file is tagged,
    its size and a signature of its contents are recorded alongside the
    labels. "🔎 Find renamed files" in the tag manager uses those to find the
    file again under its new name, in the same folder or in either panel.
    It matches on content, never on the name — the name is the thing that
    changed. A match is only accepted when it is unambiguous: if two files
    have the same size and signature, neither is chosen, and a file edited
    after being renamed no longer matches at all. Whatever cannot be matched
    stays listed in red for you to deal with.

  Stored in Helpfiles/redigerare/tags.json — nothing is written to the files
  or to NTFS, so this works on any drive, including network shares.

Send To — Your Own Programs
---------------------------
  Right-click any file → "Send to".  The submenu lists only the tools that
  apply to what is selected, so an audio tool appears on .wav files and not
  on your text files.

  Define them under TOOLS ▾ → Configure my tools:
    Name        what appears on the menu
    File types  .mp3 .wav .flac …   or  *  for any file
                (leave empty and tick "folders" for a folders-only tool)
    Shell       CMD or PowerShell
    Command     the same placeholders as everywhere else, so
                  %F  the selected file        %L  every selected file
                  %P  the current folder       %N  just the file name
    "Start it and let go" gives the tool its own window; untick it to capture
    the output in the command bar instead.

  Example — hand a file to one of your own Python programs:
      python "C:\\1---Python\\MyTool.py" "%F"

  This is what a generic file manager cannot do: it does not know about the
  rest of your toolbox, but you can tell this one.
  Saved in Helpfiles/redigerare/tools.json.

Disk Usage  (Ctrl+Alt+D)
------------------------
  A picture of where the space went, instead of a column of numbers.  Every
  file is a rectangle sized by how much room it takes, so whatever is filling
  the drive is simply the biggest block on the screen.  Folders are drawn as
  dark frames with their contents nested inside.

  Colours are by file type — video, images, audio, archives, programs, text,
  PDF — with a legend along the bottom.
    Hover        shows the full path, the size and the share of the view
    Click        goes into a folder
    Right-click  or the Up button goes back out
    Double-click a file takes the panel to it, ready to act on
  The scan runs in the background and can be stopped at any time.

Command Palette  (Ctrl+Shift+P)
-------------------------------
  One searchable list of everything the program can do — every action, every
  hotlist folder, every saved command, every workspace.  Start typing and the
  list narrows; the shortcut for each command is shown next to it.
  Matching is loose, so initials work: "mrt" finds the Multi-Rename tool,
  "dup" finds the duplicate finder.  Enter runs the highlighted entry,
  ↑ / ↓ move, Esc closes.

Undo History  (Ctrl+Z)
----------------------
  Every copy, move, rename and new folder is written to a small log, and the
  most recent steps can be reverted — "Undo last step" or "Undo last 5".
  Steps are undone from the newest down, which is the only order that makes
  sense when later operations may build on earlier ones.

  What can honestly be undone:
    Move / rename   yes — the file goes back where it came from
    New folder      yes, while it is still empty (a folder you have since
                    put files into is left alone)
    Copy            yes — the copy is deleted, the original untouched
    Delete          yes — Delete renames the item to a ~deleted~ trash name;
                    undoing (or "Restore" in the 🗑 window) renames it back.
    Purge (from 🗑)  no — once physically purged it is in the Recycle Bin;
                    only Windows can bring it back from there.
    Unpack / pack   no — kept in the history for reference only

  Where an operation OVERWROTE a file that was already there, what it
  replaced is gone for good; no undo can bring it back.  Those items are
  reported and skipped rather than guessed at, so undoing a copy can never
  leave you with neither version.

  "Details…" shows every source → destination pair in an operation.
  The log lives in Helpfiles/redigerare/oplog.json and keeps the last 300
  operations, so it survives a restart.

Delete and the trash  (F8 / Delete)
-----------------------------------
  Delete does NOT leave a file hiding on disk under its own name.  It RENAMES
  the item in place to  ~deleted~<date>~<original name>  — which frees the
  original name immediately (reuse it at once, here or in any other program)
  and hides the ~deleted~ item from the panels.

  A start-up sweep then PHYSICALLY removes old trash (to the Recycle Bin):
    • small files  (under a size you set, default 5 MB) after some WEEKS
    • larger files after some HOURS (capped at 30)
  so a big file never lingers taking space, yet an accidental delete still
  gives you time to get it back.

  The 🗑 toolbar button opens the trash: Restore an item to its original name,
  Purge selected now, or Empty ALL now (ignores the age limits).  Ctrl+Z also
  restores the most recent delete.  All the thresholds — sizes, weeks, hours,
  and the start-up delay — are in ⚙ Deletion settings.  Prefer the plain
  Windows Recycle Bin instead of the in-place trash?  Turn off "Use the
  in-place trash" there.

Network Shares  (Ctrl+Alt+N)
----------------------------
  Finds what a machine actually offers, so \\\\TOWER\\Film can be opened
  straight into a panel instead of being typed by hand.
    • Type a computer name or IP and press "Show shares".
    • Or run a LAN scan (NET ▾ → Scan …), right-click a host and choose
      "Show shares of this host" — or of ALL hosts found, in one go.
  Each share is probed to show whether it really opens ("opens") or needs
  credentials ("no access").  Optionally includes hidden admin shares
  (C$, ADMIN$).  From the result you can open it in either panel, add it to
  the hotlist, or map it to a drive letter.

  Reconnecting several at once
    "Save ALL as network favourites" turns every usable share in the list
    into a favourite in one step, each with its own free drive letter.
    Unreachable shares, printers and hidden admin shares are skipped, and
    anything already saved is left alone.
    Afterwards, NET ▾ → Activate All Favorites reconnects the whole set with
    one click — scan, save, reconnect, without typing a single path.

Which one is newest?  (⚖ — the scales, between ⚡ and 🗑)
--------------------------------------------------------
  A toggle you can simply leave switched on.  While it is in, every file NAME
  that exists in BOTH panels is compared by its modified time:

      GREEN   this side holds the NEWER copy
      RED     this side holds the OLDER copy
      AMBER   same time but a DIFFERENT size — someone changed a copy without
              the date changing, so it is worth a look
      normal  same time and same size → unchanged, nothing to do

  Nothing is touched on disk; it is only colour, and it disappears the moment
  the button pops out.  The state is remembered between sessions.
    • Names that exist on ONE side only are left alone — there is nothing to
      compare them with.
    • FOLDERS are never coloured: a folder's own date says nothing about what
      is inside it, so colouring them would be misleading.
    • Timestamps within 2 seconds of each other count as the same moment —
      FAT keeps 2-second resolution and copies across filesystems routinely
      land a second apart, so a stricter test would paint half a folder red.
    • It re-runs by itself whenever either panel changes (navigation, a
      finished copy, the auto-refresh watcher).
  Recolour it in the code: the tags cmp_newer / cmp_older / cmp_same_diff.

Network Locations  (Alt+F1 / Alt+F2 ▸ "🖧 Network location", or NET ▾)
----------------------------------------------------------------------
  The drive menu no longer asks you to remember a \\\\server\\share by heart.
  Under "🖧 Network location" it SHOWS you what is already there:
    • every drive letter Windows currently has mapped to a share,
    • your saved network favourites,
    • the network paths you opened recently (the last 15 are remembered),
  and then the ways to find something new.

  "🔍 Find network locations…" opens a window where every row is something you
  can double-click straight into a panel:
    ⚡ Quick scan (ARP)          instant — every machine this PC has talked to.
    📡 Ping sweep this subnet    slower, but finds machines the cache missed.
    🔍 Full scanner…             the complete LAN scanner (ports, names, MACs).
  Expand a computer row and its SMB shares are listed underneath (that costs
  one `net view` call, so it only happens for the machine you actually open).
  Names are resolved in the background, so "192.168.1.42" turns into "TOWER".
  Right-click any row to open it in either panel, save it as a favourite, or
  map it to a free drive letter.  The manual path box is still there — with a
  fixed (non-blinking) cursor — for when you do know the address.

Share this PC / Connect to a PC  (NET ▾, or Tools)
--------------------------------------------------
  Two halves of one idea: reach the drives of another PC of yours with ONE saved
  login, and never type it again — also after Windows is reinstalled.

  📤 Share this PC's drives …   (run it on the PC whose drives you want to reach)
    Tick the drives and press Share.  Windows asks for Administrator rights once
    (answer Yes).  File manager then makes ONE hidden network account (default
    "pcshare") with a random password, shares each ticked drive as Drive_<letter>
    for that account (the system drive read-only), switches on the Private network
    profile, the File-and-Printer-Sharing and Network-Discovery firewall rules and
    the sharing services, and writes the connection file
        Helpfiles/redigerare/Share_out/PC_connect.json
    Running it again keeps the same account and password and only repairs things.
    On a PC that has no File manager yet: copy File_manager.py there and start it
    with the switch  --share  (python File_manager.py --share): only this window
    opens.  The file is then written beside that copy, in Helpfiles/redigerare/Share_out.

  🔌 Connect to a PC (connection file) …   (run it on the PC that should get in)
    Choose the PC_connect.json you copied over by USB.  File manager signs in,
    saves the sign-in (Windows' Credential Manager, so Explorer stops asking too,
    and net_logins.json so it returns after a reinstall), saves each share as a
    network favourite with its own drive letter and connects them.
    Or just drop PC_connect*.json into Helpfiles/redigerare (or next to
    File_manager.py) and restart: it is imported once, by itself.  A drive that
    was already mapped to that PC keeps its letter.  At every start, saved drives
    of such PCs are connected again when their letter is missing.

  🌐 Server for connection files …   (NET ▾)   no USB needed
    Give the window the address, key and secret of your own PC-connect relay (or
    paste the code from another PC and press Save).  "Share this PC" then uploads
    the connection file ENCRYPTED, and every File manager with the same settings
    fetches it at start and signs in by itself.  "Test" checks the key, "Fetch now"
    does it at once.  Setting file: Helpfiles/redigerare/pc_relay.json.

  The connection file holds the password (base64 is NOT encryption).  Copy it
  only by USB between your own PCs and never e-mail or publish it.

Phones, Cameras and Media Players  (Alt+F1 ▸ "📱 Phone / portable device")
--------------------------------------------------------------------------
  A phone plugged in as "File transfer / MTP" gets NO drive letter, so it can
  never appear in a drive list — that is why a connected phone looked missing.
  Windows exposes it only through the shell namespace, and that is what this
  reads.  The device browser lets you walk the phone's folders, and copy in
  both directions:
    ⬇ Copy to panel     device → the folder the active panel is showing
    ⬆ Copy from panel   the panel's selected files → the device folder you are in
  Windows' own copy engine does the transfer, so you get its progress dialog
  and its retry handling for a flaky USB cable.
  Files ON the device cannot be opened in place — copy them across first.

  If the phone is not listed, press "❔ Why is my phone missing?" for the
  checklist (unlocked screen, USB mode set to File transfer, a cable that
  carries data, and the "Allow access?" prompt answered).
  A phone set to "USB drive / mass storage" instead DOES get a drive letter —
  it then shows up as a Removable drive, listed in the same sub-menu.

Configurable Toolbar  (Ctrl+Alt+T)
----------------------------------
  The button row is yours to arrange.  Pick actions from the Available list,
  order them with ↑ / ↓, and insert separators.  Beyond the built-in actions
  you can add your own buttons:
    Command…  runs a CMD or PowerShell command in the active panel's folder,
              with the same %P / %N / %L placeholders as the command library.
              Output appears in the command bar.
    Folder…   jumps the active panel straight to a folder you pin.
  "Rename…" changes the caption on any button.  Apply takes effect at once,
  and the layout is saved in Helpfiles/redigerare/toolbar.json.
  "Restore default toolbar" puts everything back.

Automatic Refresh  (Ctrl+Alt+R)
-------------------------------
  The panels watch their folders and refresh by themselves when files are
  added, removed or changed by another program.  The cursor position and
  scroll position are preserved.  Branch view and FTP panels are skipped,
  and a folder being renamed in-place is never refreshed under your fingers.
  Toggle it off if you prefer to refresh manually with Ctrl+R.

Start Folder
------------
  On first launch both panels open in the program's own folder.
  After that, the last visited path is remembered automatically.
  To pin a permanent start folder: open the Alt-F1 / Alt-F2 menu
  and choose "📌 Pin current folder as start folder".

Panel Navigation
----------------
  • Only ONE panel is active at a time.  Its cursor row is DARK BLUE; the other
    panel's cursor is a muted GREY, so the two can never be confused — F5/F6 and
    the arrow keys always act on the dark-blue (active) panel.  Clicking a panel,
    or Tab, makes it active and greys the other one out.  The status bar at the
    very bottom also shows each panel on its own side — the active side is
    tinted: ◧ LEFT on the left, ◨ RIGHT on the right, each with that panel's
    folder, its file/folder count and the drive's free space; the middle tells
    you which side is active and how many items are marked.
  • Folders are blue.  A completely-empty folder (no files AND no sub-folders)
    is shown in a dimmer blue-grey so it stands out — turn this off, or change
    the colour, in Settings ▸ General ▸ Display.
  • Double-click a folder to enter it.
  • Double-click ".." to go up one level.
  • Opening a file (double-click or Enter) — three ways:
      · plain           → the WINDOWS DEFAULT program (a type in your reader-
                          extensions list opens in the built-in viewer instead);
      · Shift+open      → the BUILT-IN viewer / player (text / image / PDF /
                          audio) for ANY file;
      · Ctrl+open       → the PER-TYPE opener you set (Settings ▸ Custom
                          openers); if none for that type, the built-in viewer.
    Your F4 program is never fired by a plain double-click — it stays on F4.
  • Built-in viewer/player: text (with edit), images, PDFs, and a simple audio
    player (MP3/WAV/WMA/MID… via Windows' own codecs — Play/Pause/Stop, a
    position slider and a volume slider).  No extra software needed.
  • Use the ↑ toolbar button to go up, ↖ to jump to the drive root.
  • Insert          Toggle-mark current item, move cursor one step down.
                   Press repeatedly to mark/unmark multiple items.
  • Shift + Up / Down  Mark items while moving the cursor up or down.
  • Shift + PageUp / PageDown  The same, a big step at a time: everything the
                   cursor passes over gets marked, start and end row included.
  • Shift + Home / End  Mark from the cursor to the first / last row.
  • Ctrl+N (or numpad -) clears every mark again.
  • Right-click any item for the context menu.

Renaming Several Files in a Row
-------------------------------
  Press F2, or click once on a file that is ALREADY selected (a slow second
  click — a real double-click opens the file instead).  An edit box opens
  directly on the name.

    Type the new name, then:
      ↓ / ↑   saves it and opens the edit box on the next / previous file,
              so you can walk down a folder renaming as you go
      Enter   saves it and stops
      Escape  cancels that one name

  Clicking the Type column of a file instead edits its extension.
  Every rename this way is written to the undo history (Ctrl+Z) and takes its
  tags along, exactly like any other rename.

Column Sorting
--------------
  Click any column header (Name, Type, Size, Modified, Attr) to sort by that column.
  • First click   →  ascending  (A→Z / smallest→largest / oldest→newest)  ▲
  • Second click  →  descending (Z→A / largest→smallest / newest→oldest)  ▼
  • Third click   →  ascending again, and so on.
  The ".." (parent folder) entry always stays pinned at the top regardless
  of sort order.

  Column widths
  -------------
  Drag any column edge to resize it. The widths are remembered for next time
  — you only have to set them once. (Exact numbers can also be typed under
  the ⚙ Settings button.)

  The Tags column takes no space at all in a folder where nothing is tagged,
  so it never steals room from the dates in your ordinary folders.

  Folders sort too — including by date
  ------------------------------------
  Folders carry their own Modified date, so clicking Modified really does
  sort the folders by date.  (Total Commander cannot do this: it keeps
  folders in alphabetical order whichever column you pick.)

  TOOLS ▾ → "Folders first when sorting" decides how they are laid out:
    ON  (default)  folders stay in a block above the files, sorted by the
                   chosen column among themselves
    OFF            folders and files form one single list, so a date sort
                   interleaves them in true chronological order

  A sort of its own, for ONE folder  (sort override)
  --------------------------------------------------
  Some folders want a different order from all the others: "in XYZ123 I always
  want Name A→Z, even though the window is set to Modified newest-first".

  Right-click a folder (or right-click the empty space below the list, which
  means the folder you are standing IN) → "🔀 Sort override for this folder":
    • Remember the sort I am using now  — sort it how you like with the
      headers first, then save that as this folder's own order;
    • or pick a ready-made one: Files sorted by / Sub-folders sorted by;
    • "Also use it in this folder's sub-folders" makes one rule cover a
      whole tree (a folder's own rule always beats an inherited one);
    • "✖ Remove this folder's override" puts it back to normal;
    • "🗂 All folder overrides…" lists every rule you have, jumps to them,
      and removes the ones whose folder is gone.

  The override only applies while you stand in that folder — the window's own
  sort is never touched, so leaving the folder puts you straight back. The
  sorted column shows a 🔀 next to its arrow so you can see it is in force,
  and clicking a header while you are in such a folder edits THAT folder's
  override (otherwise the click would look like it did nothing).

  Rules live in Helpfiles/redigerare/folder_sorts.json.

Toolbar Buttons
---------------
  ↑     Go up one directory
  ↖     Go to root of current drive
  F3    View selected file.  With "F3 uses the same external program as F4"
        ticked (Settings ▸ Custom openers — ON by default) this hands the file
        to YOUR program, exactly like F4; when no program of yours covers that
        file type it falls back to the built-in reader (text / image / PDF /
        audio), whose text view can edit and save too (✎ Edit, then Ctrl+S).
        Shift+Enter always forces the built-in reader.
  F4    Open selected file in the external program you chose in Settings
  F5    Copy
  F6    Move / rename
  F7    New folder — pre-filled with the name of whatever the cursor stands on
        (a file contributes its name without the extension).  The suggestion is
        pre-selected, so just typing replaces it.
  F8    Delete
  F9    Pack   (ZIP, 7z, TAR, TAR.GZ, TAR.BZ2, TAR.XZ)
  F10   Unpack (ZIP, RAR, 7z, TAR, GZ, BZ2, XZ, ISO, CAB)
  TOOLS ▾ Multi-rename, compare, synchronize, duplicates, quick view,
        branch view, archives, checksums, split/combine, hotlist,
        command bar and library, print/export, auto-refresh, shortcuts
  FTP   Open the FTP client window
  NET ▾ Network tools (Find locations, phones/portable devices, Scan,
        Favorites, ARP quick-scan)
  SEL ▾ Selection tools — Save to file / Copy paths to clipboard
  CMD   Open Command Prompt as Administrator in the current directory
  PS    Open PowerShell as Administrator in the current directory

File Operations
---------------
  Copy (F5)    Copies the selected file / folder to the other panel.
  Move (F6)    Moves the selection; prompts for a new name if source = target.
  Rename (F2)  Renames the selected item in-place.  A slow second click on an
               already-selected row does the same (click the Type column to
               edit just the extension).  It is deliberately switched off while
               MORE THAN ONE row is selected or marked, and it is cancelled the
               moment you start to drag — so dragging a multi-selection into
               another program can never leave a file in edit mode.
  Delete (F8)  MARKS the selection for deletion. Nothing is removed yet:
               the items vanish from the panel but stay on disk until you
               carry the deletion out. See "Deleting" below.
  Pack (F9)    Creates an archive from the selection — you choose the format
               (ZIP, 7z, TAR, TAR.GZ, TAR.BZ2, TAR.XZ), the name and where
               it goes.
  Unpack (F10) Extracts the selected archive(s) into the other panel's folder.
               Runs in the background with a progress dialog.

Save Selection to File
----------------------
  Toolbar: SEL ▾ → "Save selection to file…"
  Saves the names of all selected files and/or folders to a .txt file.
  A dialog lets you choose:
    Files   — with or without file extensions.
    Folders — folder name only, or recursively list all contents underneath.
  Select multiple items with Shift+click or Ctrl+click first, then open SEL ▾.

Copy Paths to Clipboard
-----------------------
  Toolbar: SEL ▾ → "Copy paths to clipboard"
  Copies the full path of every selected item to the clipboard, one per line.
  Select multiple items with Shift+click or Ctrl+click first, then open SEL ▾.

FTP Client
----------
  Click the FTP toolbar button to open the FTP client window.
  • Add, edit, or delete FTP sites (saved in Helpfiles/redigerare/ftp_sites.json).
  • Connect to an FTP or FTPS server (SFTP requires Paramiko).
  • "Open in left / right panel" mounts the FTP directly in a panel.
  • Download, upload, create folders, rename, and delete remote files.

Checkboxes (toolbar right side)
--------------------------------
  Hidden   Show / hide hidden files and folders.
  System   Show / hide system files and folders.

Status Bar
----------
  Shows current path and free / total disk space for each panel.

Right-Click Context Menu
-------------------------
  View/Edit, Copy (F5), Move (F6), Rename (F2), Delete, New Folder,
  Properties, Open Command Prompt (Admin), Open PowerShell (Admin),
  Export Path.

  Note: "Save selection to file" and "Copy paths to clipboard" are in the
  SEL ▾ toolbar button to preserve multi-file selections.

Search  (🔍 / Ctrl+F)
---------------------
  Opens a non-blocking Search window.  The main window stays fully usable
  during the search.

  File name        Glob-pattern for file/folder names.
                 Examples:  *.txt   report*   2024*   (empty = all files)
  Search in files  Optional text to find inside file contents.
                 Searched in: txt log md nfo json xml csv yaml ini py …
                 Leave empty to search by name only.
  Start folder     Root directory to start from (defaults to active panel).
                 Click … to browse.
  Options        Case-sensitive toggle; include/exclude sub-directories.

  Press ▶ Search or Enter to start.  ■ Stop cancels at any time.
  Double-click a result → navigates the active panel to that location.
  📁 blue  = folder match   📄 green = content match   📄 plain = name match

Drag & Drop
-----------
  Requires the tkinterdnd2 library (pip install tkinterdnd2).
  Once installed, drag and drop works automatically on the next launch.

  Drag OUT  Select one or more files/folders, then drag them to any program
            that accepts files (Explorer, VS Code, desktop, etc.).

  Drop IN   Drag files from Explorer or another program onto either panel.
            The panel highlights in blue while hovering.
            External drops are always Copied to the panel's current folder.

  Panel ↔ Panel
            Drag from one panel and drop onto the other.
            A dialog asks whether to Copy or Move.

  A click stays a click.  The mouse has to travel a dozen pixels with the
  button down before a drag begins, and dropping items back where they
  already are does nothing at all — so clicking a file just to give that
  panel the focus can never turn into a drag-and-drop error.  Every drop
  goes through the Task Queue, which handles name clashes, files another
  program has open, and cancelling / pausing a big transfer.

Tips
----
  • Swedish characters (å, ä, ö) are fully supported in all text fields.
  • FTP site passwords are stored in plain text in ftp_sites.json — keep
    that file in a safe location.
  • Unpacking is performed in the background; the panel refreshes when done.
  • Select multiple items with Shift+click or Ctrl+click, then use SEL ▾
    to save names to a file or copy full paths to the clipboard.
  • The window size and position are remembered between sessions, along with
    both panels' folders, the Quick View state and the command history.

Files the program keeps
-----------------------
  Everything lives next to the program itself, so it works the same from a
  folder or as an EXE placed anywhere:

    Helpfiles/redigerare/settings.json      all settings + window geometry
    Helpfiles/redigerare/keymap.json        your keyboard shortcut changes
    Helpfiles/redigerare/toolbar.json       your toolbar layout
    Helpfiles/redigerare/tools.json         your "Send to" tools
    Helpfiles/redigerare/tags.json          file tags + label colours
    Helpfiles/redigerare/pending_delete.json  items marked for deletion
    Helpfiles/redigerare/oplog.json         undo history
    Helpfiles/redigerare/hotlist.json       directory hotlist
    Helpfiles/redigerare/commands.json      command library
    Helpfiles/redigerare/ftp_sites.json     FTP sites
    Helpfiles/redigerare/workspaces.json    saved panel layouts
    Helpfiles/0---Empty/File_manager.log        activity log
    Helpfiles/0---Empty/File_manager_crash.log  crash diagnostics
    Icons/File_manager.ico                  window / taskbar icon

Optional extras
---------------
  The program runs without any of these — each one just adds a feature:
    pillow        image preview and Quick View image mode
    pymupdf       PDF rendering (viewer and Quick View)
    py7zr         7z archives without 7-Zip installed
    rarfile       RAR archives without 7-Zip installed
    reportlab     nicer PDF export of folder listings
    tkinterdnd2   drag and drop with Explorer
    7-Zip         ISO / CAB / RAR / anything else (www.7-zip.org)
    numpy         audio matching in the duplicate finder
    ffmpeg        audio matching — put ffmpeg.exe in Helpfiles/1---Movie/
"""


# ── Helpers ────────────────────────────────────────────────────────────────

def _log(msg: str):
    try:
        with open(LOG_PATH, "a", encoding="utf-8") as fh:
            fh.write(f"{datetime.now():%Y-%m-%d %H:%M:%S}  {msg}\n")
    except Exception:
        pass


# ══════════════════════════════════════════════════════════════════════════
#  Cursor trace log  (revAP)
# ══════════════════════════════════════════════════════════════════════════
#
# "Tab to the left, grey turns blue, press Enter — and the FIRST FILE BELOW the
# marker starts."  Three separate causes for that have been found and fixed by
# reasoning about the code, and it still happens, so the guessing stops here:
# every single thing that touches a panel cursor now writes a line, and the
# line carries the FULL state of BOTH panels at that moment.  When it happens
# again the log says which call moved the cursor, and what the state was one
# step earlier.
#
# On by default, because the fault is rare and unpredictable — a log you have
# to remember to switch on first is a log that is always off when the thing you
# were waiting for finally happens.  Plain text, one line per event, and it
# prunes itself: anything older than `trace_hours` (default 48) is dropped at
# startup and every half hour, with a hard size cap as a backstop so a runaway
# loop can never fill the disk.
#
# Settings ▸ General ▸ "Cursor trace log".

_TRACE_MAX_BYTES = 40 * 1024 * 1024      # hard backstop, ~40 MB
_TRACE_LOCK      = threading.Lock()


class _CursorTrace:
    """Append-only trace of everything that moves a panel cursor."""

    def __init__(self):
        self.enabled = True
        self.hours   = 48
        self._seq    = 0
        self._fh     = None

    def configure(self, enabled: bool, hours: int):
        was = self.enabled
        try:
            self.hours = max(1, min(720, int(hours)))
        except Exception:
            self.hours = 48
        if was and not enabled:
            self.write("TRACE", note="log switched OFF from Settings")
        self.enabled = bool(enabled)
        if enabled and not was:
            self.write("TRACE", note="log switched ON from Settings")

    def _open(self):
        if self._fh is None:
            self._fh = open(TRACE_PATH, "a", encoding="utf-8", errors="replace")
        return self._fh

    def close(self):
        try:
            if self._fh is not None:
                self._fh.close()
        except Exception:
            pass
        self._fh = None

    def write(self, event: str, panels: str = "", note: str = "",
              caller: str = ""):
        """One line.  Never raises."""
        if not self.enabled:
            return
        try:
            self._seq += 1
            stamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S.%f")[:-3]
            line = f"{stamp} #{self._seq:06d} {event:<18}"
            if caller:
                line += f"[{caller}] "
            if panels:
                line += panels
            if note:
                line += "  | " + note
            with _TRACE_LOCK:
                fh = self._open()
                fh.write(line + "\n")
                fh.flush()
        except Exception:
            pass

    def prune(self):
        """Drop lines older than self.hours, then enforce the size cap.

        Rewrites into a sibling and renames, so a crash halfway through can
        never leave a half-written log behind.
        """
        try:
            if not TRACE_PATH.exists():
                return
            cutoff = datetime.now() - timedelta(hours=self.hours)
            size   = TRACE_PATH.stat().st_size
            with _TRACE_LOCK:
                self.close()
                keep, dropped = [], 0
                with open(TRACE_PATH, "r", encoding="utf-8",
                          errors="replace") as fh:
                    for line in fh:
                        try:
                            when = datetime.strptime(line[:19],
                                                     "%Y-%m-%d %H:%M:%S")
                        except Exception:
                            keep.append(line)      # no stamp — keep it
                            continue
                        if when >= cutoff:
                            keep.append(line)
                        else:
                            dropped += 1
                if sum(len(x) for x in keep) > _TRACE_MAX_BYTES:
                    keep = keep[len(keep) // 2:]   # size backstop
                    dropped += 1
                if dropped or size > _TRACE_MAX_BYTES:
                    tmp = TRACE_PATH.with_suffix(".tmp")
                    with open(tmp, "w", encoding="utf-8",
                              errors="replace") as fh:
                        fh.writelines(keep)
                    os.replace(str(tmp), str(TRACE_PATH))
        except Exception as exc:
            _log(f"Cursor trace prune failed: {exc}")


_trace = _CursorTrace()


# ══════════════════════════════════════════════════════════════════════════
#  My programs  —  starting your own programs fast  (revAQ)
# ══════════════════════════════════════════════════════════════════════════
#
# "It can take MINUTES to open a PDF.  An MP3 takes 20 seconds."  Measured,
# and it is neither this program nor the Windows association: the association
# already runs the right program directly ('PDFull.exe "%1"'), so there is no
# detour to remove.  The time goes on INSIDE the program being started.
#
# The cause is how those programs are built.  A PyInstaller ONE-FILE .exe is
# a self-extracting archive: every single launch unpacks the whole bundle into
# %TEMP%\_MEIxxxxxx before a line of the program runs, and the virus scanner
# then reads every file that was just written.  Measured on this machine:
#
#     PDFull.exe      171 MB   one-file   ->  "minutes"
#     MP3.exe          89 MB   one-file   ->  ~20 seconds
#     MKV-player.exe   30 MB   one-file   ->  "a few seconds"
#     Meditor.exe      11 MB   one-file   ->  "fast"
#
# — the size of the bundle IS the startup time.  But the .py the .exe was
# built from is sitting right next to it, and Python is installed, so it can
# be run directly.  Measured import cost of the same programs from source:
# PDFull 125 ms, MP3 239 ms, SeeView 69 ms.  That is the whole 171 MB unpack
# skipped: minutes become a fraction of a second.
#
# So this is a table of "for THIS file type, run THIS program of mine, THIS
# way" — the .py through pythonw.exe where that works, the .exe where it does
# not (MKV-player needs a DLL that only exists inside its bundle).  It is
# filled in for you by reading the associations you already have.

_ASSOCSTR_EXECUTABLE = 2
_PYI_COOKIE = b"MEI\014\013\012\013\016"


def _assoc_exe(ext: str) -> str:
    """Which program Windows would run for *ext* — read-only, no launching."""
    if os.name != "nt":
        return ""
    try:
        n = ctypes.c_ulong(0)      # DWORD; ctypes.wintypes is not imported here
        ctypes.windll.shlwapi.AssocQueryStringW(
            0, _ASSOCSTR_EXECUTABLE, ext, None, None, ctypes.byref(n))
        if not n.value:
            return ""
        buf = ctypes.create_unicode_buffer(n.value)
        if ctypes.windll.shlwapi.AssocQueryStringW(
                0, _ASSOCSTR_EXECUTABLE, ext, None, buf, ctypes.byref(n)) == 0:
            return buf.value or ""
    except Exception:
        pass
    return ""


def _is_onefile_exe(path: str):
    """(is_onefile, size_bytes) for a PyInstaller build.

    A one-file build carries the bootloader's cookie in its last few KB and
    has no _internal folder beside it.  Returns (None, size) when it cannot
    be read at all.
    """
    try:
        size = os.path.getsize(path)
        d = os.path.dirname(path)
        stem = os.path.splitext(os.path.basename(path))[0]
        # The payload settles it, and it is checked FIRST: a one-FOLDER .exe
        # carries the bootloader cookie too (measured on PyInstaller 6.19),
        # so a cookie-first test calls every one-folder build one-file.
        # <Name>_data is the per-program payload folder ExeForge builds with.
        if os.path.isdir(os.path.join(d, "_internal")) or \
           os.path.isdir(os.path.join(d, stem + "_data")):
            return (False, size)
        with open(path, "rb") as fh:
            fh.seek(max(0, size - 8192))
            tail = fh.read()
        return (_PYI_COOKIE in tail, size)
    except Exception:
        return (None, 0)


# ══════════════════════════════════════════════════════════════════════════
#  Build watch  —  "the source is newer than the program"  (revAR)
# ══════════════════════════════════════════════════════════════════════════
#
# Measured on 2026-09-02, same script built both ways:
#
#     one-file    13.7 MB exe                 startup 1075 ms
#     one-folder   3.1 MB exe + data folder   startup  104 ms
#
# — ten times faster on a bundle of only 14 MB, and the gap grows with the
# bundle, because a one-file .exe is a self-extracting archive that unpacks
# EVERYTHING into %TEMP% before the program runs.  PDFull is 171 MB and
# WhyBrowse 197 MB.  That is the whole of "it takes minutes to open a PDF",
# and it applies to every launch from anywhere — Tower, the desktop, a double
# click here.  One-folder pays nothing: sys._MEIPASS just points at the
# folder that is already on disk.
#
# So: build one-folder for what you RUN, and zip that folder for what you
# SHIP.  A one-file .exe only looks tidier; it charges you the unpacking on
# every single launch, for ever, to save the person you gave it to one
# unzip, once.
#
# THIS FILE MANAGER DOES NOT BUILD ANYTHING.  Building is minutes of work and
# hundreds of megabytes, and a build that dies halfway leaves a program that
# will not start — that does not belong behind a file manager's Save button.
# What it does is watch: it compares each <Name>.py it can see against the
# <Name> program that was built from it, and says which ones have moved on.
# You tick the ones you want and it writes out a ready-to-run build list for
# Exe-bygg, which is the program whose job this actually is.

_PYI_COOKIE = b"MEI\014\013\012\013\016"


def _build_kind(exe_path: str):
    """(kind, size) for a built program: "one-file", "one-folder" or "?".

    One-file carries the PyInstaller bootloader cookie in its last few KB.
    One-folder has its payload beside it instead — either the default
    _internal folder, or (the way Exe-bygg calls PyInstaller) the DLLs lying
    directly next to the .exe.

    The payload is checked FIRST and the cookie only as a fallback: measured
    on PyInstaller 6.19, a one-FOLDER .exe carries the bootloader cookie in
    its last few KB as well, so a cookie-first test labels every one-folder
    build "one-file" - and then reports for ever that the program you just
    rebuilt is still the slow kind.  <Name>_data is the per-program payload
    folder ExeForge gives each build.
    """
    try:
        size = os.path.getsize(exe_path)
        d = os.path.dirname(exe_path)
        stem = os.path.splitext(os.path.basename(exe_path))[0]
        if os.path.isdir(os.path.join(d, "_internal")) or \
           os.path.isdir(os.path.join(d, stem + "_data")):
            return ("one-folder", size)
        try:
            for f in os.listdir(d):
                low = f.lower()
                if low.startswith("python3") and low.endswith(".dll"):
                    return ("one-folder", size)
        except OSError:
            pass
        with open(exe_path, "rb") as fh:
            fh.seek(max(0, size - 8192))
            if _PYI_COOKIE in fh.read():
                return ("one-file", size)
        return ("?", size)
    except Exception:
        return ("?", 0)


def _folder_newest(path: str):
    """(newest mtime, total bytes) under a folder — what a build really is."""
    newest, total = 0.0, 0
    try:
        for root, _dirs, files in os.walk(path):
            for f in files:
                try:
                    st = os.stat(os.path.join(root, f))
                except OSError:
                    continue
                newest = max(newest, st.st_mtime)
                total += st.st_size
    except Exception:
        pass
    return (newest, total)


def build_watch_scan(source_dirs: list, build_dirs: list) -> list:
    """Compare every source .py against the program built from it.

    Returns a row per program:
        {name, src, src_mtime, src_size, exe, exe_mtime, exe_size,
         kind, state}
    where state is one of
        "newer source"  the .py has changed since the program was built
        "one-file"      built, up to date, but still the slow kind
        "never built"   there is a source and no program
        "up to date"    nothing to do

    Runs off the UI thread — it only touches the filesystem, never Tk.
    """
    sources = {}
    for d in source_dirs:
        try:
            for f in sorted(os.listdir(d)):
                if not f.lower().endswith(".py"):
                    continue
                full = os.path.join(d, f)
                if not os.path.isfile(full):
                    continue
                name = os.path.splitext(f)[0]
                sources.setdefault(name, full)
        except Exception:
            continue

    builds = {}
    for d in build_dirs:
        try:
            entries = sorted(os.listdir(d))
        except Exception:
            continue
        for f in entries:
            full = os.path.join(d, f)
            # a one-folder build is <dir>/<Name>/<Name>.exe …
            if os.path.isdir(full):
                inner = os.path.join(full, f + ".exe")
                if os.path.isfile(inner):
                    builds.setdefault(f, inner)
                    continue
                try:
                    for g in os.listdir(full):
                        if g.lower().endswith(".exe"):
                            builds.setdefault(os.path.splitext(g)[0],
                                              os.path.join(full, g))
                            break
                except OSError:
                    pass
            # … and a plain .exe sitting in the folder counts too
            elif f.lower().endswith(".exe"):
                builds.setdefault(os.path.splitext(f)[0], full)

    rows = []
    for name in sorted(set(sources) | set(builds), key=str.lower):
        src = sources.get(name, "")
        exe = builds.get(name, "")
        try:
            s_m = os.path.getmtime(src) if src else 0.0
            s_s = os.path.getsize(src) if src else 0
        except OSError:
            s_m, s_s = 0.0, 0
        kind, e_s = _build_kind(exe) if exe else ("", 0)
        if exe:
            # A one-folder build is only as new as its NEWEST file: the .exe
            # stub often does not change when only the payload does.
            e_m, folder_bytes = _folder_newest(os.path.dirname(exe)) \
                if kind == "one-folder" else (0.0, 0)
            try:
                e_m = max(e_m, os.path.getmtime(exe))
            except OSError:
                pass
            if kind == "one-folder" and folder_bytes:
                e_s = folder_bytes
        else:
            e_m = 0.0
        if src and not exe:
            state = "never built"
        elif exe and not src:
            state = "no source here"
        elif s_m > e_m + 2:
            state = "newer source"
        elif kind == "one-file":
            state = "one-file"
        else:
            state = "up to date"
        rows.append({"name": name, "src": src, "src_mtime": s_m,
                     "src_size": s_s, "exe": exe, "exe_mtime": e_m,
                     "exe_size": e_s, "kind": kind, "state": state})
    return rows


def build_watch_commands(rows: list, out_dir: str) -> str:
    """The PyInstaller command lines for the ticked rows, as plain text.

    --contents-directory <Name>_data is the part that matters and the part
    Exe-bygg currently hard-codes to ".": with ".", two one-folder programs
    built into the same folder write their DLLs on top of each other.  Giving
    each one its own payload folder is what lets the .exe keep sitting where
    everything already points at it.
    """
    lines = [
        "# One-folder builds — generated by File Manager, "
        + datetime.now().strftime("%Y-%m-%d %H:%M"),
        "#",
        "# Run these with Exe-bygg, or straight from a shell.  Each program",
        "# gets its OWN payload folder (--contents-directory), so several of",
        "# them can live side by side without overwriting each other.",
        "#",
        "# Add each program's own icon / hidden imports / bundled files the way",
        "# Exe-bygg already stores them — these lines are the skeleton, not a",
        "# replacement for what it knows about each program.",
        "",
    ]
    for r in rows:
        if not r.get("src"):
            continue
        name = r["name"]
        lines.append(f'pyinstaller -y -w --log-level WARN \\')
        lines.append(f'    --name "{name}" \\')
        lines.append(f'    --contents-directory "{name}_data" \\')
        lines.append(f'    --distpath "{out_dir}" \\')
        lines.append(f'    "{r["src"]}"')
        lines.append("")
    return "\n".join(lines)


# ══ Handing a build to ExeForge ═══════════════════════════════════════════
#
# This program watches; ExeForge builds.  The hand-off is a small JSON order
# dropped in ExeForge's inbox — no arguments to get wrong, nothing lost if
# ExeForge is not running (it reads the inbox when it starts), and nothing
# ever builds without you pressing Build over there.

EXEFORGE_PORT = 50597          # the port a running ExeForge holds open


def _exeforge_inbox() -> Path:
    """Where ExeForge looks for orders: this program's own home, and the old
    1---Blandat only when there is no home tree at all."""
    # Own home first, the old tree only after it: ExeForge, Tower and this
    # program each work the inbox out from where they themselves are, so all
    # three have to use the same order or the orders and the watcher end up in
    # different trees.
    for cand in (APP_ROOT, Path(r"C:\1---Python\1---Blandat")):
        try:
            if cand.is_dir():
                return cand / "Helpfiles" / "ExeForge" / "orders"
        except Exception:
            continue
    return APP_ROOT / "Helpfiles" / "ExeForge" / "orders"


def _exeforge_running() -> bool:
    """A running ExeForge holds a socket open as its single-instance lock."""
    try:
        with socket.create_connection(("127.0.0.1", EXEFORGE_PORT), 0.4):
            return True
    except OSError:
        return False


def _exeforge_program() -> str:
    """The built ExeForge if there is one, otherwise its .py."""
    for exe in (r"B:\0---Burn\0---Util\0---Mina_program\ExeForge\ExeForge.exe",):
        if os.path.isfile(exe):
            return exe
    # APP_ROOT / "Py" first: in the 0---Python layout APP_ROOT is the home that
    # holds Helpfiles and the programs sit one level down. It has to beat the
    # hardcoded 1---Blandat, which is still on disk and holds the old copy.
    for py in (Path(_own_dir()) / "ExeForge.py",
               APP_ROOT / "Py" / "ExeForge.py",
               APP_ROOT / "ExeForge.py",
               Path(r"C:\1---Python\1---Blandat\ExeForge.py"),
               APP_ROOT.parent / "ExeForge.py"):
        if py.is_file():
            return str(py)
    return ""


def _real_pythonw() -> str:
    """A REAL pythonw.exe to start one of his .py programs with, or "".

    NEVER sys.executable: in a build that is THIS program's own .exe, so
    "[sys.executable, some.py]" starts a second File Manager instead of the
    program asked for.  (PyManager had the same shape and fork-bombed the
    machine on 2026-09-04.)

    And never a 0-byte file: %LOCALAPPDATA%\\Microsoft\\WindowsApps\\python.exe
    and friends are App Execution Aliases, not interpreters, and which()
    finds them first wherever the Store stub is on PATH.

    pythonw before python — a console window would flash up otherwise."""
    cands = []
    if not getattr(sys, "frozen", False):
        cands.append(os.path.join(os.path.dirname(sys.executable),
                                  "pythonw.exe"))
    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 _real_python() -> str:
    """The console interpreter — python.exe — for "Run in a console" (revBH).

    Same rules as _real_pythonw: never sys.executable (in a build that is this
    program's own .exe), never a 0-byte App Execution Alias.  Only the
    preference is reversed: here a console is the whole point."""
    cands = []
    if not getattr(sys, "frozen", False):
        cands.append(os.path.join(os.path.dirname(sys.executable), "python.exe"))
    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, "python.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 _real_pythonw()          # better a window-less run than none


def send_to_exeforge(rows: list, note: str = "") -> tuple:
    """Write a build order for *rows* and start ExeForge if it is not up.

    Returns (ok, message).  rows are build_watch_scan rows; only their source
    path is needed — ExeForge works out icon, name and options itself."""
    items = [{"name": r["name"], "py": r["src"]} for r in rows if r.get("src")]
    if not items:
        return (False, "None of those have a .py to build from.")
    inbox = _exeforge_inbox()
    try:
        inbox.mkdir(parents=True, exist_ok=True)
        path = inbox / f"order_{datetime.now():%Y-%m-%d_%H%M%S}.json"
        path.write_text(json.dumps({
            "tool": "exeforge", "version": 1,
            "created": datetime.now().isoformat(timespec="seconds"),
            "source": "File_manager", "note": note, "items": items,
        }, indent=2, ensure_ascii=False), encoding="utf-8")
    except Exception as exc:
        return (False, f"Could not write the order:\n{inbox}\n\n{exc}")

    if _exeforge_running():
        return (True, f"{len(items)} program(s) sent to ExeForge — it is "
                      f"already running, look for the yellow banner.")
    prog = _exeforge_program()
    if not prog:
        return (True, f"{len(items)} program(s) written to:\n{path}\n\n"
                      "ExeForge itself was not found — start it and it will "
                      "pick the order up.")
    try:
        if prog.lower().endswith(".py"):
            # _real_pythonw(), never sys.executable: in a build that is THIS
            # program's own .exe, so ExeForge's order would have started a
            # second File Manager instead.
            exe = _real_pythonw()
            if not exe:
                return (True, "The order was written, but no python.exe could "
                              "be found to start ExeForge with.")
            subprocess.Popen([exe, prog], cwd=os.path.dirname(prog))
        else:
            subprocess.Popen([prog], cwd=os.path.dirname(prog))
    except Exception as exc:
        return (True, f"The order was written, but ExeForge would not "
                      f"start:\n{exc}")
    return (True, f"{len(items)} program(s) sent — ExeForge is starting.")


def _load_sites():
    try:
        with open(SITES_PATH, "r", encoding="utf-8") as fh:
            data = json.load(fh)
            return data if isinstance(data, list) else data.get("sites", [])
    except FileNotFoundError:
        return []
    except Exception as exc:
        messagebox.showerror("Error", f"Could not read {SITES_PATH.name}: {exc}")
        return []


def _save_sites(sites):
    try:
        with open(SITES_PATH, "w", encoding="utf-8") as fh:
            json.dump({"sites": sites}, fh, indent=2, ensure_ascii=False)
    except Exception as exc:
        messagebox.showerror("Error", f"Could not save {SITES_PATH.name}: {exc}")


def _load_json_list(path: Path, portable: bool = False) -> list:
    """Read a JSON list from disk; return [] if missing or unreadable."""
    try:
        with open(path, "r", encoding="utf-8") as fh:
            data = json.load(fh)
        if portable:
            return fm_unpack_tree(data) if isinstance(data, list) else []
        return data if isinstance(data, list) else []
    except FileNotFoundError:
        return []
    except Exception as exc:
        _log(f"Could not read {path.name}: {exc}")
        return []


def _save_json_list(path: Path, data: list, portable: bool = False):
    """Write a JSON list to disk, logging (not raising) on failure."""
    try:
        if portable:
            data = fm_pack_tree(data)
        with open(path, "w", encoding="utf-8") as fh:
            json.dump(data, fh, indent=2, ensure_ascii=False)
    except Exception as exc:
        _log(f"Could not save {path.name}: {exc}")


def _split_args(text: str) -> list:
    """Split a command-line argument string, keeping "quoted parts" together.

    Deliberately not shlex: on Windows a path like C:\\Temp\\x is full of
    backslashes and shlex would eat them as escapes."""
    out, cur, quoted = [], "", False
    for ch in text or "":
        if ch == '"':
            quoted = not quoted
        elif ch.isspace() and not quoted:
            if cur:
                out.append(cur)
                cur = ""
        else:
            cur += ch
    if cur:
        out.append(cur)
    return out


def _load_json_dict(path: Path, portable: bool = False) -> dict:
    """Read a JSON object from disk; return {} if missing or unreadable."""
    try:
        with open(path, "r", encoding="utf-8") as fh:
            data = json.load(fh)
        return fm_unpack_tree(data) if portable else (
            data if isinstance(data, dict) else {})
    except FileNotFoundError:
        return {}
    except Exception as exc:
        _log(f"Could not read {path.name}: {exc}")
        return {}


def _save_json_dict(path: Path, data: dict, portable: bool = False):
    """Write a JSON object to disk, logging (not raising) on failure."""
    try:
        if portable:
            data = fm_pack_tree(data)
        with open(path, "w", encoding="utf-8") as fh:
            json.dump(data, fh, indent=2, ensure_ascii=False)
    except Exception as exc:
        _log(f"Could not save {path.name}: {exc}")


def _human_size(n: int) -> str:
    """Format a byte count as a compact human-readable string."""
    try:
        n = float(n)
    except Exception:
        return "?"
    for unit in ("B", "KB", "MB", "GB", "TB"):
        if abs(n) < 1024.0 or unit == "TB":
            return f"{n:.0f} {unit}" if unit == "B" else f"{n:,.1f} {unit}"
        n /= 1024.0
    return f"{n:.1f} PB"


# A version stamp inside a file or folder name:  V2, v1.2.3, V2026-09-03 ...
# The letter must not sit inside a word, or "Preview3" becomes a version, and
# after the first number only more numbers may follow — that is what stops
# "Setup_v1_then_v2" from being read as one token "V1thenv2" instead of two.
# Ported from Dir_lister.py together with the listing that used it.
_VERSION_RX = _re.compile(r"(?i)(?<![A-Za-z0-9])v[0-9]+(?:[.,\-_][0-9]+)*")


def _version_token(name: str) -> str:
    """Return the last version-like token in name (e.g. 'V2.1.3'), else ''.

    The LAST one wins because a name like "Setup_v1_patched_v2.exe" describes
    what it grew into, not what it started as.
    """
    matches = list(_VERSION_RX.finditer(os.path.splitext(name)[0]))
    if not matches:
        return ""
    # v1_2_3 means the same as v1.2.3 — write it the way people read it.
    return "V" + matches[-1].group(0)[1:].replace("_", ".")


_SIZE_UNITS = ("Auto", "Bytes", "KB", "MB", "GB", "TB")
_SIZE_DIV = {"Bytes": 1, "KB": 1024, "MB": 1024 ** 2,
             "GB": 1024 ** 3, "TB": 1024 ** 4}


def _size_in_unit(n: int, unit: str) -> str:
    """A byte count in ONE named unit, or the friendliest one when "Auto".

    A listing where every row picked its own unit reads well and adds up to
    nothing: sorting it puts 9 KB above 8 MB, and a spreadsheet cannot sum a
    column of mixed units at all.  Naming the unit is what makes the column
    worth exporting.  Ported from File-sizes.py, which this replaced.
    """
    if unit not in _SIZE_DIV:
        return _human_size(n)
    if unit == "Bytes":
        return f"{int(n)}"
    return f"{n / _SIZE_DIV[unit]:.2f}"


def _show_toplevel_no_activate(win) -> bool:
    """Show a Toplevel WITHOUT giving it keyboard/mouse focus (Windows only).

    Whatever window currently has focus keeps it — the file manager if you were
    there, or another app if you had switched away.  Returns True on success;
    the caller should fall back to a normal deiconify() when it returns False.
    """
    if platform.system() != "Windows":
        return False
    try:
        win.update_idletasks()
        # winfo_id() is the Tk client frame; its Win32 parent is the real
        # top-level window (same reason the icon code uses GetParent/FindWindow).
        hwnd = ctypes.windll.user32.GetParent(win.winfo_id())
        if not hwnd:
            return False
        SW_SHOWNOACTIVATE = 4
        ctypes.windll.user32.ShowWindow(hwnd, SW_SHOWNOACTIVATE)
        return True
    except Exception:
        return False


def _make_window_no_activate(win) -> bool:
    """Give a Toplevel the WS_EX_NOACTIVATE extended style (Windows only).

    Such a window can still be clicked — its buttons work — but it NEVER becomes
    the active window, so it can't pull keyboard focus away from whatever window
    has it.  Used for the Task Queue: you can click its Resolve buttons, yet the
    arrow keys always stay in the main file manager, never in the queue.
    Returns True on success.
    """
    if platform.system() != "Windows":
        return False
    try:
        win.update_idletasks()
        user32 = ctypes.windll.user32
        hwnd = user32.GetParent(win.winfo_id())
        if not hwnd:
            return False
        GWL_EXSTYLE       = -20
        WS_EX_NOACTIVATE  = 0x08000000
        # WS_EX_TOOLWINDOW keeps the window OUT of the taskbar (and Alt-Tab), so
        # the Task Queue no longer shows up as a phantom second entry under the
        # file-manager icon that could not be closed or brought to the front.
        WS_EX_TOOLWINDOW  = 0x00000080
        WS_EX_APPWINDOW   = 0x00040000
        getf = getattr(user32, "GetWindowLongPtrW", None) or user32.GetWindowLongW
        setf = getattr(user32, "SetWindowLongPtrW", None) or user32.SetWindowLongW
        getf.restype  = ctypes.c_ssize_t
        getf.argtypes = [ctypes.c_void_p, ctypes.c_int]
        setf.restype  = ctypes.c_ssize_t
        setf.argtypes = [ctypes.c_void_p, ctypes.c_int, ctypes.c_ssize_t]
        cur = getf(hwnd, GWL_EXSTYLE)
        new = (cur | WS_EX_NOACTIVATE | WS_EX_TOOLWINDOW) & ~WS_EX_APPWINDOW
        setf(hwnd, GWL_EXSTYLE, new)
        return True
    except Exception:
        return False


def _win_set_zorder(win, insert_after: int, show: bool = False) -> bool:
    """SetWindowPos wrapper: move *win* in the z-order WITHOUT activating it.
    insert_after is HWND_TOPMOST (-1), HWND_NOTOPMOST (-2), HWND_TOP (0) or
    HWND_BOTTOM (1).  Never steals keyboard focus (SWP_NOACTIVATE)."""
    if platform.system() != "Windows":
        return False
    try:
        win.update_idletasks()
        user32 = ctypes.windll.user32
        hwnd = user32.GetParent(win.winfo_id())
        if not hwnd:
            return False
        SWP_NOSIZE     = 0x0001
        SWP_NOMOVE     = 0x0002
        SWP_NOACTIVATE = 0x0010
        SWP_SHOWWINDOW = 0x0040
        flags = SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE
        if show:
            flags |= SWP_SHOWWINDOW
        user32.SetWindowPos.argtypes = [ctypes.c_void_p, ctypes.c_void_p,
                                        ctypes.c_int, ctypes.c_int,
                                        ctypes.c_int, ctypes.c_int,
                                        ctypes.c_uint]
        user32.SetWindowPos.restype = ctypes.c_int
        user32.SetWindowPos(hwnd, insert_after, 0, 0, 0, 0, flags)
        return True
    except Exception:
        return False


def _raise_toplevel_no_activate(win, keep_on_top: bool = False) -> bool:
    """Bring a Toplevel to the FRONT of the z-order (above other apps) without
    activating it — so it becomes clearly visible but never steals the keyboard.

    keep_on_top=True leaves it as an always-on-top window (it cannot then be
    hidden by other programs) until _drop_toplevel_no_activate() demotes it;
    keep_on_top=False raises it once and lets normal windows cover it again."""
    HWND_TOPMOST   = -1
    HWND_NOTOPMOST = -2
    try:
        win.deiconify()
    except Exception:
        pass
    if platform.system() != "Windows":
        try:
            win.lift()
        except Exception:
            pass
        return False
    ok = _win_set_zorder(win, HWND_TOPMOST, show=True)
    if ok and not keep_on_top:
        # Demote to a normal (non-topmost) window but keep the position it just
        # gained at the top of the stack.
        _win_set_zorder(win, HWND_NOTOPMOST)
    return ok


def _drop_toplevel_no_activate(win) -> bool:
    """Demote a Toplevel from always-on-top back to a normal window, so other
    windows (the file manager) can cover it again."""
    HWND_NOTOPMOST = -2
    return _win_set_zorder(win, HWND_NOTOPMOST)


def _win_set_owner(win, owner_hwnd: int) -> bool:
    """Give a Toplevel an OWNER window — the real "above that window only".

    WS_EX_TOPMOST does NOT mean "above the file manager"; it means above the
    entire desktop, browser and all.  An OWNED window is the middle setting
    Windows actually provides: it is always drawn above the window that owns
    it, and is an ordinary window in every other respect, so any OTHER program
    still covers it.  owner_hwnd=0 removes the owner again.

    Done with SetWindowLongPtrW(GWLP_HWNDPARENT) rather than Tk's
    `wm transient` on purpose: transient RECREATES the wrapper window, and the
    no-activate + tool-window styles this window depends on (never owns the
    keyboard, never appears in the taskbar) would go with it.  This call
    touches nothing but the owner field.
    """
    if platform.system() != "Windows":
        return False
    try:
        win.update_idletasks()
        user32 = ctypes.windll.user32
        hwnd = user32.GetParent(win.winfo_id())
        if not hwnd:
            return False
        GWLP_HWNDPARENT = -8
        setf = getattr(user32, "SetWindowLongPtrW", None) or user32.SetWindowLongW
        setf.restype  = ctypes.c_ssize_t
        setf.argtypes = [ctypes.c_void_p, ctypes.c_int, ctypes.c_ssize_t]
        setf(hwnd, GWLP_HWNDPARENT, ctypes.c_ssize_t(int(owner_hwnd or 0)))
        # The new relationship only shows once the z-order is touched.
        _win_set_zorder(win, 0)          # HWND_TOP, no activation
        return True
    except Exception:
        return False


def _friendly_oserror(exc: OSError) -> str:
    """Turn an OSError into something worth reading.

    Windows reports these as numbered errors in the SYSTEM's language, which is
    no help at all in an English program — and "[WinError 32]" tells you nothing
    about what to do.  The common ones get a plain sentence that names the cause
    AND the fix; anything else falls back to the OS text.
    """
    win = getattr(exc, "winerror", None)
    table = {
        32:  "the file is open in another program — close it and try again",
        33:  "part of the file is locked by another program",
        5:   "access denied — the file is read-only, or this needs "
             "administrator rights",
        19:  "the drive is write-protected",
        112: "the destination drive is full",
        2:   "the file no longer exists",
        3:   "the folder no longer exists",
        145: "the folder is not empty",
        183: "a file with that name already exists at the destination",
        206: "the full path is too long for Windows",
        1392: "the file is corrupt and unreadable",
    }
    # "Permission denied" on a file nothing has open is almost always the
    # READ-ONLY attribute, and saying "close it and try again" about a file
    # that is not open anywhere sends you looking for a program that does not
    # exist.  Ask the file itself before guessing (revBI).
    if win in (5, None) and isinstance(exc, PermissionError):
        name = getattr(exc, "filename", None)
        try:
            if name and os.path.exists(name) and not os.access(name, os.W_OK):
                return ("the file is READ-ONLY — nothing has it open; clear the "
                        "read-only attribute (right-click ▸ Change attributes…)")
        except Exception:
            pass
    if win in table:
        return table[win]
    if isinstance(exc, PermissionError):
        return "permission denied (it may be open in another program)"
    if isinstance(exc, FileNotFoundError):
        return "the file no longer exists"
    txt = (getattr(exc, "strerror", "") or str(exc)).strip()
    return txt or exc.__class__.__name__


def _nearest_existing_dir(path: str) -> str:
    """Walk UP from *path* until a folder that still exists is reached.

    A tab standing in a folder that somebody deletes — from another tab,
    another profile, or another program entirely — must not be thrown across
    the disk into the user folder.  It should come up one step at a time until
    it lands somewhere real, which is where you would have gone yourself
    (revBU).

    The root of the drive is the last stop.  Only when the whole DRIVE has gone
    (a USB disk pulled out, a mapped drive dropped) is there nothing above to
    walk to, and only then does a general fallback make any sense.
    Returns "" if even that fails.
    """
    try:
        p = os.path.abspath(path or "")
    except Exception:
        return ""
    seen = set()
    while p and p not in seen:
        seen.add(p)
        try:
            if os.path.isdir(p):
                return p
        except Exception:
            pass
        parent = os.path.dirname(p)
        if not parent or parent == p:
            break            # the root of a drive, or of a UNC share: the top
        p = parent
    for cand in (os.path.expanduser("~"), DEFAULT_START_DIR):
        try:
            if cand and os.path.isdir(cand):
                return os.path.abspath(cand)
        except Exception:
            pass
    return ""


def _path_is_network(path: str) -> bool:
    """A UNC path (one that starts with two backslashes).

    Testing one whose server is down can block for seconds, so the tab sweep
    leaves them alone: a stale tab is better than a window that stops
    answering."""
    try:
        return str(path or "").startswith("\\\\")
    except Exception:
        return False


def _win_app_is_foreground(win):
    """True / False / None — does THIS program own the foreground window?

    Used before any focus_force(): if the user has switched to Explorer or a
    browser, pulling focus back would be rude, and if another of our own
    windows has it, taking it away starts a tug-of-war.  None means "cannot
    tell" (not Windows, or the call failed), and callers treat that as "leave
    focus alone"."""
    if platform.system() != "Windows":
        return None
    try:
        user32 = ctypes.windll.user32
        fg = user32.GetForegroundWindow()
        if not fg:
            return None
        pid = ctypes.c_ulong(0)
        user32.GetWindowThreadProcessId(fg, ctypes.byref(pid))
        return pid.value == os.getpid()
    except Exception:
        return None


# ── Modal dialogs must never end up behind the pinned Task Queue ──────────
# A window with WS_EX_TOPMOST sits above every ordinary window of ours — which
# would include a modal dialog, leaving the user staring at a queue they cannot
# dismiss while an invisible dialog holds the grab.  Every modal Toplevel
# therefore un-pins the queue for as long as it lives.
_MODAL_DEPTH = {"n": 0}
_TOPMOST_HOLDERS: list = []


def _foreground_hwnd() -> int:
    """The window Windows currently considers the active one (0 if unknown)."""
    try:
        return int(ctypes.windll.user32.GetForegroundWindow())
    except Exception:
        return 0


def _win_hwnd(win) -> int:
    """The REAL top-level handle of a Tk window.

    wm_frame(), not winfo_id(): winfo_id() is the Tk client area, and the
    window Windows knows about — the one with the title bar, the one
    GetForegroundWindow() returns — is its parent frame.
    """
    try:
        return int(win.wm_frame(), 16)
    except Exception:
        return 0


def _register_topmost_window(win):
    """Let a pinned window be un-pinned automatically while a modal is open."""
    if win not in _TOPMOST_HOLDERS:
        _TOPMOST_HOLDERS.append(win)


def _unregister_topmost_window(win):
    try:
        _TOPMOST_HOLDERS.remove(win)
    except ValueError:
        pass


def _modal_suspend_topmost():
    """Called when a modal dialog opens: demote every pinned window."""
    _MODAL_DEPTH["n"] += 1
    if _MODAL_DEPTH["n"] != 1:
        return
    for w in list(_TOPMOST_HOLDERS):
        try:
            if w.winfo_exists():
                _drop_toplevel_no_activate(w)
        except Exception:
            _unregister_topmost_window(w)


def _modal_release_topmost():
    """Called when a modal dialog closes: re-pin what was pinned before."""
    _MODAL_DEPTH["n"] = max(0, _MODAL_DEPTH["n"] - 1)
    if _MODAL_DEPTH["n"] != 0:
        return
    for w in list(_TOPMOST_HOLDERS):
        try:
            if w.winfo_exists() and w.winfo_ismapped():
                _raise_toplevel_no_activate(w, keep_on_top=True)
        except Exception:
            _unregister_topmost_window(w)


def _ui_call(widget, fn, delay: int = 0):
    """Schedule fn on the Tk thread from a worker thread.

    If the window has already been closed, tkinter raises (there is no event
    loop left to schedule on).  That is expected during shutdown, not an
    error, so it is swallowed here rather than crashing the worker.
    """
    try:
        widget.after(delay, fn)
    except Exception:
        pass


def _to_clipboard(text: str) -> bool:
    """Put TEXT in the real Windows clipboard.

    Not Tk's.  Tk does not hand the text over — it registers itself as the
    clipboard OWNER and serves the content when another program asks for it,
    so everything copied that way disappears the moment File_manager closes.
    CF_UNICODETEXT through the Win32 API is a real copy, and it survives.
    Returns False if Windows would not give up the clipboard (another program
    holds it open for a moment now and then); the caller falls back to Tk.
    """
    CF_UNICODETEXT = 13
    GMEM_MOVEABLE  = 0x0002
    try:
        u32 = ctypes.windll.user32
        k32 = ctypes.windll.kernel32
        # 64-bit: handles and pointers must be declared, or they come back
        # truncated to 32 bits and the memmove writes into nowhere.
        k32.GlobalAlloc.restype       = ctypes.c_void_p
        k32.GlobalAlloc.argtypes      = [ctypes.c_uint, ctypes.c_size_t]
        k32.GlobalLock.restype        = ctypes.c_void_p
        k32.GlobalLock.argtypes       = [ctypes.c_void_p]
        k32.GlobalUnlock.argtypes     = [ctypes.c_void_p]
        u32.OpenClipboard.argtypes    = [ctypes.c_void_p]
        u32.SetClipboardData.restype  = ctypes.c_void_p
        u32.SetClipboardData.argtypes = [ctypes.c_uint, ctypes.c_void_p]

        buf  = ctypes.create_unicode_buffer(text)
        size = ctypes.sizeof(buf)
        # Windows' own clipboard history opens the clipboard the moment it
        # changes, and while any program holds it open nobody else can get it.
        # So two copies in a row can fail on the second for no reason at all
        # — that showed up in testing.  Ten quick tries, then give up.
        for _try in range(10):
            if u32.OpenClipboard(None):
                break
            _time.sleep(0.02)
        else:
            return False
        try:
            u32.EmptyClipboard()
            handle = k32.GlobalAlloc(GMEM_MOVEABLE, size)
            if not handle:
                return False
            ptr = k32.GlobalLock(handle)
            if not ptr:
                return False
            ctypes.memmove(ptr, buf, size)
            k32.GlobalUnlock(handle)
            # Once SetClipboardData succeeds the block belongs to Windows —
            # freeing it here would free the clipboard out from under it.
            return bool(u32.SetClipboardData(CF_UNICODETEXT, handle))
        finally:
            u32.CloseClipboard()
    except Exception as exc:
        _log(f"_to_clipboard failed: {exc}")
        return False


def _flash_ok(parent, message: str, title: str = "Done", ms: int = 1000):
    """Success popup that closes itself after 1 second."""
    try:
        top = tk.Toplevel(parent)
        top.title(title)
        top.configure(bg=C_BG3)
        top.resizable(False, False)
        top.transient(parent.winfo_toplevel())
        top.overrideredirect(False)
        tk.Label(top, text="✔", bg=C_BG3, fg="#7ee787",
                 font=("Segoe UI", 22)).pack(pady=(12, 0), padx=24)
        tk.Label(top, text=message, bg=C_BG3, fg=C_FG,
                 font=("Segoe UI", 10), wraplength=340,
                 justify="center").pack(padx=24, pady=(4, 14))
        top.update_idletasks()
        # Centre on the parent window
        pw = parent.winfo_toplevel()
        x = pw.winfo_rootx() + (pw.winfo_width()  - top.winfo_width())  // 2
        y = pw.winfo_rooty() + (pw.winfo_height() - top.winfo_height()) // 3
        top.geometry(f"+{max(0, x)}+{max(0, y)}")
        top.after(ms, top.destroy)
    except Exception:
        pass


def _no_blink(widget):
    """Make the caret steady (non-blinking) in Entry / Text widgets.

    Only the CLASSIC tk widgets have -insertofftime.  A ttk.Entry / ttk.Spinbox
    has no such option at all, and setting it through the ttk STYLE is accepted
    but ignored (measured: the caret still blinks), so a ttk entry cannot be
    fixed after the fact — it has to be a tk one in the first place.  This says
    so in the log instead of failing quietly, because a silent `except: pass`
    here is exactly how blinking carets crept back into the Settings window.
    """
    try:
        widget.configure(insertofftime=0, insertontime=9999999)
    except Exception:
        _log(f"_no_blink: {widget.__class__.__name__} has no caret options — "
             f"use the classic tk widget (ttk cannot be made steady here)")


def _mk_spinbox(parent, **kw):
    """A classic tk.Spinbox with a steady caret (ttk.Spinbox blinks)."""
    kw.setdefault("insertofftime", 0)
    kw.setdefault("insertontime", 9999999)
    return tk.Spinbox(parent, **kw)


def _mk_entry(parent, **kw):
    """A classic tk.Entry with a steady caret (ttk.Entry blinks)."""
    kw.setdefault("insertofftime", 0)
    kw.setdefault("insertontime", 9999999)
    return tk.Entry(parent, **kw)


# Row colours for the tool dialogs.  The Treeview keeps tkinter's default
# light list (the Windows "vista" ttk theme ignores fieldbackground anyway,
# and the main file panels are light too), so these are chosen to stay
# readable on white rather than on the dark dialog chrome.
TC_OK      = "#1a7f37"   # green   — success, identical, only-left
TC_INFO    = "#0a5ca8"   # blue    — informational, only-right, folders
TC_WARN    = "#a15c00"   # amber   — newer / changed / missing
TC_WARN2   = "#8a4b00"   # darker amber, for the opposite direction
TC_BAD     = "#c1121f"   # red     — failed, conflicting, invalid
TC_MUTED   = "#6a6a6a"   # grey    — unchanged, equal


# ── File colours by extension (Settings ▸ Customization) ──────────────────
#
# A file is drawn in the standard colour unless one of these groups is switched
# on.  Shipped switched OFF, all of them: the default look is the one that has
# always been there, and one button ("Use the suggested colours") turns the lot
# on.  The colours are chosen to sit on the WHITE file list, to stay clear of
# the folder blue, of the red/purple marking colours and of the grey inactive
# cursor — and to be muted rather than a rainbow, since the point is to tell
# file KINDS apart at a glance, not to decorate.
# A colour label (Ctrl+G) always wins over these.
DEFAULT_EXT_GROUPS = [
    {"name": "Executables & scripts", "colour": "#a03e00", "enabled": False,
     "exts": "exe, msi, bat, cmd, com, ps1, vbs, scr"},
    {"name": "Python",                "colour": "#0b7a25", "enabled": False,
     "exts": "py, pyw, pyi, ipynb"},
    {"name": "Source code",           "colour": "#7a3ea8", "enabled": False,
     "exts": "c, h, cpp, hpp, cs, java, js, ts, jsx, go, rs, rb, php, lua, pl, sh, sql"},
    {"name": "Web pages",             "colour": "#b0338a", "enabled": False,
     "exts": "html, htm, css, scss, svg, xml, xhtml, php3"},
    {"name": "Config & data",         "colour": "#55606e", "enabled": False,
     "exts": "json, ini, cfg, conf, yaml, yml, toml, reg, db, sqlite, dat"},
    {"name": "Text & notes",          "colour": "#444444", "enabled": False,
     "exts": "txt, md, nfo, log, rtf, diz, me"},
    {"name": "Documents",             "colour": "#a03030", "enabled": False,
     "exts": "pdf, doc, docx, odt, epub, mobi, djvu, chm"},
    {"name": "Spreadsheets",          "colour": "#146b45", "enabled": False,
     "exts": "xls, xlsx, xlsm, ods, csv, tsv"},
    {"name": "Presentations",         "colour": "#b05a00", "enabled": False,
     "exts": "ppt, pptx, odp"},
    {"name": "Images",                "colour": "#0f7b8a", "enabled": False,
     "exts": "jpg, jpeg, png, gif, bmp, webp, tif, tiff, ico, psd, heic, raw"},
    {"name": "Audio",                 "colour": "#6a4bbc", "enabled": False,
     "exts": "mp3, flac, wav, ogg, m4a, aac, wma, aif, aiff, mid, midi"},
    {"name": "Video",                 "colour": "#2f6fb0", "enabled": False,
     "exts": "mp4, mkv, avi, mov, wmv, m4v, mpg, mpeg, webm, flv, ts"},
    {"name": "Archives",              "colour": "#8a6d3b", "enabled": False,
     "exts": "zip, rar, 7z, tar, gz, bz2, xz, cab, arj, lzh, z"},
    {"name": "Disc images",           "colour": "#6b7f00", "enabled": False,
     "exts": "iso, img, bin, cue, nrg, mdf, vhd"},
    {"name": "Subtitles",             "colour": "#767676", "enabled": False,
     "exts": "srt, sub, idx, ass, ssa, vtt, smi"},
    {"name": "Backups & leftovers",   "colour": "#9a9a9a", "enabled": False,
     "exts": "bak, tmp, old, part, crdownload, chk, syd"},
]

# The ready-made colours the ■ button offers, so a colour can be picked without
# opening the full Windows colour box every time.
EXT_COLOUR_SWATCHES = [
    "#000000", "#444444", "#767676", "#9a9a9a", "#c8c8c8",
    "#a03e00", "#b05a00", "#8a6d3b", "#6b7f00", "#0b7a25",
    "#146b45", "#0f7b8a", "#2f6fb0", "#6a4bbc", "#7a3ea8",
    "#b0338a", "#a03030", "#55606e", "#8a5a00", "#1a5fb4",
]


def _load_ext_groups(settings: dict) -> list:
    """The saved extension-colour groups, or the shipped suggestions."""
    raw = settings.get("ext_color_groups")
    if not isinstance(raw, list) or not raw:
        return [dict(g) for g in DEFAULT_EXT_GROUPS]
    out = []
    for g in raw:
        if not isinstance(g, dict):
            continue
        out.append({"name":    str(g.get("name", "")),
                    "exts":    str(g.get("exts", "")),
                    "colour":  str(g.get("colour", "#444444")) or "#444444",
                    "enabled": bool(g.get("enabled", False))})
    return out or [dict(g) for g in DEFAULT_EXT_GROUPS]


def _ext_colour_map(groups: list) -> dict:
    """{"py": "#c8c8c8", …} from the switched-on groups.

    Later groups win, so a one-extension group added at the bottom overrides
    whatever big group already claimed it."""
    out = {}
    for g in groups or []:
        if not g.get("enabled"):
            continue
        colour = (g.get("colour") or "").strip()
        if not colour:
            continue
        for e in _re.split(r"[;,\s]+", g.get("exts", "") or ""):
            e = e.strip().lstrip("*").lstrip(".").lower()
            if e:
                out[e] = colour
    return out


def _setup_toplevel(win, title: str, parent=None, modal: bool = True):
    """Apply standard Toplevel rules: grab_set, focus_force, Escape close.

    Pass modal=False to create a non-blocking (non-grab) dialog that still
    stays on top of its parent but does not lock the rest of the UI.

    A modal dialog also un-pins any always-on-top window (the Task Queue) for
    as long as it lives — otherwise the pinned window would sit on top of the
    very dialog that is holding the grab, and the program would look frozen.
    """
    win.title(title)
    if parent:
        win.transient(parent)
    if modal:
        _modal_suspend_topmost()

        def _release(_e=None, w=win):
            if getattr(w, "_topmost_released", False):
                return
            w._topmost_released = True
            _modal_release_topmost()

        win.bind("<Destroy>", lambda e, w=win: (_release()
                                                if e.widget is w else None),
                 add="+")
        win.grab_set()
    win.focus_force()
    win.bind("<Escape>", lambda e: win.destroy())


def _ask_text(parent, title: str, prompt: str, initial: str = "",
              width: int = 44, select_all: bool = True,
              choices=None) -> str:
    """A no-blink replacement for tkinter's simpledialog.askstring().

    simpledialog builds its own tk.Entry with the default BLINKING caret, which
    is banned everywhere in this program, so every "type a name" box goes
    through here instead.  Enter accepts, Escape cancels, and an optional list
    of *choices* is offered underneath as ready-made rows you can double-click
    — that is what turns "you must know what to type" into "pick one".
    Returns "" when cancelled.
    """
    result = {"value": ""}
    win = tk.Toplevel(parent)
    _setup_toplevel(win, title, parent.winfo_toplevel())
    win.resizable(False, False)

    ttk.Label(win, text=prompt, wraplength=430,
              justify="left").pack(padx=14, pady=(14, 6), anchor="w")

    entry = tk.Entry(win, width=width, insertofftime=0, insertontime=9999999)
    entry.pack(padx=14, pady=(0, 8), fill="x")
    if initial:
        entry.insert(0, initial)
        if select_all:
            entry.select_range(0, "end")
        entry.icursor("end")
    entry.focus_set()

    if choices:
        ttk.Label(win, text="Or pick one:").pack(padx=14, anchor="w")
        box = tk.Listbox(win, height=min(8, len(choices)),
                         activestyle="none", exportselection=False)
        for c in choices:
            box.insert("end", c)
        box.pack(padx=14, pady=(2, 8), fill="both", expand=True)

        def _take(_e=None):
            sel = box.curselection()
            if sel:
                entry.delete(0, "end")
                entry.insert(0, box.get(sel[0]))
            return "break"

        box.bind("<<ListboxSelect>>", _take)
        box.bind("<Double-1>", lambda e: (_take(), _ok()))

    def _ok(_e=None):
        result["value"] = entry.get().strip()
        win.destroy()
        return "break"

    def _cancel(_e=None):
        result["value"] = ""
        win.destroy()
        return "break"

    entry.bind("<Return>", _ok)
    win.bind("<Escape>", _cancel)

    btns = ttk.Frame(win)
    btns.pack(pady=(0, 12))
    ttk.Button(btns, text="OK",     command=_ok,     width=10).pack(side="left", padx=5)
    ttk.Button(btns, text="Cancel", command=_cancel, width=10).pack(side="left", padx=5)
    win.wait_window()
    return result["value"]


def _ask_yes_no(title: str, message: str, parent=None,
                default_yes: bool = True) -> bool:
    """A Yes/No box whose buttons actually say YES and NO.

    tkinter's _ask_yes_no() is the WINDOWS box: its buttons follow the
    system language, so on a Swedish Windows they read JA / NEJ — in a program
    that is meant to be English from end to end.  This is the same question,
    built here, so the words are ours.  ENTER answers Yes (what the native box
    did), ESCAPE answers No, and LEFT/RIGHT step between the buttons.

    The argument order deliberately mirrors _ask_yes_no(title, message,
    parent=…) so every call site could be swapped over as it stood.
    """
    root = parent or tk._default_root
    win  = tk.Toplevel(root)
    answer = {"v": False}
    _setup_toplevel(win, title, root.winfo_toplevel() if root else None)
    win.resizable(False, False)
    win.protocol("WM_DELETE_WINDOW", lambda: _finish(False))

    def _finish(value):
        answer["v"] = bool(value)
        try:
            win.destroy()
        except Exception:
            pass

    body = ttk.Frame(win, padding=(18, 16, 18, 8))
    body.pack(fill="both", expand=True)
    ttk.Label(body, text="?", font=("Segoe UI", 22, "bold"),
              foreground=TC_INFO).pack(side="left", padx=(0, 14), anchor="n")
    ttk.Label(body, text=message, wraplength=460, justify="left").pack(
        side="left", fill="both", expand=True)

    btns = ttk.Frame(win, padding=(18, 0, 18, 14))
    btns.pack(fill="x")
    b_no  = ttk.Button(btns, text="No",  width=12, command=lambda: _finish(False))
    b_yes = ttk.Button(btns, text="Yes", width=12, command=lambda: _finish(True))
    b_no.pack(side="right")
    b_yes.pack(side="right", padx=(0, 8))
    order = [b_yes, b_no]

    def _step(direction):
        def handler(_e=None):
            cur = win.focus_get()
            i = order.index(cur) if cur in order else 0
            order[(i + direction) % len(order)].focus_set()
            return "break"
        return handler

    def _confirm(_e=None):
        cur = win.focus_get()
        (cur if cur in order else order[0]).invoke()
        return "break"

    win.bind("<Left>",  _step(-1))
    win.bind("<Right>", _step(+1))
    win.bind("<Return>", _confirm)
    win.bind("<KP_Enter>", _confirm)
    win.bind("<Escape>", lambda e: _finish(False))
    (b_yes if default_yes else b_no).focus_set()

    win.update_idletasks()
    if root is not None:
        try:
            top = root.winfo_toplevel()
            px = top.winfo_rootx() + (top.winfo_width()  - win.winfo_width())  // 2
            py = top.winfo_rooty() + (top.winfo_height() - win.winfo_height()) // 3
            win.geometry(f"+{max(0, px)}+{max(0, py)}")
        except Exception:
            pass
    win.wait_window()
    # Hand the grab back to whatever dialog was underneath, or it is left
    # non-modal for the rest of its life.
    try:
        if parent is not None and parent.winfo_exists():
            pt = parent.winfo_toplevel()
            if pt is not tk._default_root:
                pt.grab_set()
    except Exception:
        pass
    return answer["v"]


def _ask_close_while_busy(parent, waiting: int, running_desc: str,
                          total_bytes: int):
    """“The queue is still working — close anyway?”

    Three answers, because there really are three things you might mean:

        "keep"  — Keep working.  The transfer picks up exactly where it stood.
        "close" — Close, and the unfinished jobs come back at the next start.
        "drop"  — Close and throw the queue away.

    Deliberately not a Yes/No box: "No" to "close anyway?" is ambiguous, and on
    a Swedish Windows the native box would put JA / NEJ on it in a program that
    is English from end to end.

    ESCAPE = keep working, which is the safe answer for a stray click on the X.
    """
    root   = parent or tk._default_root
    win    = tk.Toplevel(root)
    answer = {"v": "keep"}
    _setup_toplevel(win, "The task queue is still working",
                    root.winfo_toplevel() if root else None, modal=True)
    win.resizable(False, False)
    # revCJ: the window was never given the program's dark background, so the
    # light text (fg=C_FG) sat on the system's white-grey — grey on white,
    # unreadable.  Every frame below now uses C_BG explicitly.
    win.configure(bg=C_BG)

    def _finish(value):
        answer["v"] = value
        try:
            win.destroy()
        except Exception:
            pass

    win.protocol("WM_DELETE_WINDOW", lambda: _finish("keep"))

    head = tk.Frame(win, bg="#4a3a00", padx=12, pady=9)
    head.pack(fill="x")
    tk.Label(head, text="⏸  The transfer has been PAUSED while you answer.",
             bg="#4a3a00", fg="#ffe066", font=("Segoe UI", 10, "bold"),
             anchor="w").pack(fill="x")

    body = tk.Frame(win, bg=C_BG, padx=14, pady=10)
    body.pack(fill="both", expand=True)

    lines = [f"{waiting} job(s) in the queue have not finished."]
    if running_desc:
        lines.append(f"Running right now:   {running_desc}")
    if total_bytes > 0:
        lines.append(f"Still to move:   {_fmt_size(total_bytes)}")
    lines.append("")
    lines.append("Closing does not throw them away: the list is written to")
    lines.append("Helpfiles/redigerare/task_queue.json and comes back at the")
    lines.append("next start — PAUSED, with the Task Queue in front, so nothing")
    lines.append("moves until you have looked at it.")
    lines.append("")
    lines.append("The file being written this second is stopped properly on the")
    lines.append("way out, so no half-written file is left under the right name.")
    tk.Label(body, text="\n".join(lines), bg=C_BG, fg=C_FG,
             font=("Segoe UI", 9), justify="left", anchor="w").pack(fill="x")

    # (A Frame's pady must be ONE number - the tuple "(0, 12)" is only legal
    # in pack()/grid().  It raised TclError "bad screen distance" and crashed.)
    btns = tk.Frame(win, bg=C_BG, padx=14)
    btns.pack(fill="x", pady=(0, 12))
    b_keep = ttk.Button(btns, text="▶  Keep working", width=20,
                        command=lambda: _finish("keep"))
    b_close = ttk.Button(btns, text="💾  Close — keep the queue", width=26,
                         command=lambda: _finish("close"))
    b_drop = ttk.Button(btns, text="🗑  Close and drop it", width=20,
                        command=lambda: _finish("drop"))
    b_keep.pack(side="left", padx=(0, 6))
    b_close.pack(side="left", padx=6)
    b_drop.pack(side="right", padx=(6, 0))

    order = [b_keep, b_close, b_drop]

    def _step(direction):
        def handler(_e=None):
            cur = win.focus_get()
            i = order.index(cur) if cur in order else 0
            order[(i + direction) % len(order)].focus_set()
            return "break"
        return handler

    def _confirm(_e=None):
        cur = win.focus_get()
        (cur if cur in order else order[0]).invoke()
        return "break"

    win.bind("<Left>",  _step(-1))
    win.bind("<Right>", _step(+1))
    win.bind("<Return>", _confirm)
    win.bind("<KP_Enter>", _confirm)
    win.bind("<Escape>", lambda e: _finish("keep"))
    b_keep.focus_set()
    win.update_idletasks()
    win.wait_window()
    return answer["v"]


def _ask_yes_no_cancel(title: str, message: str, parent=None):
    """Yes / No / Cancel, in English.  True, False or None (cancelled)."""
    root = parent or tk._default_root
    win  = tk.Toplevel(root)
    answer = {"v": None}
    _setup_toplevel(win, title, root.winfo_toplevel() if root else None)
    win.resizable(False, False)

    def _finish(value):
        answer["v"] = value
        try:
            win.destroy()
        except Exception:
            pass

    win.protocol("WM_DELETE_WINDOW", lambda: _finish(None))
    body = ttk.Frame(win, padding=(18, 16, 18, 8))
    body.pack(fill="both", expand=True)
    ttk.Label(body, text="?", font=("Segoe UI", 22, "bold"),
              foreground=TC_INFO).pack(side="left", padx=(0, 14), anchor="n")
    ttk.Label(body, text=message, wraplength=460, justify="left").pack(
        side="left", fill="both", expand=True)

    btns = ttk.Frame(win, padding=(18, 0, 18, 14))
    btns.pack(fill="x")
    b_cancel = ttk.Button(btns, text="Cancel", width=12,
                          command=lambda: _finish(None))
    b_no  = ttk.Button(btns, text="No",  width=12, command=lambda: _finish(False))
    b_yes = ttk.Button(btns, text="Yes", width=12, command=lambda: _finish(True))
    b_cancel.pack(side="right")
    b_no.pack(side="right", padx=(0, 8))
    b_yes.pack(side="right", padx=(0, 8))
    order = [b_yes, b_no, b_cancel]

    def _step(direction):
        def handler(_e=None):
            cur = win.focus_get()
            i = order.index(cur) if cur in order else 0
            order[(i + direction) % len(order)].focus_set()
            return "break"
        return handler

    def _confirm(_e=None):
        cur = win.focus_get()
        (cur if cur in order else order[0]).invoke()
        return "break"

    win.bind("<Left>",  _step(-1))
    win.bind("<Right>", _step(+1))
    win.bind("<Return>", _confirm)
    win.bind("<KP_Enter>", _confirm)
    win.bind("<Escape>", lambda e: _finish(None))
    b_yes.focus_set()
    win.update_idletasks()
    win.wait_window()
    try:
        if parent is not None and parent.winfo_exists():
            pt = parent.winfo_toplevel()
            if pt is not tk._default_root:
                pt.grab_set()
    except Exception:
        pass
    return answer["v"]


# Windows GetDriveTypeW() codes → what a human calls them.  The icon makes a
# USB stick, a phone in mass-storage mode and a mapped share tellable apart at
# a glance in the drive menu.
_DRIVE_KINDS = {
    0: ("Unknown",   "❔"),
    1: ("No root",   "❔"),
    2: ("Removable", "💾"),
    3: ("Fixed",     "🖴"),
    4: ("Network",   "🖧"),
    5: ("CD/DVD",    "💿"),
    6: ("RAM disk",  "⚡"),
}


def _drive_kind_info(root: str) -> dict:
    """{'kind', 'icon', 'label'} for a drive root such as 'E:\\'.

    'label' is the volume name in brackets ("  [Backup]") or "" — it is what
    tells two identical-looking removable drives apart.
    """
    kind, icon = _DRIVE_KINDS.get(0)
    label = ""
    try:
        code = ctypes.windll.kernel32.GetDriveTypeW(ctypes.c_wchar_p(root))
        kind, icon = _DRIVE_KINDS.get(code, _DRIVE_KINDS[0])
    except Exception:
        pass
    try:
        buf  = ctypes.create_unicode_buffer(261)
        fsbuf = ctypes.create_unicode_buffer(64)
        ok = ctypes.windll.kernel32.GetVolumeInformationW(
            ctypes.c_wchar_p(root), buf, 261, None, None, None, fsbuf, 64)
        if ok and buf.value.strip():
            label = "  " + buf.value.strip()
    except Exception:
        pass
    if kind == "Network":                      # "FILM-Good", not just "Good"
        try:
            label = "  " + _net_drive_caption(root, label.strip())
        except Exception:
            pass
    return {"kind": kind, "icon": icon, "label": label}


def _net_drive_caption(root: str, volume: str) -> str:
    """The name of a mapped network drive as the drive menus show it: the computer's
    name in front of the volume name, "FILM-Good" (or "FILM-Drive_C" when the
    volume has no name).  The computer is the one in the share path; when that is
    only an IP address, the name saved with the favourite of that letter is used."""
    letter = root[:2]
    unc = ""
    try:
        buf = ctypes.create_unicode_buffer(520)
        size = ctypes.c_ulong(520)
        if ctypes.windll.mpr.WNetGetConnectionW(letter, buf, ctypes.byref(size)) == 0:
            unc = buf.value
    except Exception:
        pass
    parts = [p for p in unc.split("\\") if p]
    host, share = (parts[0], parts[1]) if len(parts) >= 2 else ("", "")
    if not host or _re.fullmatch(r"[\d.:]+", host):          # an IP address says nothing
        host = ""
        try:
            for fav in _net_load_favorites():
                if fav.get("letter", "").rstrip(":").upper() == letter[:1].upper():
                    host = (fav.get("name", "").split() or [""])[0]
                    break
        except Exception:
            pass
    if not host:
        return volume
    if host.lower() in volume.lower().split("-")[0:1]:       # already "FILM-Good"
        return volume
    return f"{host.upper()}-{volume or share}"


# ── What a disk actually IS  (revision BO) ───────────────────────────────────
#
# "Vilket format" is the question that gets asked first and had no answer
# anywhere in the program — which is odd, because _drive_kind_info above has
# ALWAYS asked GetVolumeInformationW for the file-system name and then thrown
# it away.  Everything here is a read-only query; nothing changes a thing.

# GetVolumeInformationW's flags, in the order worth reading them.
_FS_FLAGS = [
    (0x00000010, "File compression"),
    (0x00008000, "The whole volume is compressed"),
    (0x00020000, "Encryption (EFS)"),
    (0x00000008, "Permissions (ACLs)"),
    (0x00000040, "Sparse files"),
    (0x00400000, "Hard links"),
    (0x00000080, "Reparse points / junctions"),
    (0x00040000, "Alternate data streams"),
    (0x00000020, "Disk quotas"),
    (0x02000000, "USN change journal"),
    (0x00200000, "Transactions"),
    (0x08000000, "Block cloning (ReFS)"),
    (0x00000001, "Case-sensitive search"),
    (0x00080000, "READ-ONLY volume"),
]

# What each file system can and cannot do — the part that actually bites.
# The 4 GB line is the one that matters to him: a FAT32 stick silently
# refuses a single file over 4 GB, which is most of a film and most of a
# disk image.
_FS_NOTES = {
    "NTFS":  ("Windows' own.  No practical file-size limit, permissions, "
              "journalling, hard links, compression."),
    "REFS":  ("Resilient File System — checksums and block cloning, no boot "
              "support.  Windows only."),
    "EXFAT": ("Made for flash.  No file-size limit worth worrying about, but "
              "NO permissions and NO journal — a bad unplug can cost the "
              "directory.  Reads on Mac and Linux too."),
    "FAT32": ("⚠  A single file may not exceed 4 GB, and a volume not 32 GB "
              "as Windows formats it.  No permissions, no journal."),
    "FAT":   ("⚠  Ancient.  2 GB volumes, 2 GB files, nothing else."),
    "CDFS":  ("CD/DVD data track.  Read-only by nature."),
    "UDF":   ("DVD/Blu-ray and packet-written discs."),
    "NFS":   ("Network file system — the limits are the server's."),
}


def _volume_info(root: str) -> dict:
    """Label, FILE SYSTEM, serial and capability flags for a drive root.

    root is 'D:\\' — with the trailing backslash, which the API insists on.
    Everything is best-effort: a card reader with no card, a disconnected
    share or a locked BitLocker volume all answer nothing, and that is a fact
    about the drive, not an error to raise.
    """
    out = {"label": "", "fs": "", "serial": "", "max_component": 0,
           "flags": [], "readonly": False, "ok": False}
    try:
        name_buf = ctypes.create_unicode_buffer(261)
        fs_buf   = ctypes.create_unicode_buffer(64)
        serial   = ctypes.c_ulong(0)
        maxcomp  = ctypes.c_ulong(0)
        flags    = ctypes.c_ulong(0)
        ok = ctypes.windll.kernel32.GetVolumeInformationW(
            ctypes.c_wchar_p(root), name_buf, 261,
            ctypes.byref(serial), ctypes.byref(maxcomp), ctypes.byref(flags),
            fs_buf, 64)
        if not ok:
            return out
        s = serial.value
        out.update({
            "label": name_buf.value.strip(),
            "fs": fs_buf.value.strip(),
            "serial": f"{(s >> 16) & 0xFFFF:04X}-{s & 0xFFFF:04X}",
            "max_component": int(maxcomp.value),
            "flags": [txt for bit, txt in _FS_FLAGS if flags.value & bit],
            "readonly": bool(flags.value & 0x00080000),
            "ok": True,
        })
    except Exception as exc:
        _log(f"Volume information for {root} could not be read: {exc}")
    return out


def _cluster_info(root: str) -> dict:
    """Sector / cluster geometry — the 'allocation unit size' of the format
    dialog, and what decides how much a million small files really cost."""
    out = {"cluster": 0, "sector": 0, "clusters_total": 0, "clusters_free": 0}
    try:
        spc = ctypes.c_ulong(0); bps = ctypes.c_ulong(0)
        free = ctypes.c_ulong(0); total = ctypes.c_ulong(0)
        ok = ctypes.windll.kernel32.GetDiskFreeSpaceW(
            ctypes.c_wchar_p(root), ctypes.byref(spc), ctypes.byref(bps),
            ctypes.byref(free), ctypes.byref(total))
        if ok:
            out = {"cluster": spc.value * bps.value, "sector": bps.value,
                   "clusters_total": total.value, "clusters_free": free.value}
    except Exception as exc:
        _log(f"Cluster geometry for {root} could not be read: {exc}")
    return out


def _ps_exe() -> str:
    """PowerShell, by ABSOLUTE path.

    Never a bare name: a folder-exe build sitting next to a file called
    powershell.exe would run THAT instead, and a bare 'cmd.exe' once turned
    into a fork bomb exactly this way.
    """
    return os.path.join(os.environ.get("SystemRoot", r"C:\Windows"),
                        "System32", "WindowsPowerShell", "v1.0",
                        "powershell.exe")


_PHYS_CACHE: dict = {}


def _physical_disk_info(letter: str, timeout: float = 12.0) -> dict:
    """The hardware under the letter: model, bus, SSD or spinning, MBR/GPT.

    None of this is reachable through the plain Win32 volume calls, so it goes
    through PowerShell's storage cmdlets — SLOW (seconds), which is why the
    dialog asks for it on a thread and fills the panel in when it arrives, and
    why the answer is cached per letter for the session.

    Read-only.  Every part is wrapped on the PowerShell side too, so one
    cmdlet that is missing or needs rights it has not got costs that one line
    and not the whole answer.
    """
    key = (letter or "").upper()[:1]
    if not key:
        return {}
    if key in _PHYS_CACHE:
        return _PHYS_CACHE[key]
    script = (
        "$ErrorActionPreference='SilentlyContinue';"
        "$o=[ordered]@{};"
        f"$L='{key}';"
        "$v=Get-Volume -DriveLetter $L;"
        "if($v){$o.VolHealth=[string]$v.HealthStatus;"
        "$o.AllocUnit=[string]$v.AllocationUnitSize;"
        "$o.FsType=[string]$v.FileSystemType}"
        "$p=Get-Partition -DriveLetter $L;"
        "if($p){$o.PartNumber=[string]$p.PartitionNumber;"
        "$o.PartOffset=[string]$p.Offset;$o.PartSize=[string]$p.Size;"
        "$o.PartType=[string]$p.Type};"
        "$d=$p|Get-Disk;"
        "if($d){$o.DiskNumber=[string]$d.Number;$o.Model=[string]$d.FriendlyName;"
        "$o.Serial=([string]$d.SerialNumber).Trim();$o.Bus=[string]$d.BusType;"
        "$o.PartStyle=[string]$d.PartitionStyle;$o.DiskSize=[string]$d.Size;"
        "$o.DiskHealth=[string]$d.HealthStatus;"
        "$o.Boot=[string]$d.IsBoot;$o.System=[string]$d.IsSystem;"
        "$pd=Get-PhysicalDisk|Where-Object{$_.DeviceId -eq $d.Number};"
        "if($pd){$o.Media=[string]$pd.MediaType;"
        "$o.Spindle=[string]$pd.SpindleSpeed;"
        "$o.PdHealth=[string]$pd.HealthStatus}};"
        "$b=Get-BitLockerVolume -MountPoint ($L+':');"
        "if($b){$o.BitLocker=[string]$b.ProtectionStatus;"
        "$o.BitLockerPct=[string]$b.EncryptionPercentage};"
        "$o|ConvertTo-Json -Compress"
    )
    data = {}
    try:
        res = subprocess.run(
            [_ps_exe(), "-NoProfile", "-NonInteractive", "-Command", script],
            capture_output=True, text=True, timeout=timeout,
            creationflags=getattr(subprocess, "CREATE_NO_WINDOW", 0))
        txt = (res.stdout or "").strip()
        if txt.startswith("{"):
            data = json.loads(txt)
    except subprocess.TimeoutExpired:
        _log(f"Physical disk info for {key}: PowerShell timed out")
    except Exception as exc:
        _log(f"Physical disk info for {key} failed: {exc}")
    if data:
        _PHYS_CACHE[key] = data
    return data


def _format_is_forbidden(letter: str) -> str:
    """Why this drive must NOT be offered for formatting — "" when it may be.

    Four answers, and every one of them is the sort of mistake that has no
    undo:  the drive Windows is running from, the drive THIS program and his
    whole tree live on, a drive that is not a local disk at all, and one that
    is not there.
    """
    L = (letter or "").upper()[:1]
    if not L:
        return "no drive letter"
    root = L + ":\\"
    if not os.path.isdir(root):
        return "there is nothing in that drive"
    sysdrv = (os.environ.get("SystemDrive", "C:") or "C:")[:1].upper()
    if L == sysdrv:
        return f"{L}: is the drive Windows is running from"
    try:
        home = os.path.splitdrive(os.path.abspath(str(APP_ROOT)))[0][:1].upper()
        if L == home:
            return f"{L}: is where this program and its Helpfiles live"
    except Exception:
        pass
    try:
        code = ctypes.windll.kernel32.GetDriveTypeW(ctypes.c_wchar_p(root))
        if code == 4:
            return f"{L}: is a network drive, not a disk on this machine"
        if code == 5:
            return f"{L}: is a CD/DVD drive"
        if code == 6:
            return f"{L}: is a RAM disk"
        if code not in (2, 3):
            return f"{L}: is not a disk that can be formatted"
    except Exception:
        pass
    return ""


def _top_level_entries(root: str, limit: int = 10) -> tuple:
    """(names of the first *limit* top-level FOLDERS, total folders, files).

    This is the list the second format warning shows.  A drive letter on its
    own says nothing — "D:" could be the empty stick or it could be the
    backup.  Ten folder names say instantly which one you are about to wipe.
    """
    folders, files = [], 0
    try:
        with os.scandir(root) as it:
            for e in it:
                try:
                    if e.is_dir(follow_symlinks=False):
                        folders.append(e.name)
                    else:
                        files += 1
                except OSError:
                    continue
    except Exception as exc:
        _log(f"Could not list the top level of {root}: {exc}")
        return [], -1, -1
    folders.sort(key=str.lower)
    return folders[:limit], len(folders), files


# The file system of a drive, cached: the status bar asks for it on every
# settle of either panel and the answer cannot change while the disk sits
# there.  Cleared when a format actually happens.
_FS_NAME_CACHE: dict = {}


def _fs_name_cached(root: str) -> str:
    """'  ·  NTFS' for the status bar, or '' when the drive will not say."""
    key = os.path.normcase(root or "")
    if not key:
        return ""
    hit = _FS_NAME_CACHE.get(key)
    if hit is None:
        fs = ""
        try:
            fs_buf = ctypes.create_unicode_buffer(64)
            if ctypes.windll.kernel32.GetVolumeInformationW(
                    ctypes.c_wchar_p(root), None, 0, None, None, None,
                    fs_buf, 64):
                fs = fs_buf.value.strip()
        except Exception:
            fs = ""
        hit = f"   ·   {fs}" if fs else ""
        _FS_NAME_CACHE[key] = hit
    return hit


def _looks_bootable(root: str) -> str:
    """"" unless this volume looks like something a machine BOOTS from.

    Worth its own line in the second warning: his D: is labelled "Win 10 to
    go" and carries a whole Windows.  GetDriveType calls it Fixed and the
    disk does not report IsBoot, because it is not the one running right now —
    so nothing else in the program would have said a word about it.
    """
    marks = []
    for rel, what in ((r"Windows\System32\config\SYSTEM", "a Windows installation"),
                      (r"Boot\BCD",                      "a BCD boot store"),
                      ("bootmgr",                        "the Windows boot manager"),
                      (r"EFI\Boot",                      "an EFI boot folder"),
                      (r"EFI\Microsoft",                 "an EFI boot folder")):
        try:
            if os.path.exists(os.path.join(root, rel)):
                marks.append(what)
        except Exception:
            pass
    # Say each thing once, in the order found.
    seen, out = set(), []
    for m in marks:
        if m not in seen:
            seen.add(m)
            out.append(m)
    return ", ".join(out)


# Drive letters already checked with GetDriveTypeW.  The answer cannot change
# while a mapping stays put, and this is asked once per tab on every redraw of
# the tab strip — a cached lookup keeps a slow/absent server out of the paint.
_NET_DRIVE_CACHE: dict = {}


def _is_network_path(path: str) -> bool:
    """True when *path* does not live on this machine.

    Two ways that happens: a UNC path (the two-backslash TOWER/Media kind) or
    a drive letter that is a MAPPED share (GetDriveTypeW == 4, DRIVE_REMOTE).
    Both are worth marking in the tab strip — a file dropped there travels
    over the network, which is the difference between "instant" and "sit and
    wait".
    """
    if not path:
        return False
    p = str(path)
    if p.startswith("\\\\") or p.startswith("//"):
        return True
    drv = os.path.splitdrive(p)[0]
    if not drv or ":" not in drv:
        return False
    key = drv.upper()
    if key not in _NET_DRIVE_CACHE:
        remote = False
        try:
            if os.name == "nt":
                code = ctypes.windll.kernel32.GetDriveTypeW(
                    ctypes.c_wchar_p(key + "\\"))
                remote = (code == 4)
        except Exception:
            remote = False
        _NET_DRIVE_CACHE[key] = remote
    return _NET_DRIVE_CACHE[key]


# The mark a network tab carries, and the colours that go with it.  One place
# to change if the globe ever needs to be something else.
NET_TAB_CHAR   = "\U0001F310"        # 🌐
NET_TAB_BG     = "#123840"           # inactive network tab (deep teal)
NET_TAB_FG     = "#67d8e8"
NET_TAB_BORDER = "#2f9fb5"
NET_TAB_ACTIVE_BG = "#3fb3c8"        # active network tab — teal, not blue

# The mark and border a LOCKED (protected) tab carries.  A lock is yours to set
# from the tab's own right-click menu — it has nothing to do with whether the
# tab belongs to a Workspace.  Steady colours, no blinking anywhere.
LOCK_TAB_CHAR   = "\U0001F512"       # 🔒
LOCK_TAB_BORDER = "#c8a64a"          # warm gold, readable on every tab state


def _underline_at(label: str, ch: str) -> int:
    """Index of *ch* inside *label*, counted the way Tk itself counts it.

    Used to point a menu entry's mnemonic underline at the exact character —
    a drive letter — instead of a fixed offset that would silently go wrong
    if the icon or the spacing in the label ever changes.  -1 (Tk's own
    "no underline" value) is a safe fallback if the character is somehow not
    found at all.

    WHY THIS IS NOT A PLAIN str.index():  Tk draws Windows menu entries
    itself (every item is MFT_OWNERDRAW — verified: Windows holds an EMPTY
    string for each one), so Windows cannot match a typed letter against the
    text.  Tk answers WM_MENUCHAR instead and looks the character up in the
    label as a UTF-16 array.  An emoji like 💽 or 🔗 is ONE Python character
    but TWO UTF-16 units, so on every label that starts with one, a plain
    character index lands one place short — the underline sat on the wrong
    character and pressing the drive letter did nothing at all.  Converting
    to a UTF-16 code-unit index is what makes the key press work.
    """
    pos = label.find(ch)
    if pos < 0:
        return -1
    # Number of UTF-16 code units in the text BEFORE the character.
    return len(label[:pos].encode("utf-16-le")) // 2


# How far the mouse must travel with the button held down before a click
# counts as a DRAG.  tkdnd ships with 3 pixels, which is far too little: just
# clicking a file to give a panel the keyboard focus regularly started a real
# drag, and letting go over the same list then tried to copy the file on top
# of itself — which is where the "Drag & Drop – error" came from.
DND_DRAG_THRESHOLD_PX = 12


def _set_dnd_drag_threshold(root, pixels: int = DND_DRAG_THRESHOLD_PX) -> None:
    """Raise tkdnd's drag threshold so a plain click stays a plain click.

    The threshold lives in two Tcl variables inside the tkdnd package
    (::tkdnd::_dx / ::tkdnd::_dy) and is read every time the mouse moves with
    a button down, so setting it once at start-up is enough.  Silently does
    nothing when drag-and-drop is not installed.
    """
    if not _HAS_DND:
        return
    try:
        px = max(3, int(pixels))
        root.tk.eval(f"set ::tkdnd::_dx {px}; set ::tkdnd::_dy {px}")
    except Exception as exc:
        _log(f"Could not raise the drag threshold: {exc}")


# ══════════════════════════════════════════════════════════════════════════
#  Built-in PDF / Image viewer  (Shift+Enter or Shift+Double-click)
# ══════════════════════════════════════════════════════════════════════════

def _read_text_best_effort(path: str, cap: int = 5_000_000):
    """Read a file as text without knowing its encoding up front.

    Returns (text, encoding_name, truncated).  Large files are capped so the
    reader never chokes on a multi-hundred-MB log; binary data still decodes
    via the latin-1 fallback (every byte maps to a character) so F3 can peek
    into anything without raising."""
    with open(path, "rb") as fh:
        raw = fh.read(cap + 1)
    truncated = len(raw) > cap
    raw = raw[:cap]
    for enc in ("utf-8-sig", "utf-8", "cp1252", "latin-1"):
        try:
            return raw.decode(enc), enc, truncated
        except UnicodeDecodeError:
            continue
    return raw.decode("latin-1", "replace"), "latin-1", truncated


class _BuiltinViewerWindow(tk.Toplevel):
    """Minimal built-in viewer for images, PDFs and text.

    Images: requires Pillow  (pip install pillow)
    PDFs:   requires PyMuPDF (pip install pymupdf) for page rendering;
            falls back to text-only extraction via pypdf.

    Keyboard:
      Escape        Close
      Left / Right  Previous / next PDF page
      Ctrl+Scroll   Zoom in / out
    """

    def __init__(self, parent, path: str):
        super().__init__(parent)
        self._mgr = parent            # the EditorFrame (settings, refresh, …)
        self.title(f"Viewer — {os.path.basename(path)}")
        self.geometry("960x720")
        self.resizable(True, True)
        self.configure(bg=C_BG)
        self.bind("<Escape>", lambda e: self.destroy())
        self.focus_force()

        ext = os.path.splitext(path)[1].lower()
        if ext in _VIEWER_PDF_EXTS:
            self._show_pdf(path)
        elif ext in _VIEWER_IMAGE_EXTS:
            self._show_image(path)
        elif ext in _VIEWER_AUDIO_EXTS:
            self._show_audio(path)
        else:
            # Everything else — the named text types AND any unknown file — is
            # shown as best-effort text, so F3 can "peek" into anything.
            self._show_text(path)

    # ── Audio player (simple, MCI-based — no extra dependency) ────────────

    @staticmethod
    def _fmt_ms(ms) -> str:
        """Milliseconds → 'm:ss'."""
        try:
            s = int(ms) // 1000
        except Exception:
            s = 0
        return f"{s // 60}:{s % 60:02d}"

    def _show_audio(self, path: str):
        """A deliberately simple built-in audio player (MP3 / WAV / WMA / MID …).
        Uses Windows' own MCI (winmm) so there is NO extra dependency: Play /
        Pause / Stop, a position slider and a volume slider — nothing fancy,
        it just plays the file.  Anything Windows has no codec for falls back to
        an 'open in the default program' button."""
        self.geometry("500x260")
        self._audio_path    = path
        self._audio_after   = None
        self._audio_len     = 0
        self._audio_ok      = False
        self._audio_playing = False
        self._audio_seeking = False

        if os.name != "nt":
            ttk.Label(self, text="The built-in audio player needs Windows.",
                      padding=20).pack(expand=True)
            self.protocol("WM_DELETE_WINDOW", self._audio_close)
            return

        self._winmm = ctypes.windll.winmm
        type(self)._audio_seq = getattr(type(self), "_audio_seq", 0) + 1
        self._audio_alias = f"fmaud{type(self)._audio_seq}"

        def _mci(cmd):
            buf = ctypes.create_unicode_buffer(256)
            err = self._winmm.mciSendStringW(
                ctypes.c_wchar_p(cmd), buf, 256, None)
            return err, buf.value
        self._mci = _mci

        # MCI picks the device from the extension; if that fails, try the MPEG
        # device explicitly, then give up gracefully with a fallback button.
        err, _ = _mci(f'open "{path}" alias {self._audio_alias}')
        if err:
            err, _ = _mci(f'open "{path}" type mpegvideo alias {self._audio_alias}')
        if err:
            self._audio_fallback(path)
            return
        self._audio_ok = True
        _mci(f'set {self._audio_alias} time format milliseconds')
        _, ln = _mci(f'status {self._audio_alias} length')
        try:
            self._audio_len = int(ln)
        except ValueError:
            self._audio_len = 0

        wrap = tk.Frame(self, bg=C_BG)
        wrap.pack(fill="both", expand=True, padx=16, pady=14)
        tk.Label(wrap, text="🎵  " + os.path.basename(path), bg=C_BG, fg=C_FG,
                 font=("Segoe UI", 11, "bold"),
                 wraplength=450, justify="left").pack(anchor="w")

        # Position slider + time read-out
        self._pos_var = tk.DoubleVar(value=0)
        self._pos_scale = tk.Scale(
            wrap, from_=0, to=max(1, self._audio_len), orient="horizontal",
            showvalue=False, variable=self._pos_var, bg=C_BG, fg=C_FG,
            troughcolor=C_BG3, highlightthickness=0, command=self._audio_on_slider)
        self._pos_scale.pack(fill="x", pady=(12, 0))
        self._pos_scale.bind("<Button-1>",
                             lambda e: setattr(self, "_audio_seeking", True))
        self._pos_scale.bind("<ButtonRelease-1>", self._audio_seek_release)
        self._time_lbl = tk.Label(
            wrap, text="0:00 / " + self._fmt_ms(self._audio_len),
            bg=C_BG, fg=C_FG_DIM, font=("Segoe UI", 9))
        self._time_lbl.pack(anchor="e")

        # Transport buttons — normal colours written out so they are easy to change
        btns = tk.Frame(wrap, bg=C_BG)
        btns.pack(pady=(8, 0))
        self._play_btn = tk.Button(btns, text="⏸  Pause", width=10,
                                   bg="lightgreen", fg="black", relief="flat",
                                   command=self._audio_toggle)
        self._play_btn.pack(side="left", padx=4)
        tk.Button(btns, text="⏹  Stop", width=8, bg="white", fg="black",
                  relief="flat", command=self._audio_stop).pack(side="left", padx=4)

        # Volume
        vol = tk.Frame(wrap, bg=C_BG)
        vol.pack(fill="x", pady=(12, 0))
        tk.Label(vol, text="Volume", bg=C_BG, fg=C_FG_DIM,
                 font=("Segoe UI", 9)).pack(side="left")
        self._vol_scale = tk.Scale(vol, from_=0, to=1000, orient="horizontal",
                                   showvalue=False, bg=C_BG, fg=C_FG,
                                   troughcolor=C_BG3, highlightthickness=0,
                                   command=self._audio_volume)
        self._vol_scale.set(1000)
        self._vol_scale.pack(side="left", fill="x", expand=True, padx=(8, 0))

        # Close handling: stop + close the MCI device and cancel the poll.
        self.protocol("WM_DELETE_WINDOW", self._audio_close)
        self.bind("<Escape>", lambda e: self._audio_close())

        # Autoplay (you double-clicked to hear it) + start the position poll.
        _mci(f'play {self._audio_alias}')
        self._audio_playing = True
        self._audio_tick()

    def _audio_on_slider(self, val):
        # React only to a user drag, never to our own poll updates.
        if getattr(self, "_audio_seeking", False):
            self._time_lbl.config(
                text=self._fmt_ms(int(float(val))) + " / "
                + self._fmt_ms(self._audio_len))

    def _audio_seek_release(self, event=None):
        if not self._audio_ok:
            return
        pos = int(self._pos_var.get())
        self._mci(f'seek {self._audio_alias} to {pos}')
        if self._audio_playing:
            self._mci(f'play {self._audio_alias}')
        self._audio_seeking = False

    def _audio_tick(self):
        if not self._audio_ok:
            return
        if not self._audio_seeking:
            _, pos = self._mci(f'status {self._audio_alias} position')
            try:
                p = int(pos)
            except ValueError:
                p = 0
            self._pos_var.set(p)          # command guard ignores non-drag sets
            self._time_lbl.config(
                text=self._fmt_ms(p) + " / " + self._fmt_ms(self._audio_len))
            _, mode = self._mci(f'status {self._audio_alias} mode')
            if (self._audio_playing and mode.strip() == "stopped"
                    and self._audio_len and p >= self._audio_len - 400):
                self._audio_playing = False
                self._play_btn.config(text="▶  Play")
        self._audio_after = self.after(300, self._audio_tick)

    def _audio_toggle(self):
        if not self._audio_ok:
            return
        if self._audio_playing:
            self._mci(f'pause {self._audio_alias}')
            self._audio_playing = False
            self._play_btn.config(text="▶  Play")
        else:
            err, _ = self._mci(f'resume {self._audio_alias}')
            if err:                       # had ended / cannot resume → play again
                self._mci(f'play {self._audio_alias}')
            self._audio_playing = True
            self._play_btn.config(text="⏸  Pause")

    def _audio_stop(self):
        if not self._audio_ok:
            return
        self._mci(f'stop {self._audio_alias}')
        self._mci(f'seek {self._audio_alias} to 0')
        self._audio_playing = False
        self._play_btn.config(text="▶  Play")
        self._pos_var.set(0)
        self._time_lbl.config(text="0:00 / " + self._fmt_ms(self._audio_len))

    def _audio_volume(self, val):
        if self._audio_ok:
            self._mci(f'setaudio {self._audio_alias} volume to {int(float(val))}')

    def _audio_close(self):
        if self._audio_after:
            try:
                self.after_cancel(self._audio_after)
            except Exception:
                pass
            self._audio_after = None
        if getattr(self, "_audio_ok", False):
            try:
                self._mci(f'stop {self._audio_alias}')
                self._mci(f'close {self._audio_alias}')
            except Exception:
                pass
            self._audio_ok = False
        self.destroy()

    def _audio_fallback(self, path: str):
        wrap = tk.Frame(self, bg=C_BG)
        wrap.pack(fill="both", expand=True, padx=16, pady=16)
        tk.Label(wrap, text="🎵  " + os.path.basename(path), bg=C_BG, fg=C_FG,
                 font=("Segoe UI", 11, "bold"),
                 wraplength=450, justify="left").pack(anchor="w")
        tk.Label(wrap,
                 text="Windows has no built-in (MCI) codec for this audio format,\n"
                      "so the simple player cannot open it.",
                 bg=C_BG, fg=C_FG_DIM, justify="left").pack(anchor="w", pady=(8, 12))
        tk.Button(wrap, text="▶  Open in the default program",
                  bg="white", fg="black", relief="flat",
                  command=lambda: (self._mgr._open_local_file(path, use_overrides=False,
                                                             use_hub=False),
                                   self.destroy())).pack(anchor="w")
        self.protocol("WM_DELETE_WINDOW", self._audio_close)

    # ── Text viewer ───────────────────────────────────────────────────────

    def _show_text(self, path: str):
        """Text reader — and, when you press ✎ Edit, a small text EDITOR.

        It opens read-only on purpose (F3 is "look at this"), so a stray key
        press can never touch a file.  ✎ Edit (or Ctrl+E) unlocks it, Ctrl+S
        saves, and closing with unsaved changes asks first.  The file is written
        back in the SAME encoding it was read in, with the same line endings.

        A file too big for the cap is shown truncated and can NEVER be edited —
        saving a truncated buffer would silently chop the rest of the file off.
        """
        try:
            content, enc, truncated = _read_text_best_effort(path)
        except Exception as exc:
            ttk.Label(self, text=f"Could not open file:\n{exc}",
                      padding=20).pack(expand=True)
            return

        self._edit_path      = path
        self._edit_enc       = enc
        self._edit_truncated = truncated
        self._edit_binary    = "\x00" in content[:65536]
        self._editing        = False
        self._dirty          = False
        # Remember the line endings so saving doesn't silently convert the file
        # (a CRLF .nfo turning into LF changes every line for other tools).
        self._edit_newline   = "\r\n" if "\r\n" in content else "\n"

        # ── toolbar ──────────────────────────────────────────────────
        tb = tk.Frame(self, bg=C_BG2)
        tb.pack(fill="x")
        try:
            size = os.path.getsize(path)
        except OSError:
            size = 0
        info = f"  {os.path.basename(path)}    ·    {size:,} bytes    ·    {enc}"
        if truncated:
            info += "    ·    (large file — showing the first part only)"
        self._info_base = info
        self._info_lbl = tk.Label(tb, text=info, bg=C_BG2, fg=C_FG,
                                  font=("Segoe UI", 9))
        self._info_lbl.pack(side="left")

        self._txt_wrap = tk.BooleanVar(value=False)

        def _toggle_wrap():
            try:
                self._txt.configure(wrap="word" if self._txt_wrap.get() else "none")
            except Exception:
                pass

        # normal button colour: C_BG3 (change to taste, e.g. "green")
        tk.Checkbutton(tb, text="Wrap lines", variable=self._txt_wrap,
                       command=_toggle_wrap, bg=C_BG2, fg=C_FG,
                       selectcolor=C_BG3, activebackground=C_BG2,
                       activeforeground=C_FG, font=("Segoe UI", 8),
                       takefocus=0).pack(side="right", padx=6, pady=2)

        # ── editing controls (only when the manager allows it) ───────
        try:
            allow_edit = bool(self._mgr.settings.get("reader_editable", True))
        except Exception:
            allow_edit = True

        self._btn_save = None
        self._btn_edit = None
        if allow_edit:
            # normal button colours are written out so they are easy to change
            self._btn_save = tk.Button(tb, text="💾  Save   (Ctrl+S)",
                                       bg="lightgreen", fg="black", relief="flat",
                                       state="disabled", command=self._save_text)
            self._btn_save.pack(side="right", padx=(2, 6), pady=2)
            self._btn_edit = tk.Button(tb, text="✎  Edit   (Ctrl+E)",
                                       bg="white", fg="black", relief="flat",
                                       command=self._toggle_edit)
            self._btn_edit.pack(side="right", padx=2, pady=2)
            if truncated:
                self._btn_edit.configure(state="disabled",
                                         text="✎  Edit  (file too large)")

        # ── text area ────────────────────────────────────────────────
        frame = ttk.Frame(self)
        frame.pack(fill="both", expand=True)
        vsb = ttk.Scrollbar(frame, orient="vertical")
        hsb = ttk.Scrollbar(frame, orient="horizontal")
        # tk.Text (not ttk) with a FIXED (non-blinking) caret per house rules.
        txt = tk.Text(frame, wrap="none", bg=C_BG, fg=C_FG,
                      insertbackground=C_FG, insertofftime=0, insertontime=9999999,
                      font=("Consolas", 10), undo=True, maxundo=-1,
                      autoseparators=True, highlightthickness=0,
                      borderwidth=0, yscrollcommand=vsb.set, xscrollcommand=hsb.set)
        vsb.config(command=txt.yview)
        hsb.config(command=txt.xview)
        vsb.pack(side="right", fill="y")
        hsb.pack(side="bottom", fill="x")
        txt.pack(side="left", fill="both", expand=True)
        txt.insert("1.0", content)
        txt.edit_reset()                  # the initial text is not an undo step
        txt.edit_modified(False)
        txt.configure(state="disabled")   # read-only, but still selectable/copyable
        # Mouse-wheel scrolling (the widget is disabled, so bind it explicitly)
        txt.bind("<MouseWheel>",
                 lambda e: (txt.yview_scroll(int(-e.delta / 120), "units"), "break")[1])
        txt.bind("<Shift-MouseWheel>",
                 lambda e: (txt.xview_scroll(int(-e.delta / 120), "units"), "break")[1])
        txt.bind("<<Modified>>", self._on_text_modified)
        self._txt = txt
        txt.focus_set()

        if allow_edit:
            self.bind("<Control-s>", lambda e: (self._save_text(), "break")[1])
            self.bind("<Control-S>", lambda e: (self._save_text(), "break")[1])
            self.bind("<Control-e>", lambda e: (self._toggle_edit(), "break")[1])
            self.bind("<Control-E>", lambda e: (self._toggle_edit(), "break")[1])
        # Escape / the window X must not throw away unsaved work
        self.bind("<Escape>", lambda e: self._close_text())
        self.protocol("WM_DELETE_WINDOW", self._close_text)

    # ── Text editing ──────────────────────────────────────────────────────

    def _on_text_modified(self, _event=None):
        """<<Modified>> fires once until the flag is reset; use it to track the
        unsaved state cheaply instead of comparing the whole buffer."""
        try:
            if not self._txt.edit_modified():
                return
            self._txt.edit_modified(False)
        except Exception:
            return
        if self._editing and not self._dirty:
            self._dirty = True
            self._update_title()

    def _update_title(self):
        mark = "  ●  UNSAVED" if self._dirty else ""
        mode = "Editing" if self._editing else "Viewer"
        try:
            self.title(f"{mode} — {os.path.basename(self._edit_path)}{mark}")
            self._info_lbl.config(
                text=self._info_base + ("    ·    UNSAVED CHANGES" if self._dirty else ""),
                fg=("#ffcc66" if self._dirty else C_FG))
            if self._btn_save is not None:
                self._btn_save.configure(
                    state=("normal" if (self._editing and self._dirty) else "disabled"))
        except Exception:
            pass

    def _toggle_edit(self):
        """Unlock the text for editing (or lock it again)."""
        if self._edit_truncated:
            messagebox.showwarning(
                "Too large to edit",
                "Only the first part of this file is loaded, so saving would cut "
                "the rest of it off.\n\nOpen it in an external editor instead (F4).",
                parent=self)
            return
        if not self._editing and self._edit_binary:
            if not _ask_yes_no(
                    "Binary file",
                    "This file contains binary data — it is shown as text so you "
                    "can peek at it, but saving it as text WILL corrupt it.\n\n"
                    "Edit anyway?", parent=self):
                return
        if self._editing and self._dirty:
            if not _ask_yes_no("Discard changes",
                                       "Lock the text again and lose the unsaved "
                                       "changes?", parent=self):
                return
            self._reload_text()
        self._editing = not self._editing
        self._txt.configure(state="normal" if self._editing else "disabled")
        if self._btn_edit is not None:
            self._btn_edit.configure(
                text=("🔒  Stop editing" if self._editing else "✎  Edit   (Ctrl+E)"),
                bg=("orange" if self._editing else "white"))
        if self._editing:
            self._txt.focus_set()
        self._update_title()

    def _reload_text(self):
        """Throw the buffer away and read the file again."""
        try:
            content, enc, truncated = _read_text_best_effort(self._edit_path)
        except Exception:
            return
        self._edit_enc, self._edit_truncated = enc, truncated
        was = self._txt.cget("state")
        self._txt.configure(state="normal")
        self._txt.delete("1.0", "end")
        self._txt.insert("1.0", content)
        self._txt.edit_reset()
        self._txt.edit_modified(False)
        self._txt.configure(state=was)
        self._dirty = False
        self._update_title()

    def _save_text(self):
        """Write the buffer back, in the encoding and line endings it came with.

        The file is written to a temporary name in the same folder and then
        moved over the original, so a failure half-way cannot leave a
        half-written file where your data used to be."""
        if not self._editing:
            return
        if self._edit_truncated:
            messagebox.showerror("Not saved",
                                 "Only part of this file is loaded — saving it "
                                 "would cut the rest off.", parent=self)
            return
        text = self._txt.get("1.0", "end-1c")
        if self._edit_newline == "\r\n":
            text = text.replace("\r\n", "\n").replace("\n", "\r\n")
        enc = self._edit_enc or "utf-8"
        try:
            data = text.encode(enc, "strict")
        except (UnicodeEncodeError, LookupError):
            if not _ask_yes_no(
                    "Encoding",
                    f"Some characters you typed cannot be written in this file's "
                    f"encoding ({enc}).\n\nSave it as UTF-8 instead?", parent=self):
                return
            enc = "utf-8"
            data = text.encode("utf-8")
        tmp = self._edit_path + ".~fmtmp"
        try:
            with open(tmp, "wb") as fh:
                fh.write(data)
                fh.flush()
                os.fsync(fh.fileno())
            os.replace(tmp, self._edit_path)
        except Exception as exc:
            try:
                if os.path.exists(tmp):
                    os.remove(tmp)
            except Exception:
                pass
            messagebox.showerror("Could not save", f"{self._edit_path}\n\n{exc}",
                                 parent=self)
            return
        self._dirty = False
        self._txt.edit_modified(False)
        self._update_title()
        try:
            size = os.path.getsize(self._edit_path)
            self._info_base = (f"  {os.path.basename(self._edit_path)}"
                               f"    ·    {size:,} bytes    ·    {enc}")
        except OSError:
            pass
        _flash_ok(self, "Saved", "Saved")
        # Let the panels pick up the new size / date at once
        try:
            self._mgr.refresh_panels()
        except Exception:
            pass

    def _close_text(self):
        """Close, but never silently drop unsaved work."""
        if getattr(self, "_dirty", False):
            ans = _ask_yes_no_cancel(
                "Unsaved changes",
                f"Save your changes to\n{os.path.basename(self._edit_path)}?",
                parent=self)
            if ans is None:
                return
            if ans:
                self._save_text()
                if self._dirty:          # the save failed — stay open
                    return
        self.destroy()

    # ── shared widget helpers ─────────────────────────────────────────────

    def _make_canvas_area(self, parent):
        """Return a scrollable (canvas, vsb, hsb) triple packed into parent."""
        frame = ttk.Frame(parent)
        frame.pack(fill="both", expand=True)
        vsb = ttk.Scrollbar(frame, orient="vertical")
        hsb = ttk.Scrollbar(frame, orient="horizontal")
        c   = tk.Canvas(frame, bg="#303040",
                        yscrollcommand=vsb.set, xscrollcommand=hsb.set,
                        highlightthickness=0)
        vsb.config(command=c.yview)
        hsb.config(command=c.xview)
        vsb.pack(side="right", fill="y")
        hsb.pack(side="bottom", fill="x")
        c.pack(fill="both", expand=True)
        return c, vsb, hsb

    # ── Image viewer ──────────────────────────────────────────────────────

    def _show_image(self, path: str):
        try:
            from PIL import Image, ImageTk
        except ImportError:
            ttk.Label(
                self,
                text="Pillow is needed for image preview.\n\npip install pillow",
                justify="center", padding=20,
            ).pack(expand=True)
            return

        try:
            self._pil_image = Image.open(path)
            self._pil_image.load()
        except Exception as exc:
            ttk.Label(self, text=f"Could not open image:\n{exc}",
                      padding=20).pack(expand=True)
            return

        # ── toolbar ──────────────────────────────────────────────────
        tb = tk.Frame(self, bg=C_BG2)
        tb.pack(fill="x")
        tk.Label(tb, text=f"  {os.path.basename(path)}  "
                          f"({self._pil_image.width}×{self._pil_image.height})",
                 bg=C_BG2, fg=C_FG, font=("Segoe UI", 9)).pack(side="left")

        self._img_zoom = 1.0
        for txt, cmd in [("＋", self._img_zoom_in),
                          ("－", self._img_zoom_out),
                          ("1:1", self._img_zoom_reset),
                          ("Fit", self._img_zoom_fit)]:
            tk.Button(tb, text=txt, command=cmd,
                      bg=C_BG3, fg=C_FG, relief="flat",
                      padx=6, cursor="hand2").pack(side="right", padx=1, pady=2)

        # ── canvas ──────────────────────────────────────────────────
        self._img_canvas, _, _ = self._make_canvas_area(self)
        self._img_canvas.bind("<MouseWheel>", self._img_scroll)
        self._img_canvas.bind("<Configure>",  lambda e: self._img_render())
        self._img_render()

    def _img_render(self):
        if not hasattr(self, "_pil_image"):
            return
        try:
            from PIL import Image, ImageTk
        except ImportError:
            return
        w = max(1, int(self._pil_image.width  * self._img_zoom))
        h = max(1, int(self._pil_image.height * self._img_zoom))
        resampler = getattr(Image, "LANCZOS", getattr(Image, "ANTIALIAS", 1))
        img = self._pil_image.copy().resize((w, h), resampler)
        self._img_tk = ImageTk.PhotoImage(img)
        c  = self._img_canvas
        cw = max(w, c.winfo_width())
        ch = max(h, c.winfo_height())
        c.delete("all")
        c.create_image(cw // 2, ch // 2, anchor="center", image=self._img_tk)
        c.configure(scrollregion=(0, 0, cw, ch))

    def _img_zoom_in(self):
        self._img_zoom = min(self._img_zoom * 1.25, 12.0)
        self._img_render()

    def _img_zoom_out(self):
        self._img_zoom = max(self._img_zoom / 1.25, 0.04)
        self._img_render()

    def _img_zoom_reset(self):
        self._img_zoom = 1.0
        self._img_render()

    def _img_zoom_fit(self):
        if not hasattr(self, "_pil_image"):
            return
        cw = self._img_canvas.winfo_width()
        ch = self._img_canvas.winfo_height()
        if cw < 2 or ch < 2:
            return
        self._img_zoom = min(cw / self._pil_image.width,
                              ch / self._pil_image.height)
        self._img_render()

    def _img_scroll(self, event):
        if event.state & 0x4:   # Ctrl → zoom
            if event.delta > 0: self._img_zoom_in()
            else:               self._img_zoom_out()
        else:
            self._img_canvas.yview_scroll(-1 * (event.delta // 120), "units")

    # ── PDF viewer ────────────────────────────────────────────────────────

    def _show_pdf(self, path: str):
        try:
            import fitz  # PyMuPDF
            self._fitz_doc       = fitz.open(path)
            self._pdf_page_count = len(self._fitz_doc)
            self._pdf_page_idx   = 0
            self._pdf_zoom       = 1.5
            self._pdf_path       = path
            self._show_pdf_fitz()
        except ImportError:
            self._show_pdf_text_fallback(path)

    def _show_pdf_fitz(self):
        try:
            from PIL import Image, ImageTk
        except ImportError:
            ttk.Label(
                self,
                text="Pillow is also needed for PDF rendering.\n\npip install pillow pymupdf",
                justify="center", padding=20,
            ).pack(expand=True)
            return

        # ── toolbar ──────────────────────────────────────────────────
        tb = tk.Frame(self, bg=C_BG2)
        tb.pack(fill="x")

        self._pdf_page_var = tk.StringVar(value="1")
        tk.Label(tb, text="  Page:", bg=C_BG2, fg=C_FG,
                 font=("Segoe UI", 9)).pack(side="left")
        pe = tk.Entry(tb, textvariable=self._pdf_page_var, width=5,
                      bg=C_BG3, fg=C_FG, insertbackground=C_FG,
                      insertofftime=0, insertontime=9999999, relief="flat")
        pe.pack(side="left", padx=2, pady=3)
        pe.bind("<Return>", self._pdf_goto_page)

        self._pdf_count_lbl = tk.Label(tb, text=f"/ {self._pdf_page_count}",
                                        bg=C_BG2, fg=C_FG_DIM,
                                        font=("Segoe UI", 9))
        self._pdf_count_lbl.pack(side="left", padx=(0, 8))

        for txt, cmd in [("◀", self._pdf_prev), ("▶", self._pdf_next),
                          ("＋", self._pdf_zoom_in), ("－", self._pdf_zoom_out)]:
            tk.Button(tb, text=txt, command=cmd,
                      bg=C_BG3, fg=C_FG, relief="flat",
                      padx=6, cursor="hand2").pack(side="left", padx=1, pady=2)

        tk.Label(tb, text=f"  {os.path.basename(self._pdf_path)}",
                 bg=C_BG2, fg=C_FG_DIM, font=("Segoe UI", 8, "italic")).pack(
            side="left", padx=6)

        # ── canvas ──────────────────────────────────────────────────
        self._pdf_canvas, _, _ = self._make_canvas_area(self)
        self._pdf_canvas.bind("<MouseWheel>", self._pdf_scroll)
        self.bind("<Left>",  lambda e: self._pdf_prev())
        self.bind("<Right>", lambda e: self._pdf_next())

        self._pdf_render_page()

    def _pdf_render_page(self):
        try:
            import fitz
            from PIL import Image, ImageTk
        except ImportError:
            return
        page = self._fitz_doc[self._pdf_page_idx]
        mat  = fitz.Matrix(self._pdf_zoom, self._pdf_zoom)
        pix  = page.get_pixmap(matrix=mat, alpha=False)
        img  = Image.frombytes("RGB", (pix.width, pix.height), pix.samples)
        self._pdf_tk = ImageTk.PhotoImage(img)
        c   = self._pdf_canvas
        cw  = max(pix.width, c.winfo_width())
        c.delete("all")
        c.create_image(cw // 2, 10, anchor="n", image=self._pdf_tk)
        c.configure(scrollregion=(0, 0, max(pix.width, cw), pix.height + 20))
        c.yview_moveto(0)
        self._pdf_page_var.set(str(self._pdf_page_idx + 1))

    def _pdf_prev(self):
        if self._pdf_page_idx > 0:
            self._pdf_page_idx -= 1
            self._pdf_render_page()

    def _pdf_next(self):
        if self._pdf_page_idx < self._pdf_page_count - 1:
            self._pdf_page_idx += 1
            self._pdf_render_page()

    def _pdf_goto_page(self, event=None):
        try:
            n = int(self._pdf_page_var.get()) - 1
            if 0 <= n < self._pdf_page_count:
                self._pdf_page_idx = n
                self._pdf_render_page()
        except ValueError:
            pass

    def _pdf_zoom_in(self):
        self._pdf_zoom = min(self._pdf_zoom + 0.25, 6.0)
        self._pdf_render_page()

    def _pdf_zoom_out(self):
        self._pdf_zoom = max(self._pdf_zoom - 0.25, 0.25)
        self._pdf_render_page()

    def _pdf_scroll(self, event):
        if event.state & 0x4:   # Ctrl → zoom
            if event.delta > 0: self._pdf_zoom_in()
            else:               self._pdf_zoom_out()
        else:
            self._pdf_canvas.yview_scroll(-1 * (event.delta // 120), "units")

    def _show_pdf_text_fallback(self, path: str):
        """Text-only fallback when PyMuPDF is not installed."""
        content = ""
        try:
            from pypdf import PdfReader
            reader = PdfReader(path)
            parts  = []
            for i, p in enumerate(reader.pages, 1):
                txt = p.extract_text() or ""
                parts.append(f"{'─'*60}\n  Page {i}\n{'─'*60}\n{txt}\n")
            content = "\n".join(parts)
        except Exception as exc:
            content = (f"Could not read PDF: {exc}\n\n"
                       "For full page rendering, install PyMuPDF:\n"
                       "  pip install pymupdf\n\n"
                       "For text extraction only, install pypdf:\n"
                       "  pip install pypdf")

        tb = tk.Frame(self, bg=C_BG2)
        tb.pack(fill="x")
        tk.Label(tb,
                 text=f"  PDF (text only — install PyMuPDF for rendering) — "
                      f"{os.path.basename(path)}",
                 bg=C_BG2, fg=C_FG_DIM, font=("Segoe UI", 8, "italic")).pack(
            side="left", padx=6, pady=4)

        frame = ttk.Frame(self)
        frame.pack(fill="both", expand=True)
        vsb = ttk.Scrollbar(frame)
        vsb.pack(side="right", fill="y")
        txt = tk.Text(frame, wrap="word", yscrollcommand=vsb.set,
                      font=("Consolas", 10), padx=10, pady=8,
                      insertofftime=0)
        vsb.config(command=txt.yview)
        txt.pack(fill="both", expand=True)
        txt.insert("1.0", content)
        txt.config(state="disabled")


# ══════════════════════════════════════════════════════════════════════════
#  Main frame
# ══════════════════════════════════════════════════════════════════════════

# ══════════════════════════════════════════════════════════════════════════
#  Copy / Move engine  (TC-style conflict handling)
# ══════════════════════════════════════════════════════════════════════════

def _same_file_enough(src: str, dst: str) -> bool:
    """True when the two files are, to all appearances, the SAME file.

    Same size and the same modified time (within two seconds — FAT stores the
    time in 2-second steps, so a file copied to a USB stick comes back looking
    one second different).  Deliberately does NOT hash: this is used to decide
    "do not bother asking", and reading both files in full to answer a
    question nobody wanted would cost more than the copy it saves.

    Folders always answer False — a folder with the same name is not the same
    folder, and its contents still have to be walked."""
    try:
        if os.path.isdir(src) or os.path.isdir(dst):
            return False
        a, b = os.stat(src), os.stat(dst)
        return a.st_size == b.st_size and abs(a.st_mtime - b.st_mtime) <= 2
    except Exception:
        return False


def _fmt_size(n: int) -> str:
    if n < 1024:        return f"{n} B"
    if n < 1024**2:     return f"{n//1024} KB"
    if n < 1024**3:     return f"{n//1024**2} MB"
    return f"{n//1024**3} GB"


# Files that are RUN rather than opened.  Enter / double-click on one of these
# starts it; F4 still edits it, Shift+Enter still shows it in the built-in
# viewer.  .py, .bat and .ps1 are on this list AND in DefaultHub's "text" kind
# at the same time, and both are right: they are text files to every other
# program in the tree, and programs to a file manager.
_RUNNABLE_EXTS = {".py", ".pyw", ".exe", ".com", ".bat", ".cmd", ".ps1",
                  ".msi", ".lnk", ".vbs", ".wsf", ".jar"}


def _is_runnable(path: str) -> bool:
    return os.path.splitext(path)[1].lower() in _RUNNABLE_EXTS


def _shorten_mid(text: str, width: int) -> str:
    """Shorten a path for a one-line note, cutting the MIDDLE out.

    A status line has room for one path, not three — and the two ENDS are what
    identify it (which drive, which folder).  Trimming the tail the ordinary
    way would leave every path in his tree looking the same."""
    t = str(text or "")
    if len(t) <= width or width < 8:
        return t
    keep = width - 1
    head = keep // 2
    return t[:head] + "…" + t[len(t) - (keep - head):]


def _group_digits(n: int) -> str:
    """Thousands-group an integer with SPACES: 9133144 → '9 133 144'.
    (Python's format spec only offers ',' or '_', so we swap ',' for a space.)"""
    return format(int(n), ",").replace(",", " ")   # non-breaking space


def _dir_is_empty(path: str) -> bool:
    """True only when a directory has NO entries at all — no files AND no
    sub-folders.  Uses os.scandir and stops at the first entry, so it is cheap
    even for huge folders.  An unreadable / protected folder counts as NOT
    empty, so it keeps its normal blue colour instead of being mislabelled."""
    try:
        with os.scandir(path) as it:
            return next(it, None) is None
    except Exception:
        return False


def _same_drive(a: str, b: str) -> bool:
    """True when two paths are on the same drive/volume (so a MOVE is a rename)."""
    try:
        return (os.path.splitdrive(os.path.abspath(a))[0].upper()
                == os.path.splitdrive(os.path.abspath(b))[0].upper())
    except Exception:
        return False


# ── How hard a big copy is allowed to pull ────────────────────────────────────
#
# Three ready-made answers to "I do not want a copy to make the machine
# unusable", because seven numbers is not a question anybody wants to answer.
#
#   full        no cap, no priority change — the disk decides
#   polite      full speed, but the copy always gives way (background I/O)
#   background  the above PLUS a hard percentage cap once a file drags on
#
# The middle one is the default, and it is the one that actually does what
# "give the big file less power so I can work" was always supposed to mean.
# See the revAZ note in the header for why SLEEPING was the wrong mechanism.
THROTTLE_PRESETS = {
    "full": {
        "throttle_enabled": False,
        "throttle_soft_after_s": 60,  "throttle_soft_pct": 80,
        "throttle_hard_after_s": 300, "throttle_hard_pct": 60,
        "throttle_batch_after_s": 600, "throttle_batch_pct": 70,
        "io_background": False, "copy_flush_mb": 0,
    },
    "polite": {
        "throttle_enabled": False,
        "throttle_soft_after_s": 60,  "throttle_soft_pct": 80,
        "throttle_hard_after_s": 300, "throttle_hard_pct": 60,
        "throttle_batch_after_s": 600, "throttle_batch_pct": 70,
        "io_background": True, "copy_flush_mb": 64,
    },
    "background": {
        "throttle_enabled": True,
        "throttle_soft_after_s": 5,   "throttle_soft_pct": 60,
        "throttle_hard_after_s": 15,  "throttle_hard_pct": 30,
        "throttle_batch_after_s": 30, "throttle_batch_pct": 50,
        "io_background": True, "copy_flush_mb": 32,
    },
}


def _throttle_preset_name(s: dict) -> str:
    """Which preset the current settings match, or 'custom'."""
    for name, vals in THROTTLE_PRESETS.items():
        if all(s.get(k) == v for k, v in vals.items()):
            return name
    return "custom"


# ── The knob that ACTUALLY frees the machine: background I/O priority ─────────
#
# Sleeping between blocks hands nobody a single disk request.  The copy still
# ASKS for its I/O at the same priority as the program you are trying to use,
# and one drive serves one queue: a 4 MB write that is already in flight is
# still in front of Explorer's 8 KB read.  Making the copy sleep only makes it
# last LONGER, so the queue it is sitting in front of stays clogged for longer
# — which is exactly backwards, and exactly what a 10 GB C→C copy felt like.
#
# Windows has the real mechanism.  Background mode drops the CALLING THREAD's
# I/O priority to Very Low and its memory priority with it, and the kernel then
# lets normal-priority requests jump the queue.  It is what Windows Search and
# Defender use so they can grind away unnoticed.  Two properties matter here:
#   • it costs nothing on an idle machine — nothing is competing, so nothing
#     jumps ahead, and the copy runs at full speed;
#   • it takes effect on the very next request, not after sixty seconds.
_THREAD_MODE_BACKGROUND_BEGIN = 0x00010000
_THREAD_MODE_BACKGROUND_END   = 0x00020000


def _io_background(on: bool) -> bool:
    """Put THIS thread into (or out of) Windows background I/O mode.

    Thread-level on purpose: putting the whole PROCESS in background mode would
    drag the GUI down with it.  Returns True when the call was accepted (a
    thread already in background mode returns False, which is harmless)."""
    if os.name != "nt":
        return False
    try:
        k32 = ctypes.windll.kernel32
        k32.SetThreadPriority.argtypes = [ctypes.c_void_p, ctypes.c_int]
        return bool(k32.SetThreadPriority(
            k32.GetCurrentThread(),
            _THREAD_MODE_BACKGROUND_BEGIN if on else _THREAD_MODE_BACKGROUND_END))
    except Exception:
        return False


def _clear_readonly(path: str) -> bool:
    """Take the READ-ONLY attribute off a file.  True when it is now writable.

    This is the whole of the "Permission denied" mystery (revBI).  Nothing was
    locked: his sources carry the read-only attribute, `shutil.copystat` copies
    that attribute to the destination, and so the SECOND copy of the same tree
    meets a read-only file where it wants to write.  Windows then refuses both
    the delete and the create, and the error says "Permission denied" — which
    reads exactly like a file another program is holding open.

    Clearing it is right, not a liberty: he asked for Overwrite / Backup-rename
    on that file.  And it is put straight back afterwards, because copystat
    re-applies the source's attributes once the copy is written."""
    try:
        if not os.path.exists(path):
            return True
        if os.access(path, os.W_OK):
            return True
        os.chmod(path, stat.S_IWRITE)
        return os.access(path, os.W_OK)
    except Exception:
        return False


def _force_remove(path: str) -> bool:
    """Delete a file or folder, clearing read-only where that is what stops it.

    Returns True when the path is gone.  A read-only file makes os.remove raise
    WinError 5, and swallowing that (which is what used to happen) turned a
    plain "the old file is read-only" into an unrelated failure further down."""
    for attempt in (0, 1):
        try:
            if not os.path.exists(path):
                return True
            if os.path.isdir(path) and not os.path.islink(path):
                shutil.rmtree(path, onerror=_rmtree_readonly)
            else:
                os.remove(path)
            return not os.path.exists(path)
        except OSError:
            if attempt:
                return False
            if not _clear_readonly(path):
                return False
    return False


def _rmtree_readonly(func, path, _exc):
    """rmtree onerror hook: clear read-only and try that one entry again."""
    try:
        _clear_readonly(path)
        func(path)
    except Exception:
        pass


def _open_sequential(path: str, write: bool):
    """open() with FILE_FLAG_SEQUENTIAL_SCAN, the second half of the problem.

    A buffered 10 GB read fills the Windows file cache with 10 GB of pages the
    copy will never look at again, and every one of them is evicted from
    somewhere useful — which is why LogonUI and a cold python.exe had to be
    read back off the same overloaded disk.  O_SEQUENTIAL tells the cache
    manager to free the pages behind a sequential stream, so the copy stops
    pushing the rest of the machine out of RAM.  Falls back to a plain open()
    on anything that is not Windows."""
    flags = os.O_BINARY if hasattr(os, "O_BINARY") else 0
    flags |= getattr(os, "O_SEQUENTIAL", 0)
    try:
        if write:
            fd = os.open(path, flags | os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o666)
            return open(fd, "wb", buffering=0)
        fd = os.open(path, flags | os.O_RDONLY)
        return open(fd, "rb", buffering=0)
    except PermissionError:
        # An EXISTING read-only destination is the common case here and it is
        # not a real refusal — the attribute is put back by copystat as soon as
        # the copy is written.  Retry once with it cleared before falling
        # through to the plain open(), so the second copy of a read-only tree
        # does not come back as "Permission denied" (revBI).
        if write and _clear_readonly(path):
            try:
                fd = os.open(path, flags | os.O_WRONLY | os.O_CREAT | os.O_TRUNC,
                             0o666)
                return open(fd, "wb", buffering=0)
            except Exception:
                pass
        raise
    except Exception:
        return open(path, "wb" if write else "rb", buffering=0)


def _copy_file_chunked(src, dst, *, is_cancelled, is_paused, throttle,
                       batch_start, keep_date=True, on_bytes=None) -> bool:
    """Copy ONE file in blocks so a big transfer can be CANCELLED, PAUSED and
    THROTTLED mid-file — the whole reason a 9 GB copy could not be stopped
    before (shutil.copy2 runs a single file to completion with no way in).

      • is_cancelled()  → bool: stop now, delete the partial destination, return False
      • is_paused()     → bool: block here (still cancellable) while True
      • throttle        → dict of the throttle settings (or None to disable)
      • batch_start     → monotonic() time the whole job began (for the batch cap)
      • on_bytes(n)     → called with each block written, so a 6 GB file can
                          show a bar that MOVES instead of one that sits at 50%
                          for eight minutes

    READ-AHEAD: one thread reads the next block while this one writes the last.
    On two DIFFERENT devices, reading and writing in turn on one thread leaves
    each of them idle half the time.  On ONE device (C→C) it is the opposite —
    the read-ahead only interleaves reads into the write stream and deepens the
    queue — so the look-ahead is cut to a single block there.

    LIVE SETTINGS: `throttle` may be a dict, or a zero-argument callable that
    returns one.  With a callable it is re-read a couple of times a second, so
    ticking "⚡ Full speed" in the Task Queue takes effect on the file that is
    ALREADY RUNNING, which is the only moment anybody ever wants it.

    Returns True on success, False if cancelled (partial dst removed)."""
    _thr_of = throttle if callable(throttle) else (lambda: throttle)
    thr0    = _thr_of() or {}
    chunk = max(64 * 1024, int(thr0.get("copy_chunk_kb", 4096)) * 1024) \
        if thr0 else 4 * 1024 * 1024
    file_start = _time.monotonic()
    # One device = no look-ahead beyond a single block (see the note above).
    q: "queue.Queue" = queue.Queue(maxsize=1 if _same_drive(src, dst) else 3)
    stop = threading.Event()
    read_err: list = []
    bg_wanted = bool(thr0.get("io_background", True))

    def _reader():
        # The reader is a thread of its own, and background mode is PER THREAD.
        #
        # It RE-READS the setting as it goes (revBN).  ⚡ Full speed is meant to
        # reach the file that is ALREADY being copied, and it only ever lifted
        # the WRITER's priority: this thread took one look at io_background when
        # the file was opened and stayed at Very Low for the rest of it.  On a
        # single big file that is half the switch quietly doing nothing.
        my_bg   = bg_wanted
        bg_read = _time.monotonic()
        if my_bg:
            _io_background(True)
        try:
            with _open_sequential(src, write=False) as fi:
                while not stop.is_set():
                    now_r = _time.monotonic()
                    if callable(throttle) and now_r - bg_read >= 0.5:
                        bg_read = now_r
                        want_r = bool((_thr_of() or {}).get("io_background", True))
                        if want_r != my_bg:
                            _io_background(want_r)
                            my_bg = want_r
                    buf = fi.read(chunk)
                    if not buf:
                        break
                    # Never a blocking put: a cancel must not leave this thread
                    # parked on a full queue for the rest of the session.
                    while not stop.is_set():
                        try:
                            q.put(buf, timeout=0.2)
                            break
                        except queue.Full:
                            continue
        except Exception as exc:
            read_err.append(exc)
        finally:
            if my_bg:
                _io_background(False)
            # ── THE END MARKER MUST GET THROUGH (revBN) ──────────────────
            # This was ONE `q.put(None, timeout=0.5)` inside a bare
            # `except Exception: pass`.  The queue holds three blocks; if it
            # happened to be FULL when the last block was read, and the writer
            # took longer than half a second over its own block — one fsync to
            # a USB disk does it, so does standing aside for the bus lane, so
            # does a throttle sleep of up to 2 s — the put timed out, the
            # exception was swallowed, and the marker was never sent at all.
            # The writer's only way out of its loop is `buf is None`, so it
            # then sat on q.get() FOR EVER: destination file complete and still
            # open, task stuck on RUNNING, not one byte moving, and a progress
            # bar still quoting a speed.  (2026-09-12: two lanes onto one USB
            # disk; both died within 76 seconds of each other and the queue
            # stood still for half an hour without saying so.)
            # Retry until it lands or the copy is being torn down.
            while not stop.is_set():
                try:
                    q.put(None, timeout=0.2)      # end marker
                    break
                except queue.Full:
                    continue

    reader = threading.Thread(target=_reader, daemon=True)
    bg_on  = False
    # Pacing state.  full_rate is measured, not guessed: the fastest 2-second
    # stretch seen while NOTHING was capping it is what "100 % of full speed"
    # means for this particular file on this particular pair of disks.
    full_rate  = 0.0          # bytes/s
    win_bytes  = 0
    win_start  = file_start
    cap_frac   = 1.0
    cap_bytes  = 0
    cap_since  = file_start
    since_flush = 0
    thr        = thr0
    thr_read   = 0.0
    try:
        if bg_wanted:
            bg_on = _io_background(True)
        with _open_sequential(dst, write=True) as fo:
            reader.start()
            while True:
                if is_cancelled():
                    stop.set()
                    fo.close()
                    try:
                        os.remove(dst)
                    except Exception:
                        pass
                    return False
                # Pause blocks here but stays cancellable.
                while is_paused() and not is_cancelled():
                    _time.sleep(0.1)
                try:
                    buf = q.get(timeout=0.2)
                except queue.Empty:
                    if read_err:
                        raise read_err[0]
                    # BELT AND BRACES for the hang above (revBN).  If the reader
                    # thread has finished AND the queue is empty, this file is
                    # over: nothing can ever arrive again, marker or no marker.
                    # The reader puts its marker in BEFORE it ends, so a dead
                    # reader with an empty queue can only mean the marker was
                    # already taken — never that one is still on its way.
                    if not reader.is_alive() and q.empty():
                        break
                    continue
                if buf is None:
                    break
                fo.write(buf)
                now = _time.monotonic()
                n   = len(buf)
                if on_bytes:
                    try:
                        on_bytes(n)
                    except Exception:
                        pass

                # Re-read the live settings twice a second, no more: this is
                # what makes the toolbar checkbox reach a running file.
                if callable(throttle) and now - thr_read >= 0.5:
                    thr_read = now
                    thr = _thr_of() or {}
                    want_bg = bool(thr.get("io_background", True))
                    if want_bg != bg_on:
                        _io_background(want_bg)
                        bg_on = want_bg

                # ── Keep the write-behind cache BOUNDED ──────────────────
                # Ordinary buffered writes land in the Windows file cache and
                # are drained by the lazy writer.  Feed it faster than the disk
                # can drain — trivially easy on a drive whose SLC cache has run
                # out — and the dirty page count climbs into the gigabytes.
                # Windows then throttles EVERY process that writes anything and
                # starts evicting mapped pages to find room, which is the
                # 30-seconds-for-Ctrl+Alt+Del part of the story.  Flushing every
                # N MB writes exactly the same bytes; it just refuses to let the
                # backlog grow without limit.  (At background I/O priority this
                # wait costs other programs nothing — they overtake it.)
                since_flush += n
                fmb = int(thr.get("copy_flush_mb", 64) or 0)
                if fmb > 0 and since_flush >= fmb * 1024 * 1024:
                    since_flush = 0
                    try:
                        os.fsync(fo.fileno())
                    except Exception:
                        pass

                # ── Percentage cap (only when it is asked for) ────────────
                # The old code paced on how long fo.write() took.  With a
                # buffered write that is the time to memcpy into RAM —
                # microseconds — so the sleep was microseconds and the cap did
                # NOTHING until the cache was already saturated, i.e. until the
                # machine had already seized.  Real throughput is measured here
                # instead, against the fastest uncapped stretch of this file.
                frac = 1.0
                if thr and thr.get("throttle_enabled", False):
                    fe = now - file_start
                    be = now - batch_start
                    if fe >= thr.get("throttle_hard_after_s", 300):
                        frac = min(frac, thr.get("throttle_hard_pct", 60) / 100.0)
                    elif fe >= thr.get("throttle_soft_after_s", 60):
                        frac = min(frac, thr.get("throttle_soft_pct", 80) / 100.0)
                    if be >= thr.get("throttle_batch_after_s", 600):
                        frac = min(frac, thr.get("throttle_batch_pct", 70) / 100.0)
                if frac != cap_frac:
                    cap_frac, cap_bytes, cap_since = frac, 0, now
                if frac >= 1.0:
                    # Uncapped: this is what full speed looks like.  Whole
                    # windows only, so a half-finished one cannot report a
                    # fantasy rate and pin the cap far too high.
                    win_bytes += n
                    if now - win_start >= 2.0:
                        full_rate = max(full_rate, win_bytes / (now - win_start))
                        win_bytes, win_start = 0, now
                elif full_rate > 0:
                    cap_bytes += n
                    ideal = cap_bytes / (full_rate * frac)
                    behind = ideal - (now - cap_since)
                    if behind > 0:
                        _time.sleep(min(2.0, behind))
        if read_err:
            raise read_err[0]
        if keep_date:
            try:
                shutil.copystat(src, dst)
            except Exception:
                pass
        return True
    except Exception:
        # A failure must not leave a half-written destination behind.
        try:
            if os.path.exists(dst):
                os.remove(dst)
        except Exception:
            pass
        raise
    finally:
        # Hand this thread its normal I/O priority back before it goes on to
        # do anything else — background mode is sticky until it is ended.
        if bg_on:
            _io_background(False)
        stop.set()
        # Let the reader out of a put() it may be sitting in.
        try:
            while True:
                q.get_nowait()
        except queue.Empty:
            pass
        if reader.is_alive():
            reader.join(timeout=1.0)


def _auto_rename_path(dest: str) -> str:
    """Return a non-existing path by appending _1, _2 … before the extension."""
    base, ext = os.path.splitext(dest)
    i = 1
    while True:
        candidate = f"{base}_{i}{ext}"
        if not os.path.exists(candidate):
            return candidate
        i += 1


# Free space per volume, remembered for a few seconds.  smart_sort() asks for
# every pending task every time the queue is re-sorted — and the queue thread
# re-sorts twice a second while it is waiting for something.  On a network
# share each of those is a round trip to the server, so the answer is cached.
_FREE_SPACE_CACHE: dict = {}


def _free_space(path: str, ttl: float = 5.0) -> int:
    """Free bytes on the volume holding *path*, or -1 when it cannot be asked."""
    if not path:
        return -1
    try:
        drv = os.path.splitdrive(os.path.abspath(path))[0] or path
    except Exception:
        drv = path
    key = os.path.normcase(drv)
    now = _time.monotonic()
    hit = _FREE_SPACE_CACHE.get(key)
    if hit and (now - hit[0]) < ttl:
        return hit[1]
    free = -1
    root = drv if drv.endswith(os.sep) else drv + os.sep
    for probe in (path, root):
        try:
            free = shutil.disk_usage(probe).free
            break
        except Exception:
            continue
    _FREE_SPACE_CACHE[key] = (now, free)
    return free


# "Notes (3).py" — the suffix a browser (or Windows) adds when the same file is
# saved again into a folder that already has it.  Up to three digits in round
# brackets, right before the extension, with or without a space in front.
_COPY_SUFFIX_RE = _re.compile(r"^(?P<base>.+?)[ _]*\((?P<n>\d{1,3})\)$")


def _copy_suffix_number(name: str) -> int:
    """The number in a "(3)" suffix, or 0 when the name has none."""
    stem = os.path.splitext(name)[0]
    m = _COPY_SUFFIX_RE.match(stem)
    if not m:
        return 0
    try:
        return int(m.group("n"))
    except ValueError:
        return 0


def _strip_copy_suffix(name: str) -> str:
    """'Notes (3).py' → 'Notes.py'.  Unchanged when there is no such suffix.

    This is what makes the file manager see the third save of the same program
    as the SAME file: everything but the bracketed number is identical, so it
    can be offered the plain name instead of piling up (2), (3), (4)…
    """
    stem, ext = os.path.splitext(name)
    m = _COPY_SUFFIX_RE.match(stem)
    if not m:
        return name
    base = m.group("base").rstrip()
    return (base + ext) if base else name


def _scan_suffix_twins(sources: list, dest_dir: str) -> list:
    """Sources that are a "(3)" copy of a file ALREADY at the destination.

    Returns [{"src", "dst", "base"}].  A source whose exact name is taken is
    NOT listed — that is an ordinary clash and the normal dialog owns it.
    """
    out = []
    if not dest_dir:
        return out
    for s in sources:
        try:
            if not os.path.isfile(s):
                continue
            name = os.path.basename(s)
            base = _strip_copy_suffix(name)
            if base == name:
                continue
            if os.path.exists(os.path.join(dest_dir, name)):
                continue            # real clash — not our business
            dst_base = os.path.join(dest_dir, base)
            if os.path.isfile(dst_base):
                out.append({"src": s, "dst": dst_base, "base": base})
        except Exception:
            continue
    return out


def _load_twin_rules() -> list:
    return _load_json_list(TWIN_RULES_PATH)


def _save_twin_rules(rules: list):
    _save_json_list(TWIN_RULES_PATH, rules)


def _match_twin_rule(src_dir: str, dst_dir: str) -> str:
    """The remembered answer for this folder pair ("" when there is none).

    Matching is the same as the smart-queue conflict rules: a rule's folder
    matches that folder or anything under it, and a blank one means "any"."""
    def _n(p):
        try:
            return os.path.normcase(os.path.abspath(p)) if p else ""
        except Exception:
            return ""

    s, d = _n(src_dir), _n(dst_dir)

    def _under(pattern, target):
        if not pattern:
            return True
        base = _n(pattern)
        return target == base or target.startswith(base + os.sep)

    for r in _load_twin_rules():
        if not r.get("enabled", True):
            continue
        if _under(r.get("src", ""), s) and _under(r.get("dst", ""), d):
            return r.get("policy", "") or ""
    return ""


def _remember_twin_rule(src_dir: str, dst_dir: str, policy: str):
    """Write down "always do this, from here to there" (replacing any older
    answer for the very same pair)."""
    rules = _load_twin_rules()

    def _n(p):
        try:
            return os.path.normcase(os.path.abspath(p)) if p else ""
        except Exception:
            return ""

    rules = [r for r in rules
             if not (_n(r.get("src", "")) == _n(src_dir)
                     and _n(r.get("dst", "")) == _n(dst_dir))]
    rules.append({"src": src_dir, "dst": dst_dir,
                  "policy": policy, "enabled": True})
    _save_twin_rules(rules)


# ── Unpacking steps aside for the person at the keyboard ───────────────────
# An unpack is the LOWEST priority thing this program does: it may take 100 % of
# the machine while you are not browsing or doing anything else, and it gives
# way the moment you touch the mouse or keyboard.  _fm_note_input() is bound to
# every input event of the main window; _fm_be_polite() is called by the unpack
# between members and sleeps a little while input is recent, and merely hands
# the GIL back (a near-zero sleep) when it is not.
_FM_INPUT_AT = 0.0


def _fm_note_input(_event=None):
    global _FM_INPUT_AT
    _FM_INPUT_AT = _time.monotonic()


def _fm_be_polite():
    try:
        if _time.monotonic() - _FM_INPUT_AT < 1.0:
            _time.sleep(0.06)       # you are working: the unpack waits
        else:
            _time.sleep(0.0005)     # idle: just let the UI thread in
    except Exception:
        pass


def _dir_snapshot(folder: str) -> set:
    """Every file that is in *folder* right now (recursively).

    Taken before an extraction so a failed one can be undone precisely: only
    what this attempt wrote is removed, never a file that was already there."""
    out = set()
    try:
        for dirpath, _dirs, names in os.walk(folder):
            for n in names:
                out.add(os.path.normcase(os.path.join(dirpath, n)))
    except Exception:
        pass
    return out


def _dir_take_back(folder: str, before: set) -> int:
    """Delete everything in *folder* that was not in the *before* snapshot,
    then drop the empty folders that leaves.  Returns how many files went."""
    removed = 0
    try:
        for dirpath, _dirs, names in os.walk(folder):
            for n in names:
                p = os.path.join(dirpath, n)
                if os.path.normcase(p) in before:
                    continue
                try:
                    os.remove(p)
                    removed += 1
                except OSError:
                    pass
        for dirpath, dirs, names in os.walk(folder, topdown=False):
            if dirpath == folder:
                continue
            try:
                if not os.listdir(dirpath):
                    os.rmdir(dirpath)
            except OSError:
                pass
    except Exception as exc:
        _log(f"_dir_take_back({folder}): {exc}")
    if removed:
        _log(f"Cleaned up {removed} half-written file(s) in {folder}")
    return removed


def _archive_makes_own_folder(path: str, stem: str) -> bool:
    """True when everything inside the archive already sits in ONE top-level
    folder — extracting into a folder of our own would then give Film/Film/."""
    try:
        entries = archive_list(path)
    except Exception:
        return False
    tops = set()
    for e in entries[:400]:
        name = (e.name or "").replace("\\", "/").lstrip("/")
        if not name:
            continue
        tops.add(name.split("/", 1)[0])
        if len(tops) > 1:
            return False
    return len(tops) == 1


def _count_copy_items(sources: list) -> int:
    """Return the total number of files across all sources (for progress bar)."""
    total = 0
    for src in sources:
        if os.path.isfile(src):
            total += 1
        elif os.path.isdir(src):
            for _, _, fnames in os.walk(src):
                total += max(1, len(fnames))
    return max(1, total)


class _ProgressDialog(tk.Toplevel):
    """Non-blinking progress dialog with ETA.

    Thread-safe: background threads call  .post(*msg)  to enqueue updates;
    the main thread polls every 80 ms via an after() callback.

    Message protocol (first element = kind):
      ("progress", current, total, filename)   — update bar + labels
      ("conflict", src, dst, result_list, evt) — show _ConflictDlg; set evt when done
      ("error",    text, cont_list,       evt) — ask yes/no; set evt when done
      ("done")                                 — close dialog
    """

    def __init__(self, parent, title: str, total: int = 0, cancelable: bool = True):
        super().__init__(parent)
        self.title(title)
        self.resizable(False, False)
        self.configure(bg=C_BG2)
        if parent:
            self.transient(parent)
        # No grab_set — keep the rest of the UI usable while an operation runs.

        self.cancelled   = False
        self._q          = queue.Queue()
        self._start_time: float | None = None
        self._poll_id    = None
        self._done       = False

        # ── UI ────────────────────────────────────────────────────────
        outer = tk.Frame(self, bg=C_BG2, padx=22, pady=14)
        outer.pack()

        tk.Label(outer, text=title, bg=C_BG2, fg=C_ACCENT,
                 font=("Segoe UI", 10, "bold")).pack(anchor="w", pady=(0, 10))

        self._lbl_file = tk.Label(
            outer, text="Preparing…", bg=C_BG2, fg=C_FG,
            font=("Segoe UI", 9), width=54, anchor="w", justify="left",
        )
        self._lbl_file.pack(anchor="w")

        self._pb_var = tk.DoubleVar(value=0.0)
        self._pb = ttk.Progressbar(
            outer, variable=self._pb_var, maximum=100.0,
            length=440, mode="determinate",
        )
        self._pb.pack(pady=(6, 3))

        foot = tk.Frame(outer, bg=C_BG2)
        foot.pack(fill="x")

        self._lbl_count = tk.Label(foot, text="", bg=C_BG2, fg=C_FG_DIM,
                                   font=("Segoe UI", 8), anchor="w")
        self._lbl_count.pack(side="left")

        self._lbl_eta = tk.Label(foot, text="", bg=C_BG2, fg=C_FG_DIM,
                                 font=("Segoe UI", 8), anchor="e")
        self._lbl_eta.pack(side="right")

        if cancelable:
            ttk.Button(outer, text="Cancel", command=self._on_cancel,
                       width=12).pack(pady=(12, 0))
        else:
            tk.Frame(outer, bg=C_BG2, height=8).pack()

        self.protocol("WM_DELETE_WINDOW", self._on_cancel)
        self.bind("<Escape>", lambda e: self._on_cancel())

        # Center over parent
        self.update_idletasks()
        if parent:
            try:
                px = parent.winfo_rootx() + (parent.winfo_width()  - self.winfo_width())  // 2
                py = parent.winfo_rooty() + (parent.winfo_height() - self.winfo_height()) // 2
                self.geometry(f"+{max(0, px)}+{max(0, py)}")
            except Exception:
                pass

        self._poll_id = self.after(80, self._poll)

    # ── thread-safe API ───────────────────────────────────────────────

    def post(self, *msg):
        """Enqueue a message from any thread."""
        self._q.put(msg)

    # ── internal ──────────────────────────────────────────────────────

    def _on_cancel(self):
        self.cancelled = True

    def _poll(self):
        """Drain the queue and update UI. Runs in the main thread every 80 ms."""
        try:
            for _ in range(100):
                msg  = self._q.get_nowait()
                kind = msg[0]

                if kind == "progress":
                    _, cur, total, filename = msg
                    self._update_ui(cur, total, filename)

                elif kind == "conflict":
                    _, src, dst, result_list, evt = msg
                    dlg = _ConflictDlg(self.master, src, dst)
                    self.master.wait_window(dlg)
                    result_list[0] = dlg.action
                    evt.set()
                    try:
                        self.grab_set()   # reclaim grab after conflict dialog
                    except Exception:
                        pass

                elif kind == "error":
                    _, err_msg, cont_list, evt = msg
                    ans = _ask_yes_no(
                        "Error", err_msg + "\n\nContinue with remaining files?",
                        parent=self.master)
                    cont_list[0] = ans
                    evt.set()
                    try:
                        self.grab_set()
                    except Exception:
                        pass

                elif kind == "done":
                    self._close()
                    return

        except queue.Empty:
            pass

        if not self._done:
            self._poll_id = self.after(80, self._poll)

    def _update_ui(self, cur: int, total: int, filename: str):
        if self._start_time is None and cur > 0:
            self._start_time = _time.monotonic()

        total = max(1, total)
        pct   = min(100.0, cur / total * 100.0)
        self._pb_var.set(pct)

        # File label (truncate long names)
        name = os.path.basename(filename) if filename else "…"
        if len(name) > 55:
            name = "…" + name[-52:]
        self._lbl_file.configure(text=name)

        # Count label — detect if values are bytes or file counts
        if total > 50_000:
            self._lbl_count.configure(text=f"{_fmt_size(cur)} / {_fmt_size(total)}")
        else:
            self._lbl_count.configure(text=f"{cur} / {total} files")

        # ETA
        if self._start_time and cur > 0 and cur < total:
            elapsed   = _time.monotonic() - self._start_time
            remaining = elapsed / cur * (total - cur)
            if remaining < 4:
                eta_txt = ""
            elif remaining < 90:
                eta_txt = f"~{remaining:.0f} s left"
            elif remaining < 5400:
                eta_txt = f"~{remaining / 60:.0f} min left"
            else:
                eta_txt = f"~{remaining / 3600:.1f} h left"
            self._lbl_eta.configure(text=eta_txt)
        else:
            self._lbl_eta.configure(text="")

    def _close(self):
        self._done = True
        if self._poll_id:
            try:
                self.after_cancel(self._poll_id)
            except Exception:
                pass
        try:
            self.destroy()
        except Exception:
            pass


class _CopyMoveConfirmDlg(tk.Toplevel):
    """Initial TC-style copy/move dialog: shows source(s) and destination,
    lets the user choose the conflict-resolution policy before starting."""

    def __init__(self, parent, sources: list, dest_dir: str, move: bool):
        super().__init__(parent)
        self.result        = False   # True if user pressed OK
        self.conflict_mode = "ask"   # chosen policy

        verb = "Move" if move else "Copy"
        _setup_toplevel(self, verb, parent)
        self.resizable(True, False)

        pad = dict(padx=10, pady=4)

        # ── Source summary ────────────────────────────────────────────────
        if len(sources) == 1:
            src_text = sources[0]
        else:
            src_text = f"{len(sources)} items from  {os.path.dirname(sources[0])}"
        ttk.Label(self, text=f"{verb}:", anchor="w").pack(fill="x", **pad)
        frm_src = ttk.Frame(self)
        frm_src.pack(fill="x", padx=10, pady=(0, 4))
        self._src_lbl = ttk.Label(frm_src, text=src_text,
                                  foreground=C_ACCENT, anchor="w", wraplength=480)
        self._src_lbl.pack(fill="x")

        ttk.Label(self, text="To:", anchor="w").pack(fill="x", **pad)

        # Editable destination
        self._dest_var = tk.StringVar(value=dest_dir)
        dest_row = ttk.Frame(self)
        dest_row.pack(fill="x", padx=10, pady=(0, 8))
        dest_e = tk.Entry(dest_row, textvariable=self._dest_var, width=52,
                          insertofftime=0, insertontime=9999999)
        dest_e.pack(side="left", fill="x", expand=True)
        ttk.Button(dest_row, text="…", width=3,
                   command=self._browse_dest).pack(side="left", padx=(4, 0))

        ttk.Separator(self, orient="horizontal").pack(fill="x", padx=10, pady=4)

        tk.Label(self,
                 text="Conflicts and disk space will be checked before the job starts.",
                 bg=self["bg"], fg=C_FG_DIM, font=("Segoe UI", 8),
                 anchor="w").pack(fill="x", padx=10, pady=(0, 4))

        # ── Buttons ────────────────────────────────────────────────
        btn_row = ttk.Frame(self)
        btn_row.pack(fill="x", padx=10, pady=(0, 10))
        ttk.Button(btn_row, text=f"  {verb}  ", command=self._ok,
                   width=12).pack(side="left")
        ttk.Button(btn_row, text="Cancel", command=self.destroy,
                   width=10).pack(side="right")

        self.bind("<Return>", lambda e: (self._ok(), "break")[1])
        dest_e.focus_set()
        dest_e.icursor("end")

    def _browse_dest(self):
        d = filedialog.askdirectory(initialdir=self._dest_var.get(), parent=self)
        if d:
            self._dest_var.set(d)

    def _ok(self):
        self.result   = True
        self.dest_dir = self._dest_var.get().strip()
        self.destroy()


class _LockedDlg(tk.Toplevel):
    """"That file is open in another program" — what should happen?

    A MOVE of a locked file cannot rename it, but it can usually still READ it
    (most programs open files sharing read access).  So the useful offer is:
    copy it across now and delete the original the moment the other program
    lets go.  Until then nothing is lost — the original simply stays put.
    """

    COPY_LATER = "copy_then_delete"   # copy now, delete the source when free
    RETRY      = "retry"
    SKIP       = "skip"
    ABORT      = "abort"

    def __init__(self, parent, path: str, reason: str, dest: str):
        super().__init__(parent)
        self.action  = self.SKIP
        self.all_var = tk.BooleanVar(value=False)
        _setup_toplevel(self, "File is in use", parent, modal=True)
        try:
            self.lift()
        except Exception:
            pass
        self.resizable(True, False)
        self.protocol("WM_DELETE_WINDOW", lambda: self._pick(self.SKIP))

        tk.Label(self, text="🔒  This file is in use by another program",
                 font=("Segoe UI", 11, "bold")).pack(padx=16, pady=(16, 2))
        tk.Label(self, text=os.path.basename(path), fg=C_ACCENT,
                 font=("Segoe UI", 10)).pack(padx=16)
        tk.Label(self, text=f"{os.path.dirname(path)}\n→  {dest}",
                 fg="#666666", font=("Segoe UI", 8), justify="center"
                 ).pack(padx=16, pady=(2, 6))
        tk.Label(self, text=f"Windows says: {reason}.",
                 font=("Segoe UI", 9)).pack(padx=16, pady=(0, 10))

        tk.Label(
            self,
            text="It can usually still be READ, just not renamed or deleted.\n"
                 "So the file can be COPIED across now and the original removed\n"
                 "automatically as soon as the other program releases it —\n"
                 "nothing is lost either way, the original just stays put until then.",
            font=("Segoe UI", 9), justify="left"
        ).pack(padx=16, pady=(0, 10), anchor="w")

        ttk.Checkbutton(self, text="Do the same for every other locked file "
                                   "in this job",
                        variable=self.all_var).pack(padx=16, anchor="w")

        btns = ttk.Frame(self)
        btns.pack(padx=16, pady=(10, 14))
        for col, (val, label, width) in enumerate((
                (self.COPY_LATER, "Copy now, delete the original later", 34),
                (self.RETRY,      "Try again", 12),
                (self.SKIP,       "Skip this file", 15),
                (self.ABORT,      "✖  Abort the job", 17))):
            ttk.Button(btns, text=label, width=width,
                       command=lambda v=val: self._pick(v)
                       ).grid(row=0, column=col, padx=4)

        self.update_idletasks()
        if parent:
            try:
                px = parent.winfo_rootx() + (parent.winfo_width()  - self.winfo_width())  // 2
                py = parent.winfo_rooty() + (parent.winfo_height() - self.winfo_height()) // 3
                self.geometry(f"+{max(0, px)}+{max(0, py)}")
            except Exception:
                pass
        self.focus_force()

    def _pick(self, action: str):
        self.action = action
        self.destroy()


class _DeleteErrorDlg(tk.Toplevel):
    """"That file could not be deleted" — what should happen?

    Shown once per failure (locked by another program, permission denied,
    still-open handle, …).  "Do the same for every other file that fails"
    lets one answer cover the rest of the batch instead of clicking through
    an OK box for every single one.
    """

    RETRY = "retry"
    SKIP  = "skip"
    ABORT = "abort"

    def __init__(self, parent, path: str, reason: str):
        super().__init__(parent)
        self.action  = self.SKIP
        self.all_var = tk.BooleanVar(value=False)
        _setup_toplevel(self, "Could not delete", parent, modal=True)
        try:
            self.lift()
        except Exception:
            pass
        self.resizable(True, False)
        self.protocol("WM_DELETE_WINDOW", lambda: self._pick(self.SKIP))

        tk.Label(self, text="⚠  Could not delete this file",
                 font=("Segoe UI", 11, "bold")).pack(padx=16, pady=(16, 2))
        tk.Label(self, text=os.path.basename(path), fg=C_ACCENT,
                 font=("Segoe UI", 10)).pack(padx=16)
        tk.Label(self, text=os.path.dirname(path),
                 fg="#666666", font=("Segoe UI", 8), justify="center"
                 ).pack(padx=16, pady=(2, 6))
        tk.Label(self, text=f"Windows says: {reason}.",
                 font=("Segoe UI", 9), wraplength=380, justify="left"
                 ).pack(padx=16, pady=(0, 10))

        ttk.Checkbutton(self, text="Do the same for every other file that "
                                   "fails in this batch",
                        variable=self.all_var).pack(padx=16, anchor="w")

        btns = ttk.Frame(self)
        btns.pack(padx=16, pady=(10, 14))
        for col, (val, label, width) in enumerate((
                (self.RETRY, "Try again", 12),
                (self.SKIP,  "Skip this file", 16),
                (self.ABORT, "✖  Abort the rest", 18))):
            ttk.Button(btns, text=label, width=width,
                       command=lambda v=val: self._pick(v)
                       ).grid(row=0, column=col, padx=4)

        self.update_idletasks()
        if parent:
            try:
                px = parent.winfo_rootx() + (parent.winfo_width()  - self.winfo_width())  // 2
                py = parent.winfo_rooty() + (parent.winfo_height() - self.winfo_height()) // 3
                self.geometry(f"+{max(0, px)}+{max(0, py)}")
            except Exception:
                pass
        self.focus_force()

    def _pick(self, action: str):
        self.action = action
        self.destroy()


class _ConflictDlg(tk.Toplevel):
    """Per-file conflict dialog, shown when conflict_mode == 'ask'."""

    # action constants
    OVERWRITE       = "overwrite"
    OVERWRITE_ALL   = "overwrite_all"
    SKIP            = "skip"
    SKIP_ALL        = "skip_all"
    AUTO_RENAME     = "auto_rename"        # rename the NEW incoming file
    AUTO_RENAME_ALL = "auto_rename_all"
    BACKUP_OLD      = "backup_old"         # keep the OLD file under a Backup<code>- name
    BACKUP_OLD_ALL  = "backup_old_all"
    CANCEL          = "cancel"

    def __init__(self, parent, src: str, dst: str, modal: bool = True):
        super().__init__(parent)
        self.action = self.CANCEL
        _setup_toplevel(self, "File already exists", parent, modal=modal)
        # This dialog BLOCKS the transfer until it is answered, so it must never
        # end up behind anything — least of all the pinned Task Queue, which
        # would look like the program had frozen.  (_setup_toplevel already
        # un-pinned it; this puts the dialog itself on top of the stack.)
        try:
            self.lift()
        except Exception:
            pass
        self.resizable(True, False)
        # Close with X = cancel (action stays CANCEL, window destroyed)
        self.protocol("WM_DELETE_WINDOW", lambda: self._pick(self.CANCEL))
        # ESC = SKIP, not cancel.  _setup_toplevel binds Escape to destroy(),
        # which left `action` on CANCEL and stopped the WHOLE job — so the one
        # key you reach for to wave a single file away killed the other 200.
        # Escape now means exactly what the Skip button means (and obeys the
        # "apply to all" tick the same way), while X and the Cancel button
        # still stop everything.
        self.bind("<Escape>", lambda e: self._pick(self.SKIP))

        ttk.Label(self, text="A file with the same name already exists.",
                  font=("", 0, "bold")).pack(padx=14, pady=(14, 4))

        # ── File comparison table ──────────────────────────────────────────
        frm = ttk.Frame(self)
        frm.pack(fill="x", padx=14, pady=4)
        frm.columnconfigure(1, weight=1)
        frm.columnconfigure(2, weight=1)

        # Header row
        ttk.Label(frm, text="",         width=12, anchor="e").grid(row=0, column=0)
        ttk.Label(frm, text="Source",   anchor="center", font=("", 0, "bold")).grid(
            row=0, column=1, sticky="ew", padx=4)
        ttk.Label(frm, text="Destination", anchor="center", font=("", 0, "bold")).grid(
            row=0, column=2, sticky="ew", padx=4)

        def _file_info(path):
            """Return (name, size_bytes, size_str, mtime_str, raw mtime)."""
            try:
                st = os.stat(path)
                return (
                    os.path.basename(path),
                    st.st_size,
                    _fmt_size(st.st_size),
                    datetime.fromtimestamp(st.st_mtime).strftime("%Y-%m-%d  %H:%M"),
                    st.st_mtime,
                )
            except Exception:
                return (os.path.basename(path), -1, "?", "?", 0.0)

        src_name, src_sz, src_sz_str, src_mtime, src_mt = _file_info(src)
        dst_name, dst_sz, dst_sz_str, dst_mtime, dst_mt = _file_info(dst)

        same_size = (src_sz >= 0 and dst_sz >= 0 and src_sz == dst_sz)
        # Same size but a different moment is its own case: green would claim
        # they are the same file, and they probably ARE — one copy simply got
        # written a moment later.  Blue says that without claiming either one
        # is the newer version.
        restamped = same_size and not _same_moment(src_mt, dst_mt)

        # Name row
        ttk.Label(frm, text="Name:", anchor="e", width=12).grid(
            row=1, column=0, sticky="e", padx=(0, 6), pady=2)
        ttk.Label(frm, text=src_name, foreground=C_ACCENT, anchor="w").grid(
            row=1, column=1, sticky="w", padx=4, pady=2)
        ttk.Label(frm, text=dst_name, foreground=C_ACCENT, anchor="w").grid(
            row=1, column=2, sticky="w", padx=4, pady=2)

        # Size row — highlight if sizes differ
        if not same_size:
            sz_fg, sz_note = C_CMP_BIGGER, "  ≠ different"
        elif restamped:
            sz_fg, sz_note = C_CMP_RESTAMP, "  = same size, different moment"
        else:
            sz_fg, sz_note = C_CMP_EQUAL, "  ✓ equal"
        ttk.Label(frm, text="Size:", anchor="e", width=12).grid(
            row=2, column=0, sticky="e", padx=(0, 6), pady=2)
        ttk.Label(frm, text=src_sz_str, foreground=sz_fg, anchor="w").grid(
            row=2, column=1, sticky="w", padx=4, pady=2)
        sz_dst_lbl = tk.Label(frm, text=dst_sz_str + sz_note,
                              fg=sz_fg, bg=self["bg"], anchor="w")
        sz_dst_lbl.grid(row=2, column=2, sticky="w", padx=4, pady=2)

        # Modified row
        ttk.Label(frm, text="Modified:", anchor="e", width=12).grid(
            row=3, column=0, sticky="e", padx=(0, 6), pady=2)
        ttk.Label(frm, text=src_mtime, foreground=C_FG_DIM, anchor="w").grid(
            row=3, column=1, sticky="w", padx=4, pady=2)
        ttk.Label(frm, text=dst_mtime, foreground=C_FG_DIM, anchor="w").grid(
            row=3, column=2, sticky="w", padx=4, pady=2)

        ttk.Separator(self, orient="horizontal").pack(fill="x", padx=14, pady=8)

        # ── "Apply to all" checkbox ────────────────────────────────────────
        # When ticked, whichever button you press applies to every remaining
        # conflict in this operation, not just this one file.  ("Rename new"
        # used to be the exception — it had no all-variant, so ticking the box
        # and picking it asked again on the very next file.)
        self._all_var = tk.BooleanVar(value=False)
        chk = ttk.Checkbutton(
            self, text="Apply to all remaining conflicts",
            variable=self._all_var)
        chk.pack(anchor="w", padx=16, pady=(0, 0))
        ttk.Label(self,
                  text="(Shift+Enter ticks this  ·  Esc = Skip  ·  "
                       "Enter = the highlighted button)",
                  foreground=C_FG_DIM, font=("Segoe UI", 8)
                  ).pack(anchor="w", padx=16, pady=(0, 4))

        # ── Buttons ───────────────────────────────────────────────────────
        btn_frm = ttk.Frame(self)
        btn_frm.pack(padx=14, pady=(0, 14))
        # (base action, label, tooltip)
        actions = [
            (self.OVERWRITE,   "Overwrite",            "Replace the existing file with the new one"),
            (self.BACKUP_OLD,  "Backup-rename old",    "Keep the old file, renamed Backup<code>-… ; the new file takes the name"),
            (self.AUTO_RENAME, "Rename new",           "Keep both — the new file gets a  (2)  suffix"),
            (self.SKIP,        "Skip",                 "Leave the existing file, do not copy this one"),
            (self.CANCEL,      "Cancel",               "Stop the whole operation"),
        ]
        # Buttons are kept in a list (same order as `actions`) so LEFT/RIGHT
        # can step through them and so we know which one is the keyboard
        # default ("Backup-rename old" — ENTER alone confirms it, no mouse
        # needed).  A bold face marks whichever button currently has
        # keyboard focus, since the plain ttk focus ring is easy to miss.
        style = ttk.Style(self)
        style.configure("ConflictDefault.TButton", font=("Segoe UI", 9, "bold"))

        self._btn_order  = []   # [(val, button), ...] in reading order
        self._default_idx = 0
        for idx, (val, label, tip) in enumerate(actions):
            r, c = divmod(idx, 2)
            b = ttk.Button(btn_frm, text=label, width=18,
                           command=lambda v=val: self._pick(v))
            b.grid(row=r, column=c, padx=5, pady=3)
            b.bind("<FocusIn>",
                   lambda e, bt=b: bt.configure(style="ConflictDefault.TButton"))
            b.bind("<FocusOut>", lambda e, bt=b: bt.configure(style="TButton"))
            self._btn_order.append((val, b))
            if val == self.BACKUP_OLD:
                self._default_idx = idx

        def _step(direction):
            def handler(event=None):
                widgets = [w for _, w in self._btn_order]
                cur = self.focus_get()
                i = widgets.index(cur) if cur in widgets else self._default_idx
                widgets[(i + direction) % len(widgets)].focus_set()
                return "break"
            return handler

        def _confirm(also_all):
            def handler(event=None):
                widgets = [w for _, w in self._btn_order]
                cur = self.focus_get()
                i = widgets.index(cur) if cur in widgets else self._default_idx
                if also_all:
                    self._all_var.set(True)
                self._btn_order[i][1].invoke()
                return "break"
            return handler

        self.bind("<Left>",         _step(-1))
        self.bind("<Right>",        _step(+1))
        self.bind("<Shift-Return>", _confirm(True))
        self.bind("<Return>",       _confirm(False))
        self.bind("<KP_Enter>",     _confirm(False))

        # ── Center over parent and ensure visible ──────────────────────────
        self.update_idletasks()
        if parent:
            try:
                pw = parent.winfo_rootx()
                py_ = parent.winfo_rooty()
                px_c = pw + (parent.winfo_width()  - self.winfo_width())  // 2
                py_c = py_ + (parent.winfo_height() - self.winfo_height()) // 2
                self.geometry(f"+{max(0, px_c)}+{max(0, py_c)}")
            except Exception:
                pass
        self.lift()
        self.focus_force()
        # Keyboard-first: land on "Backup-rename old" so a bare ENTER
        # confirms it without ever touching the mouse.
        self._btn_order[self._default_idx][1].focus_set()

    def _pick(self, action):
        # The "Apply to all" checkbox upgrades the one-file actions to their
        # all-conflicts variants.  Rename-new is already applied per file as a
        # mode; Cancel stops everything regardless.
        if getattr(self, "_all_var", None) is not None and self._all_var.get():
            action = {
                self.OVERWRITE:   self.OVERWRITE_ALL,
                self.SKIP:        self.SKIP_ALL,
                self.BACKUP_OLD:  self.BACKUP_OLD_ALL,
                self.AUTO_RENAME: self.AUTO_RENAME_ALL,
            }.get(action, action)
        self.action = action
        self.destroy()




class _SuffixTwinDlg(tk.Toplevel):
    """A "Foo (3).py" arriving where a "Foo.py" already lives.

    Not a name clash — the two names differ — so nothing would normally stop
    to ask, and the folder slowly fills up with (2), (3), (4) of the same
    program.  This is the copy of "Backup-rename old" for that case: keep the
    old file under a Backup<code>- name and let the new one take the PLAIN
    name.  Non-modal by design: it answers through *on_done* instead of
    blocking, because it is opened from a queue callback.
    """

    BACKUP = "backup_old"      # keep the old one renamed, new file takes the name
    OVER   = "overwrite"       # replace the old one, new file takes the name
    KEEP   = "keep"            # leave the (3) in the name — what used to happen

    def __init__(self, parent, twins: list, src_dir: str, dst_dir: str,
                 move: bool, on_done=None):
        super().__init__(parent)
        self._on_done = on_done
        self._answered = False
        _setup_toplevel(self, "Same file, one “(2)” apart", parent, modal=False)
        self.resizable(True, False)
        self.protocol("WM_DELETE_WINDOW", lambda: self._pick(self.KEEP))

        n = len(twins)
        head = (f"{n} file{'s' if n != 1 else ''} differ from a file already "
                f"there only by a “(2)” suffix.")
        ttk.Label(self, text=head, font=("", 0, "bold"),
                  wraplength=560, justify="left").pack(
                      padx=14, pady=(14, 2), anchor="w")
        ttk.Label(self,
                  text="Treat them as the SAME file and let the new one take "
                       "the plain name?",
                  foreground=C_FG_DIM, wraplength=560, justify="left").pack(
                      padx=14, pady=(0, 8), anchor="w")

        box = tk.Listbox(self, height=min(8, max(2, n)), activestyle="none",
                         bg=C_BG2, fg=C_FG, highlightthickness=0,
                         selectbackground=C_BG3, selectforeground=C_FG,
                         font=("Consolas", 9))
        for t in twins[:200]:
            box.insert("end",
                       f"  {os.path.basename(t['src'])}   →   {t['base']}")
        if n > 200:
            box.insert("end", f"  … and {n - 200} more")
        box.pack(fill="x", padx=14, pady=(0, 8))

        ttk.Separator(self, orient="horizontal").pack(fill="x", padx=14, pady=4)

        self._always = tk.BooleanVar(value=False)
        ttk.Checkbutton(
            self, variable=self._always,
            text="Always do this, from this folder to that one").pack(
                anchor="w", padx=16)
        ttk.Label(self, text=f"from   {src_dir or '(any)'}\n"
                             f"to        {dst_dir or '(any)'}",
                  foreground=C_FG_DIM, font=("Segoe UI", 8),
                  justify="left").pack(anchor="w", padx=34, pady=(0, 6))

        btns = ttk.Frame(self)
        btns.pack(padx=14, pady=(0, 14))
        verb = "moved" if move else "copied"
        actions = [
            (self.BACKUP, "Backup old, drop the (2)",
             f"The old file is kept as Backup<code>-… ; the {verb} file takes "
             f"its plain name"),
            (self.OVER,   "Replace old, drop the (2)",
             "The old file is deleted and the new one takes its plain name"),
            (self.KEEP,   "Keep the (2) name",
             "Leave both files exactly as they are named now"),
        ]
        style = ttk.Style(self)
        style.configure("TwinDefault.TButton", font=("Segoe UI", 9, "bold"))
        self._btns = []
        for i, (val, label, tip) in enumerate(actions):
            b = ttk.Button(btns, text=label, width=26,
                           command=lambda v=val: self._pick(v))
            b.grid(row=0, column=i, padx=4)
            b.bind("<FocusIn>",
                   lambda e, bt=b: bt.configure(style="TwinDefault.TButton"))
            b.bind("<FocusOut>", lambda e, bt=b: bt.configure(style="TButton"))
            self._btns.append(b)

        def _step(direction):
            def handler(_e=None):
                cur = self.focus_get()
                i = self._btns.index(cur) if cur in self._btns else 0
                self._btns[(i + direction) % len(self._btns)].focus_set()
                return "break"
            return handler

        def _confirm(_e=None):
            cur = self.focus_get()
            i = self._btns.index(cur) if cur in self._btns else 0
            self._btns[i].invoke()
            return "break"

        self.bind("<Left>",   _step(-1))
        self.bind("<Right>",  _step(+1))
        self.bind("<Return>", _confirm)
        self.bind("<KP_Enter>", _confirm)
        self.bind("<Escape>", lambda e: self._pick(self.KEEP))

        self.update_idletasks()
        try:
            px = parent.winfo_rootx() + (parent.winfo_width() - self.winfo_width()) // 2
            py = parent.winfo_rooty() + (parent.winfo_height() - self.winfo_height()) // 3
            self.geometry(f"+{max(0, px)}+{max(0, py)}")
        except Exception:
            pass
        self.lift()
        self.focus_force()
        self._btns[0].focus_set()

    def _pick(self, choice: str):
        if self._answered:
            return
        self._answered = True
        always = bool(self._always.get())
        cb = self._on_done
        try:
            self.destroy()
        except Exception:
            pass
        if cb:
            cb(choice, always)


class _QueueProgressProxy:
    """Drop-in replacement for _ProgressDialog when running inside the task queue.

    Instead of creating a blocking Toplevel window, it routes progress updates to
    the TaskQueueManager so the QueueWindow can display them inline.

    Conflict and error dialogs are shown as non-blocking Toplevels (no grab_set)
    so the user can continue working with other panels while choosing.

    Thread-safe: background threads call .post(*msg); the main thread polls via
    an after() callback, exactly like _ProgressDialog.
    """

    def __init__(self, mgr: "TaskQueueManager", editor: tk.Widget, task=None):
        self._mgr    = mgr
        self._editor = editor
        self._task   = task
        self._q: "queue.Queue" = queue.Queue()
        self._done   = False
        self._poll_id = editor.after(80, self._poll)

    # Public attribute checked by worker threads
    @property
    def cancelled(self) -> bool:
        """Cancel is PER TASK.

        With the fast lane there can be two jobs in flight, so the queue-wide
        ✖ button (_cancel_current) must only stop the big one — otherwise
        cancelling a 9 GB copy would also kill the little file that happened to
        be slipping past it."""
        t = self._task
        if t is not None:
            if getattr(t, "cancel_requested", False):
                return True
            if getattr(t, "fast", False) or getattr(t, "reloc", False):
                return False        # the queue-wide ✖ is not aimed at this one
        return self._mgr._cancel_current

    def post(self, *msg):
        """Enqueue a message from any thread."""
        self._q.put(msg)

    # ── Internal ──────────────────────────────────────────────────────────

    def _poll(self):
        """Drain the queue and update QueueWindow progress. Runs in main thread."""
        # Progress messages pile up faster than 80 ms can show them (an archive
        # of 50 000 small files posts one per file) and every one of them used
        # to repaint the whole queue window.  Only the NEWEST of a run of them
        # is worth drawing, so it is held back and drawn once.
        held = None

        def _draw_held():
            nonlocal held
            if held is not None:
                m, held = held, None
                unit = m[4] if len(m) > 4 else "files"
                self._mgr._proxy_progress(m[1], m[2], m[3], unit, self._task)

        try:
            for _ in range(5000):
                msg  = self._q.get_nowait()
                kind = msg[0]

                if kind == "progress":
                    # A 5th field says what the numbers COUNT.  Older posters
                    # (pack, unpack, FTP) send four and mean files.
                    held = msg
                    continue

                # Anything else must see the numbers as they stood.
                if kind == "done":
                    held = None
                else:
                    _draw_held()

                if kind == "conflict":
                    _, src, dst, result_list, evt = msg
                    # Modal conflict dialog — user must respond before the
                    # operation can continue.  The grab is released the moment
                    # they click a button, so the rest of the UI unlocks.
                    dlg = _ConflictDlg(self._editor, src, dst, modal=True)
                    self._editor.wait_window(dlg)
                    result_list[0] = dlg.action
                    evt.set()

                elif kind == "locked":
                    # A file another program is holding open.  Ask once (the
                    # worker waits on the event); the answer can be applied to
                    # every other locked file in the same job.
                    _, path, reason, dest, result_list, evt = msg
                    dlg = _LockedDlg(self._editor, path, reason, dest)
                    self._editor.wait_window(dlg)
                    result_list[0] = dlg.action
                    result_list[1] = bool(dlg.all_var.get())
                    evt.set()

                elif kind == "error":
                    _, err_msg, cont_list, evt = msg
                    ans = _ask_yes_no(
                        "Error",
                        err_msg + "\n\nContinue with remaining files?",
                        parent=self._editor,
                    )
                    cont_list[0] = ans
                    evt.set()

                elif kind == "done":
                    self._done = True
                    self._mgr._proxy_progress(0, 0, "", "files", self._task)
                    return

        except queue.Empty:
            pass

        _draw_held()                  # the newest progress of this round

        if not self._done:
            self._poll_id = self._editor.after(80, self._poll)

class TaskType(enum.Enum):
    COPY   = "copy"
    MOVE   = "move"
    PACK   = "pack"
    UNPACK = "unpack"

class TaskStatus(enum.Enum):
    PENDING   = "pending"
    RUNNING   = "running"
    DONE      = "done"
    CANCELLED = "cancelled"
    ERROR     = "error"

_TASK_ICONS = {
    TaskType.COPY:   "📋 Copy",
    TaskType.MOVE:   "🚚 Move",
    TaskType.PACK:   "📦 Pack",
    TaskType.UNPACK: "📂 Unpack",
}
_STATUS_ICONS = {
    TaskStatus.PENDING:   "⏳ Pending",
    TaskStatus.RUNNING:   "▶ Running",
    TaskStatus.DONE:      "✓ Done",
    TaskStatus.CANCELLED: "✖ Cancelled",
    TaskStatus.ERROR:     "⚠ Error",
}


@dataclasses.dataclass
class QueueTask:
    task_id:       int
    task_type:     TaskType
    description:   str
    sources:       list
    dest_dir:      str
    conflict_mode: str           = "ask"
    zip_name:      str           = ""
    size_bytes:    int           = 0
    status:        TaskStatus    = dataclasses.field(default_factory=lambda: TaskStatus.PENDING)
    locked:        bool          = False
    error_msg:     str           = ""
    space_warning: str           = ""   # set by smart_sort when disk space is tight
    added_at:      float         = dataclasses.field(default_factory=_time.time)   # wall-clock queued time
    finished_at:   float         = 0.0  # wall-clock time the task left RUNNING
    # FAST LANE: a job small enough (or instant enough) that it should not have
    # to wait behind a multi-gigabyte transfer.  Set at enqueue time; such tasks
    # are run by their own worker, in parallel with the big one.
    fast:          bool          = False
    # BUS LANE: the hand-picked version of the fast lane.  🚌 "Do it now"
    # sets this, and it overrules the size rule entirely — THIS job is the one
    # being waited for, so it runs beside the big transfer instead of after it.
    bus:           bool          = False
    # MAIN LANE ONLY (revision CL): the user took this job OUT of the fast/bus
    # lane by hand.  The size rule must not put it back in.
    main_only:     bool          = False
    cancel_requested: bool       = False   # per-task cancel (the fast lane's ✖)
    # RELOCATOR LANE (revision BZ): the Relocator's jobs run in a lane of their
    # OWN, never behind the big transfer and never in the bus/fast queue.  A
    # rule is a seconds-job; waiting minutes for a 30 GB copy to end made the
    # whole ⤴ feature feel broken.
    reloc:         bool          = False
    # Per-file problems, so one locked file reports itself instead of taking
    # the whole job down: [(path, plain-language reason)]
    failures:      list          = dataclasses.field(default_factory=list)
    # Locked originals that were copied and are queued for deletion (DEL 49)
    deferred:      list          = dataclasses.field(default_factory=list)
    # ── PREFLIGHT (DEL 04b) ──────────────────────────────────────────────
    # Adding up the source size and asking the destination "is this name
    # taken?" is one round trip PER FILE.  Locally that is nothing; to a
    # network drive it is seconds to minutes — and it used to run on the main
    # thread, which is exactly why the program froze while a copy to the
    # network drive was being queued.  It now runs in a worker thread and the
    # task sits in the queue marked "Checking…" until it is in.
    preflight:     str           = "done"     # "scanning" while being measured
    requested_mode: str          = "ask"      # clash policy asked for at queue time
    pending_conflicts: list      = dataclasses.field(default_factory=list)
    # Destination NAME override per source path (normcase'd abs path → name).
    # Used by "drop the (2) suffix" and by the Relocator.
    rename_map:    dict          = dataclasses.field(default_factory=dict)
    # Sources whose name differs from a file already at the destination only
    # by a " (2)" suffix — asked about once, when the scan comes back.
    twins:         list          = dataclasses.field(default_factory=list)
    # ── UNPACK (DEL 20b) ─────────────────────────────────────────────────
    # Every file of a split set, so the size is honest and "delete after
    # unpacking" can take the whole set rather than leaving 42 orphans.
    parts:         list          = dataclasses.field(default_factory=list)
    # A job that cannot run YET because a part of the archive is still being
    # downloaded.  It stays PENDING and is simply not runnable until
    # wait_until; wait_tries counts the attempts so it can give up.
    wait_reason:   str           = ""
    wait_until:    float         = 0.0
    wait_tries:    int           = 0
    # revCJ: "Unpack anyway" - skip the completeness check (.sfv / missing or
    # still-arriving parts) for this one job.  Not saved; a restored job asks
    # the check again.
    force_unpack:  bool          = False
    # ── CARRIED OVER FROM THE LAST SESSION (revision BB) ──────────────
    restored:        bool        = False   # came back from task_queue.json
    was_interrupted: bool        = False   # ...and it was the one mid-transfer
    # ── PICKING UP WHERE IT STOPPED (revision BN) ─────────────────────
    # A job that is being RESUMED — carried over, loaded from a saved queue,
    # or put back by ↺ Resume — has already written some of its files.  This
    # makes it skip, in silence, every destination file that is already there
    # and identical (same size, same date).  Without it a resumed 33 GB copy
    # asks one clash question per file already copied, four thousand times,
    # which is not a resume by any reading of the word.
    resume_skip:     bool        = False

    def touch_paths(self) -> set:
        """Every path this job reads or writes — what it must not share with a
        job that is allowed to overtake it.

        Sources AND the files they become at the destination: a COPY of X into
        2 and a MOVE of the same X into 3 both hold X, and if the move goes
        first the copy has nothing left to copy.  The result is cached: the
        sources of a task never change once it is queued, and this is asked
        for on every pass of the scheduler.
        """
        cached = getattr(self, "_touch_cache", None)
        if cached is not None:
            return cached
        out = set()
        dest = self.dest_dir or ""
        for s in (self.sources or []):
            try:
                out.add(os.path.normcase(os.path.abspath(s)))
                if dest:
                    name = self.rename_map.get(
                        os.path.normcase(os.path.abspath(s)),
                        os.path.basename(s.rstrip("\\/")))
                    out.add(os.path.normcase(
                        os.path.abspath(os.path.join(dest, name))))
            except Exception:
                continue
        for p in (self.parts or []):          # a split set holds every piece
            try:
                out.add(os.path.normcase(os.path.abspath(p)))
            except Exception:
                continue
        self._touch_cache = out
        return out

    def is_instant(self) -> bool:
        """A same-drive move is a rename — no bytes travel, so it finishes in
        milliseconds no matter how many gigabytes the file holds."""
        if self.task_type != TaskType.MOVE or not self.sources or not self.dest_dir:
            return False
        cached = getattr(self, "_instant_cache", None)
        if cached is not None:
            return cached
        dst_drv = os.path.splitdrive(self.dest_dir)[0].upper()
        ok = all(os.path.splitdrive(s)[0].upper() == dst_drv
                 for s in self.sources)
        # REVISION CL — "1 GB-katalog tar upp bus lane-platsen": a FOLDER is
        # not a rename here.  The worker moves a folder file by file (exists
        # check, rename, log entry, progress post for each), so a folder full
        # of small files takes as long as it takes — and calling it "instant"
        # put it in the one-worker fast lane, where it blocked every tiny file
        # behind it.  Only plain FILES are instant; a folder is judged by its
        # size like any other job.  (Cached: this is asked on every re-sort.)
        if ok:
            try:
                ok = not any(os.path.isdir(s) for s in self.sources)
            except Exception:
                ok = False
        self._instant_cache = ok
        return ok

    def auto_priority(self) -> float:
        """Lower value = execute sooner.  SHORTEST JOB FIRST.

        Asked for in as many words (revBT): "Det ska vara automatiskt att göra
        sig av med mängden överföringar… minska dem, så fort som möjligt (i.f.a.
        det blir krasch så blir det mindre rörigt)."  So this is not "which TYPE
        is cheapest" any more — that sorted a 4 GB unpack in front of a 73 KB
        copy, because the type decided the band and the size only broke ties
        inside it.  It is an estimate of how LONG the job will take, and the
        shortest one goes first.  The type survives only as the per-byte weight
        that goes into that estimate.
        """
        if self.status != TaskStatus.PENDING:
            return 9999.0

        gb = max(0, self.size_bytes) / 1e9

        if self.is_instant():
            # A same-drive move is a rename: no bytes travel, however many
            # gigabytes the file holds.  It takes a row off the list at once,
            # so it goes before anything that has to move data — and the size
            # term is only there to keep two of them in a sensible order.
            cost = gb * 1e-6
        else:
            # Per-byte weight: packing has to compress every byte, unpacking
            # has to write them all out again, a cross-drive move is a copy
            # plus a delete.  A plain copy is the unit.
            weight = {TaskType.PACK:   2.0,
                      TaskType.UNPACK: 1.5,
                      TaskType.MOVE:   1.2}.get(self.task_type, 1.0)
            # The 1.0 floor is what keeps every real transfer behind an instant
            # move, and stops a job of a few empty folders looking free.
            cost = 1.0 + gb * weight

        # 🚌 Do it now — hand-picked work goes before anything the heuristic
        # would choose.  But INSIDE the lane it is still shortest-first: this
        # used to be a flat 0.0 for every bus job, so they tied, the stable
        # sort left them in the order they were queued in, and a 35 GB one
        # that happened to be queued first blocked three 73 KB ones behind it.
        # (-1e9 is simply below every real cost; a job would have to be an
        # exabyte to climb out of the lane.)
        if getattr(self, "bus", False):
            return -1e9 + cost

        # Unresolved conflicts → always last
        if self.conflict_mode == "pending_conflicts":
            return 9000.0 + cost
        # Waiting for a part that has not arrived → out of the way of work
        # that can actually run now.
        if self.wait_until > _time.time():
            return 8000.0 + cost
        return cost

# ── Who may overtake whom ─────────────────────────────────────────────────────
#
# The queue reorders itself so quick jobs go first — a same-drive move is a
# rename and costs nothing, a 9 GB copy costs minutes.  That is right until the
# two jobs are about the SAME FILE:
#
#     queue  COPY  film.mkv  1 → 2      (waits, something big is running)
#     queue  MOVE  film.mkv  1 → 3      (instant, jumps the queue)
#
# The move goes first, film.mkv is no longer in 1, and the copy that was queued
# FIRST now has nothing to copy.  So: a job may never overtake an EARLIER job
# that holds one of the same paths.  Same file = first come, first served, no
# matter how cheap the later one looks.

def _paths_clash(a: set, b: set) -> bool:
    """True if two jobs touch the same file — or a folder holding the other.

    The folder test matters: "copy C:\\dist" and "move C:\\dist\\app.exe" are
    the same fight even though neither path equals the other."""
    if not a or not b:
        return False
    if a & b:
        return True
    # The folder test is a double loop, so it is only worth doing while the
    # two jobs are small.  A 900-file job that shares no path with another is
    # not going to be a parent of it either — it is a list of files.
    if len(a) * len(b) > 4096:
        return False
    for pa in a:
        for pb in b:
            if pa.startswith(pb + os.sep) or pb.startswith(pa + os.sep):
                return True
    return False


def _read_write_paths(t):
    """(paths the job only READS, paths it CHANGES) for a copy or move; None for
    any other kind of job (pack/unpack keep the strict rule).

    COPY reads its sources and writes the files they become at the destination.
    MOVE also changes its sources — it takes them away.  Cached on the task."""
    cached = getattr(t, "_rw_cache", None)
    if cached is not None:
        return cached or None
    if t.task_type not in (TaskType.COPY, TaskType.MOVE):
        t._rw_cache = ()
        return None
    reads, writes = set(), set()
    dest = t.dest_dir or ""
    for s in (t.sources or []):
        try:
            key = os.path.normcase(os.path.abspath(s))
            reads.add(key)
            if t.task_type == TaskType.MOVE:
                writes.add(key)
            if dest:
                name = t.rename_map.get(key, os.path.basename(s.rstrip("\\/")))
                writes.add(os.path.normcase(
                    os.path.abspath(os.path.join(dest, name))))
        except Exception:
            continue
    t._rw_cache = (reads, writes)
    return t._rw_cache


def _tasks_clash(t1, t2) -> bool:
    """Do two jobs fight over a file?

    REVISION CL — "KvarnPC.py (212 kb) is 'after #10' because the 381 MB folder
    Kvarn is being copied": two COPIES that only READ the same source do not
    fight, so the small one must not wait for the big one.  A clash needs at
    least one of them to CHANGE the path the other uses: a write meeting a
    write, a write meeting a read (either way round), or a MOVE (which removes
    its source) meeting anything that uses that source."""
    rw1, rw2 = _read_write_paths(t1), _read_write_paths(t2)
    if rw1 is None or rw2 is None:
        return _paths_clash(t1.touch_paths(), t2.touch_paths())
    r1, w1 = rw1
    r2, w2 = rw2
    return (_paths_clash(w1, w2) or _paths_clash(w1, r2)
            or _paths_clash(r1, w2))


def _held_map(tasks: list) -> dict:
    """{job → the earlier job holding one of its files}, from a SNAPSHOT.

    Worked out without the queue's lock on purpose: this is for drawing the
    list, which happens four times a second while a copy runs, and the lock is
    held by the worker threads that are doing the actual work."""
    active = sorted((t for t in tasks
                     if t.status in (TaskStatus.PENDING, TaskStatus.RUNNING)),
                    key=lambda t: t.task_id)
    if len(active) > 200:
        return {}                       # too many to draw this for; the
                                        # scheduler still keeps the order
    out = {}
    for i, t in enumerate(active):
        if t.status != TaskStatus.PENDING:
            continue
        for o in active[:i]:
            if _tasks_clash(o, t):
                out[t.task_id] = o.task_id
                break
    return out


# ── Preflight helpers ─────────────────────────────────────────────────────────

def _scan_conflicts(sources: list, dest_dir: str) -> list:
    """Return a list of conflict dicts for every source file that already
    exists at the destination."""
    conflicts = []
    for src_root in sources:
        if os.path.isfile(src_root):
            dst = os.path.join(dest_dir, os.path.basename(src_root))
            if os.path.exists(dst):
                conflicts.append(_conflict_entry(src_root, dst))
        elif os.path.isdir(src_root):
            dst_root = os.path.join(dest_dir, os.path.basename(src_root))
            for dirpath, _, fnames in os.walk(src_root):
                rel = os.path.relpath(dirpath, src_root)
                for fname in fnames:
                    fsrc = os.path.join(dirpath, fname)
                    fdst = (os.path.join(dst_root, rel, fname) if rel != "."
                            else os.path.join(dst_root, fname))
                    if os.path.exists(fdst):
                        conflicts.append(_conflict_entry(fsrc, fdst))
    return conflicts


# Two timestamps closer together than this are "the same moment".  FAT keeps
# 2-second resolution and a copy across filesystems routinely lands a second
# out, so a stricter test would call half a folder "changed".  DEL 48 uses the
# same number (EditorFrame.CMP_TOLERANCE_S), on purpose: the whole program
# should agree about what "the same moment" means.
SAME_MOMENT_S = 2.0

# What the colours mean wherever two copies of a file are compared.  Green is
# reserved for "these really are the same file"; a matching size with a
# different timestamp gets its own blue, because that is what a file copied
# into two folders looks like and it must not read as "one is newer".
C_CMP_BIGGER  = "#e8c84a"      # the incoming copy is larger
C_CMP_SMALLER = "#e8a24a"      # the incoming copy is smaller
C_CMP_EQUAL   = "#55aa55"      # same size, same moment → the same file
C_CMP_RESTAMP = "#6fa8ff"      # same size, different moment → probably a copy
# The ⚖ toolbar button (DEL 48).  Red = off, no colour = comparing, blue = also
# flagging the files that only exist on one side.
C_CMP_BTN_OFF     = "#c1121f"
C_CMP_BTN_SINGLES = "#1a5fb4"


def _same_moment(a: float, b: float) -> bool:
    try:
        return abs(float(a) - float(b)) <= SAME_MOMENT_S
    except Exception:
        return False


def _conflict_entry(src: str, dst: str) -> dict:
    def _stat(p):
        try:
            st = os.stat(p)
            return (st.st_size,
                    datetime.fromtimestamp(st.st_mtime).strftime("%Y-%m-%d %H:%M"),
                    st.st_mtime)
        except Exception:
            return -1, "?", 0.0
    ss, sm, sr = _stat(src)
    ds, dm, dr = _stat(dst)
    # src_mt / dst_mt are the RAW times.  The displayed ones are cut off at the
    # minute, so two files three seconds apart look identical in the list —
    # which is exactly the case the colour has to be able to tell apart.
    return {"src": src, "dst": dst,
            "src_size": ss, "dst_size": ds,
            "src_mtime": sm, "dst_mtime": dm,
            "src_mt": sr, "dst_mt": dr}


def _disk_free(path: str) -> int:
    try:
        return shutil.disk_usage(path).free
    except Exception:
        return -1


def _pending_bytes_to(dest_dir: str, tasks: list) -> int:
    try:
        dst_drv = os.path.splitdrive(os.path.abspath(dest_dir))[0].upper()
    except Exception:
        dst_drv = ""
    total = 0
    for t in tasks:
        if t.status.name != "PENDING":
            continue
        try:
            t_drv = os.path.splitdrive(os.path.abspath(t.dest_dir))[0].upper()
        except Exception:
            t_drv = ""
        if t_drv == dst_drv:
            total += t.size_bytes
    return total



class _PreflightDialog(tk.Toplevel):
    """Show conflicts + disk-space check BEFORE queuing a copy/move.

    Result attributes after wait_window():
        .choice   "overwrite_all" | "skip_all" | "auto_rename" |
                  "ask" (per-file) | "cancel"
    """
    OVERWRITE_ALL = "overwrite_all"
    SKIP_ALL      = "skip_all"
    AUTO_RENAME   = "auto_rename"
    INDIVIDUAL    = "ask"
    CANCEL        = "cancel"

    def __init__(self, parent, conflicts: list, transfer_bytes: int,
                 dest_dir: str, pending_bytes: int = 0):
        super().__init__(parent)
        self.choice = self.CANCEL
        _setup_toplevel(self, "Pre-flight check", parent, modal=True)
        self.resizable(True, True)
        self.minsize(700, 300)
        self.protocol("WM_DELETE_WINDOW", lambda: self._pick(self.CANCEL))
        # ESC = SKIP, the same as on the per-file "File already exists" dialog.
        # This is the window you meet FIRST when a copy has clashes, and
        # Escape here used to be _setup_toplevel's plain close — i.e. cancel
        # the whole job.  Bound after the button row is built, further down,
        # because whether "Skip all" is even available depends on disk space.

        # ── Disk space banner ──────────────────────────────────────────────
        # REPORTED (2026-09-18 — "jag vill skriva över 28,9 GB med 29,0 GB, men
        # det saknas 17 GB"):  this was ONE number,
        #     after = free - pending_bytes - transfer_bytes
        # which counts every byte coming IN and not one byte going OUT.  So
        # replacing a 28,9 GB file with a 29,0 GB one reported 17 GB missing on
        # a disk with 12 GB free, when the job really needs 0,1 GB.
        # The engine was never wrong: _copy_one() deletes the file in the way
        # BEFORE it starts the copy — no temp file, no copy-then-swap — so those
        # bytes are ours to spend.  Only the banner lied, loudly enough to read
        # as a refusal.
        #
        # The cost is now worked out PER MODE, because the modes do not cost
        # remotely the same thing:
        #     Overwrite ……… the old file is destroyed first, so it pays us back
        #     Skip ………………… the clashing files are never copied, so they cost 0
        #     Rename / Backup … both copies live side by side, so: full price
        # Each mode gets its own verdict, a mode that cannot fit is disabled
        # with the reason written on it, and a mode that fits is not questioned.
        self._space_reason = {}          # action value → why it is unavailable

        free   = _disk_free(dest_dir)
        budget = (free - pending_bytes) if free >= 0 else -1

        # What the clashing files weigh on each side.
        reclaim   = sum(c["dst_size"] for c in conflicts if c["dst_size"] > 0)
        clash_src = sum(c["src_size"] for c in conflicts if c["src_size"] > 0)
        # Bytes belonging to no clash at all: full price whatever is chosen,
        # because nothing is being replaced.
        nonclash  = max(0, transfer_bytes - clash_src)

        # The worst MOMENT during the job, not just the state at the end.  Each
        # file's old copy is gone before its new copy is written, so the two
        # never coexist — but a clash that GROWS still pushes the high-water
        # mark up by the difference, and one whose sizes cannot be read has to
        # be assumed to grow by its whole size.  Without this, the banner could
        # say OK and the disk could still fill up halfway through.
        grow = 0
        for c in conflicts:
            ss, ds = c["src_size"], c["dst_size"]
            if ss < 0:
                continue
            grow += (ss if ds < 0 else max(0, ss - ds))

        need_overwrite = nonclash + max(0, clash_src - reclaim)   # end state
        peak_overwrite = nonclash + grow                          # high-water
        need_keepboth  = transfer_bytes        # rename / backup / per-file
        need_skip      = nonclash

        # A mode fits when its HIGH-WATER mark fits, not merely its end state.
        fits_overwrite = budget < 0 or peak_overwrite <= budget
        fits_keepboth  = budget < 0 or need_keepboth  <= budget
        fits_skip      = budget < 0 or need_skip      <= budget

        if not fits_overwrite:
            self._space_reason[self.OVERWRITE_ALL] = (
                f"needs {_fmt_size(peak_overwrite)} at its peak; "
                f"{_fmt_size(budget)} available")
        if not fits_keepboth:
            self._space_reason[self.AUTO_RENAME] = (
                f"needs {_fmt_size(need_keepboth)} — both copies live side by "
                f"side; {_fmt_size(budget)} available")
        if not fits_skip:
            self._space_reason[self.SKIP_ALL] = (
                f"needs {_fmt_size(need_skip)} for the files that do NOT "
                f"clash; {_fmt_size(budget)} available")

        after = (budget - need_overwrite) if budget >= 0 else -1

        if free < 0:
            banner_bg, banner_fg = C_BG3, C_FG
            space_txt = f"   Transfer size:  {_fmt_size(transfer_bytes)}    (could not read free space)"
        elif not fits_overwrite:
            # Genuinely not enough: even destroying everything in the way does
            # not make room.  This is the only case that earns red.
            banner_bg, banner_fg = "#5a1a1a", "#ff8888"
            space_txt = (
                f"\u26a0  Disk space warning!\n"
                f"   Free now:  {_fmt_size(free)}     "
                f"This job:  {_fmt_size(transfer_bytes)}     "
                f"Other queued jobs to same drive:  {_fmt_size(pending_bytes)}\n"
                f"   Even overwriting everything in the way needs "
                f"{_fmt_size(peak_overwrite)} of the {_fmt_size(budget)} "
                f"available  \u2190 NOT ENOUGH"
            )
        elif not fits_keepboth:
            # THE 28,9 GB \u2192 29,0 GB CASE.  Overwriting fits with room to spare;
            # keeping both copies does not.  Say exactly that, and do not dress
            # it up as a failure \u2014 the job can go ahead as it stands.
            banner_bg, banner_fg = "#4a3a00", "#ffe066"
            space_txt = (
                f"\u26a0  Only {_fmt_size(free)} free, and this job brings "
                f"{_fmt_size(transfer_bytes)}.\n"
                f"   \u2713  Overwrite needs just {_fmt_size(need_overwrite)} "
                f"\u2014 the {_fmt_size(reclaim)} already at the destination is "
                f"deleted before the copy starts.\n"
                f"   \u2716  Keeping both copies needs "
                f"{_fmt_size(need_keepboth)}, which will not fit."
            )
        elif after < 500_000_000:
            banner_bg, banner_fg = "#4a3a00", "#ffe066"
            space_txt = (
                f"\u26a0  Low disk space after transfer.\n"
                f"   Free now:  {_fmt_size(free)}     "
                f"This job:  {_fmt_size(transfer_bytes)}     "
                f"Other queued:  {_fmt_size(pending_bytes)}\n"
                f"   Estimated free after all jobs:  {_fmt_size(after)}"
            )
        else:
            banner_bg, banner_fg = C_BG3, "#55aa55"
            space_txt = (
                f"\u2713  Disk space OK.     "
                f"Free now:  {_fmt_size(free)}     "
                f"This job:  {_fmt_size(transfer_bytes)}     "
                f"Estimated after all queued jobs:  {_fmt_size(after)}"
            )

        banner = tk.Frame(self, bg=banner_bg, padx=10, pady=7)
        banner.pack(fill="x", padx=8, pady=(10, 4))
        tk.Label(banner, text=space_txt, bg=banner_bg, fg=banner_fg,
                 font=("Segoe UI", 9), justify="left", anchor="w").pack(fill="x")

        # ── What each way out actually costs ───────────────────────────────
        # Worth showing only when there is a clash to resolve: without one every
        # mode costs the same and the banner has already said it.
        if conflicts and free >= 0:
            cost = tk.Frame(self, bg=C_BG3, padx=10, pady=5)
            cost.pack(fill="x", padx=8, pady=(0, 4))
            head = (f"Space each choice needs   (free now {_fmt_size(free)}"
                    + (f", less {_fmt_size(pending_bytes)} already queued"
                       if pending_bytes else "") + "):")
            tk.Label(cost, text=head, bg=C_BG3, fg=C_FG,
                     font=("Segoe UI", 9, "bold"), anchor="w"
                     ).grid(row=0, column=0, columnspan=3, sticky="w")
            rows = [
                ("Overwrite all",   need_overwrite, peak_overwrite, fits_overwrite),
                ("Skip all",        need_skip,      need_skip,      fits_skip),
                ("Auto-rename all", need_keepboth,  need_keepboth,  fits_keepboth),
                ("Decide per file", need_skip,      need_keepboth,  True),
            ]
            for r, (lbl, low, high, ok) in enumerate(rows, start=1):
                tk.Label(cost, text=f"   {lbl}", bg=C_BG3, fg=C_FG,
                         font=("Segoe UI", 9), anchor="w"
                         ).grid(row=r, column=0, sticky="w")
                txt = (_fmt_size(high) if low == high
                       else f"{_fmt_size(low)} – {_fmt_size(high)}")
                tk.Label(cost, text=txt, bg=C_BG3,
                         fg=("#55aa55" if ok else "#ff8888"),
                         font=("Segoe UI", 9), anchor="e"
                         ).grid(row=r, column=1, sticky="e", padx=(14, 10))
                if not ok:
                    note = "does not fit"
                elif low != high:
                    note = "depends on what you answer"
                elif lbl == "Overwrite all" and reclaim > 0:
                    note = f"{_fmt_size(reclaim)} comes back from the old file"
                else:
                    note = ""
                tk.Label(cost, text=note, bg=C_BG3, fg="#9a9a9a",
                         font=("Segoe UI", 8), anchor="w"
                         ).grid(row=r, column=2, sticky="w")

        # ── Conflict list ──────────────────────────────────────────────────
        if conflicts:
            tk.Label(self,
                     text=f"{len(conflicts)} file(s) already exist at destination:",
                     bg=self["bg"], fg=C_FG, font=("Segoe UI", 9, "bold"),
                     anchor="w").pack(fill="x", padx=10, pady=(6, 2))

            tree_frm = ttk.Frame(self)
            tree_frm.pack(fill="both", expand=True, padx=8)

            cols = ("name", "src_sz", "src_dt", "dst_sz", "dst_dt", "delta")
            tree = ttk.Treeview(tree_frm, columns=cols, show="headings", height=8)
            tree.heading("name",   text="File")
            tree.heading("src_sz", text="Src size",  anchor="e")
            tree.heading("src_dt", text="Src date",  anchor="center")
            tree.heading("dst_sz", text="Dst size",  anchor="e")
            tree.heading("dst_dt", text="Dst date",  anchor="center")
            tree.heading("delta",  text="\u0394 size", anchor="e")
            tree.column("name",   width=210, stretch=True,  anchor="w")
            tree.column("src_sz", width=80,  stretch=False, anchor="e")
            tree.column("src_dt", width=130, stretch=False, anchor="center")
            tree.column("dst_sz", width=80,  stretch=False, anchor="e")
            tree.column("dst_dt", width=130, stretch=False, anchor="center")
            tree.column("delta",  width=80,  stretch=False, anchor="e")

            vsb = ttk.Scrollbar(tree_frm, orient="vertical", command=tree.yview)
            tree.configure(yscrollcommand=vsb.set)
            vsb.pack(side="right", fill="y")
            tree.pack(fill="both", expand=True)

            # The colours changed meaning, so they are spelled out rather than
            # left to be guessed at.
            legend = tk.Frame(self, bg=self["bg"])
            legend.pack(fill="x", padx=10, pady=(3, 0))
            for col, txt in ((C_CMP_EQUAL,   "green = same size and moment"),
                             (C_CMP_RESTAMP, "blue = same size, different moment"),
                             (C_CMP_BIGGER,  "yellow = incoming is bigger"),
                             (C_CMP_SMALLER, "orange = incoming is smaller")):
                tk.Label(legend, text="  " + txt, bg=self["bg"], fg=col,
                         font=("Segoe UI", 8)).pack(side="left")

            tree.tag_configure("bigger",  foreground=C_CMP_BIGGER)
            tree.tag_configure("smaller", foreground=C_CMP_SMALLER)
            tree.tag_configure("equal",   foreground=C_CMP_EQUAL)
            tree.tag_configure("restamp", foreground=C_CMP_RESTAMP)

            for c in conflicts:
                ss, ds = c["src_size"], c["dst_size"]
                if ss >= 0 and ds >= 0:
                    d = ss - ds
                    if d > 0:
                        delta_s, tag = f"+{_fmt_size(d)}", "bigger"
                    elif d < 0:
                        delta_s, tag = f"-{_fmt_size(-d)}", "smaller"
                    elif _same_moment(c.get("src_mt", 0.0), c.get("dst_mt", 0.0)):
                        delta_s, tag = "equal", "equal"
                    else:
                        # Same size, different moment.  Almost always the same
                        # file copied into two folders, one of which happened
                        # to be written a moment later — so it is NOT called
                        # equal (green) and NOT allowed to look newer.
                        delta_s, tag = "same size", "restamp"
                else:
                    delta_s, tag = "?", "equal"
                tree.insert("", "end",
                            values=(os.path.basename(c["src"]),
                                    _fmt_size(ss) if ss >= 0 else "?", c["src_mtime"],
                                    _fmt_size(ds) if ds >= 0 else "?", c["dst_mtime"],
                                    delta_s),
                            tags=(tag,))
        else:
            tk.Label(self, text="\u2713  No filename conflicts.",
                     bg=self["bg"], fg="#55aa55",
                     font=("Segoe UI", 9)).pack(padx=10, pady=6, anchor="w")

        ttk.Separator(self, orient="horizontal").pack(fill="x", padx=8, pady=8)

        # ── Action buttons ─────────────────────────────────────────────────
        tk.Label(self,
                 text="How should conflicts be handled?" if conflicts else "Ready to proceed.",
                 bg=self["bg"], fg=C_FG, font=("Segoe UI", 9)
                 ).pack(padx=10, anchor="w")

        btn_frm = ttk.Frame(self)
        btn_frm.pack(padx=10, pady=(6, 12), anchor="w")

        if conflicts:
            actions = [
                (self.OVERWRITE_ALL, "Overwrite all"),
                (self.SKIP_ALL,      "Skip all"),
                (self.AUTO_RENAME,   "Auto-rename all"),
                (self.INDIVIDUAL,    "Decide per file"),
            ]
            for col, (val, label) in enumerate(actions):
                why = self._space_reason.get(val, "")
                btn = ttk.Button(btn_frm, text=label, width=17,
                                 command=lambda v=val: self._pick(v))
                btn.grid(row=0, column=col, padx=4, pady=3)
                # A choice that cannot possibly fit is not offered as if it
                # could — but the reason is written straight under the button,
                # so it never reads as the program simply being broken.
                if why:
                    btn.state(["disabled"])
                    tk.Label(btn_frm, text=why, fg="#ff8888", bg=self["bg"],
                             font=("Segoe UI", 8), wraplength=150,
                             justify="left", anchor="w"
                             ).grid(row=1, column=col, padx=4, sticky="w")
            ttk.Button(btn_frm, text="\u2716  Cancel", width=14,
                       command=lambda: self._pick(self.CANCEL)
                       ).grid(row=0, column=len(actions), padx=(14, 4), pady=3)
        else:
            ttk.Button(btn_frm, text="\u25b6  Proceed", width=14,
                       command=lambda: self._pick(self.OVERWRITE_ALL)
                       ).grid(row=0, column=0, padx=4, pady=3)
            ttk.Button(btn_frm, text="\u2716  Cancel", width=14,
                       command=lambda: self._pick(self.CANCEL)
                       ).grid(row=0, column=1, padx=4, pady=3)

        self.update_idletasks()
        if parent:
            try:
                px = parent.winfo_rootx() + (parent.winfo_width()  - self.winfo_width())  // 2
                py = parent.winfo_rooty() + (parent.winfo_height() - self.winfo_height()) // 2
                self.geometry(f"+{max(0, px)}+{max(0, py)}")
            except Exception:
                pass
        self.lift()
        self.focus_force()

        # ESC: skip the clashing files and copy the rest.  If there is no room
        # for that mode (or nothing clashes at all) Escape falls back to its
        # old meaning rather than doing something that cannot work.
        esc = self.SKIP_ALL if (conflicts and
                                not self._space_reason.get(self.SKIP_ALL, "")) \
            else self.CANCEL
        self.bind("<Escape>", lambda e, c=esc: self._pick(c))

    def _pick(self, choice: str):
        self.choice = choice
        self.destroy()


class TaskQueueManager:
    """Manages a list of pending/running/done tasks and executes them sequentially."""

    def __init__(self, editor: "EditorFrame"):
        self._editor  = editor
        self._tasks: list[QueueTask] = []
        self._lock    = threading.Lock()
        self._next_id = 1
        self._running = False
        self._paused  = False
        self._current_task: "QueueTask | None" = None
        self._window:  "QueueWindow | None"    = None
        # Inline progress (updated by _QueueProgressProxy)
        self._cancel_current: bool = False
        self._prog_cur:  int = 0
        self._prog_total: int = 0
        self._prog_file: str = ""
        self._prog_unit: str = "files"    # what _prog_cur/_prog_total count
        self._prog_start: "float | None" = None
        # ── An HONEST speed, and a stall you can SEE (revBN) ──────────────
        # The strip used to divide total bytes by total wall-clock time since
        # the job began.  That average can never reach zero, so half an hour of
        # a dead transfer still read "1 MB/s · ~4.6 h left" — a number that
        # looks like work being done.  _rate is measured over the last few
        # seconds instead, and _seen is when the last byte actually landed, so
        # "nothing is happening" can be said out loud.
        self._prog_rate: float = 0.0         # bytes/s, rolling window
        self._prog_seen: "float | None" = None   # monotonic time of last byte
        self._prog_win:  list = [None, 0, 0.0]   # [anchor_t, anchor_bytes, rate]
        self._space_recheck_id  = None   # after() id for space-recheck timer
        self._space_blocked     = False   # True while waiting for disk space
        self._space_recheck_at  = 0.0    # monotonic time of next auto-recheck
        # ── FAST LANE ────────────────────────────────────────────────────
        # A second worker that only ever runs SMALL (or instant) copy/move
        # jobs, so a 200 KB file never has to sit behind a 9 GB transfer.
        # While it is busy the big job pauses, which is what makes the small
        # one finish in the blink it should take.
        self._fast_running: bool = False
        self._current_fast: "QueueTask | None" = None
        # ── RELOCATOR LANE (revision BZ) ─────────────────────────────────
        # A third worker that only runs Relocator jobs.  It ignores Pause, 🚌
        # and the "big job yields" rules on purpose: whatever the Task Queue is
        # doing, a rule's files start moving NOW.  Only a program close stops
        # it (_reloc_stop, set by shutdown_stop).
        self._reloc_running: bool = False
        self._current_reloc: "QueueTask | None" = None
        self._reloc_stop:    bool = False
        self._fast_busy_since: float = 0.0
        # Its own progress numbers.  Two jobs really do run at once, and with
        # one set of fields the bar jumped between them several times a second
        # — unreadable, and exactly the kind of flicker to keep out of a window
        # that is on screen for an hour.
        self._fprog_cur:   int = 0
        self._fprog_total: int = 0
        self._fprog_file:  str = ""
        self._fprog_unit:  str = "files"
        self._fprog_start: "float | None" = None
        self._fprog_rate:  float = 0.0
        self._fprog_seen:  "float | None" = None
        self._fprog_win:   list = [None, 0, 0.0]
        # ── 🚌 THE BUS LANE'S OWN WORKER (revision CL) ───────────────────
        # Two fast lanes: ⚡ is the AUTOMATIC one (small / single-file instant
        # jobs, chosen by the size rule) and 🚌 is the one that can ONLY be
        # filled by hand.  They are separate workers with separate numbers, so
        # a 35 GB job you sent down the bus lane never holds up the 18 KB files
        # the size rule sends down the ⚡ lane — and the other way round.
        self._bus_running:     bool = False
        self._current_bus: "QueueTask | None" = None
        self._bus_busy_since:  float = 0.0
        self._bprog_cur:   int = 0
        self._bprog_total: int = 0
        self._bprog_file:  str = ""
        self._bprog_unit:  str = "files"
        self._bprog_start: "float | None" = None
        self._bprog_rate:  float = 0.0
        self._bprog_seen:  "float | None" = None
        self._bprog_win:   list = [None, 0, 0.0]
        # ── 🚌 BUS LANE, held open (revBN) ───────────────────────────────
        # "Do it now" used to mean "run beside the big job".  With the switch
        # below it means what it says: while there is bus work that CAN run,
        # the main lane stands down and the bus lane has the disk to itself.
        # Sticky, because "only the bus lane, until I say otherwise" is a mode,
        # not a one-off.
        self._bus_solo: bool = bool(
            getattr(editor, "settings", {}).get("queue_bus_solo", False))
        # ── 🚌 paused (revBT) ────────────────────────────────────────────
        # The other direction: hold the BUS lane still and let the main lane
        # carry on.  Deliberately NOT remembered between sessions — a hold you
        # have forgotten about must never be able to stop work at the next
        # start.  A job already running in the lane stops at the next block
        # boundary, so nothing is half-written and nothing is thrown away.
        self._bus_paused: bool = False
        # ── The queue outlives the program ────────────────────────
        self._state_save_id  = None    # after() id of the debounced save
        self._state_last     = None    # what was written last (skip no-ops)
        self._state_frozen   = False   # the closing snapshot is final
        self._restored_note  = ""      # banner text after a restore

    # ── Public add-task API ───────────────────────────────────────────────

    def add_copy_move(self, sources: list, dest_dir: str,
                      move: bool, conflict_mode: str = "ask",
                      rename_map: dict = None,
                      skip_twin_check: bool = False,
                      reloc: bool = False) -> "QueueTask":
        """Enqueue straight away; measure and scan for clashes in a thread.

        The task appears in the queue at once, marked "🔎 Checking…", and
        nothing runs it until the scan is in.  If clashes are found it is
        parked with conflict_mode="pending_conflicts" until they are resolved
        in the Task Queue window — the same as before, just without the wait.

        WHY IT IS THREADED:  adding up the size of the sources and asking the
        destination whether each name is taken is one round trip per file.  On
        a local disk that is microseconds; on a network drive it is the whole
        reason the file manager "locked up" while queueing a copy to it.
        """
        typ = TaskType.MOVE if move else TaskType.COPY
        if len(sources) == 1:
            desc = f"{os.path.basename(sources[0])}  →  {dest_dir}"
        else:
            desc = f"{len(sources)} files/folders  →  {dest_dir}"

        task = self._enqueue(typ, desc, sources, dest_dir, conflict_mode, 0,
                             preflight="scanning")
        task.requested_mode  = conflict_mode
        task.skip_twin_check = bool(skip_twin_check)
        # Set BEFORE the scan thread starts, so the job is in its lane the
        # moment release_preflight looks at it.
        task.reloc           = bool(reloc)
        if rename_map:
            task.rename_map = dict(rename_map)
        threading.Thread(target=self._preflight_worker, args=(task,),
                         daemon=True).start()
        return task

    def _preflight_worker(self, task: "QueueTask"):
        """Thread: measure the sources and ask the destination what is there."""
        sz, conflicts, twins = 0, [], []
        try:
            sz = self._estimate_size(task.sources)
        except Exception as exc:
            _log(f"Preflight size failed for task {task.task_id}: {exc}")
        try:
            conflicts = _scan_conflicts(task.sources, task.dest_dir)
        except Exception as exc:
            _log(f"Preflight clash scan failed for task {task.task_id}: {exc}")
        if not getattr(task, "skip_twin_check", False):
            try:
                twins = _scan_suffix_twins(task.sources, task.dest_dir)
            except Exception as exc:
                _log(f"Preflight twin scan failed for task {task.task_id}: {exc}")
        _ui_call(self._editor,
                 lambda: self._preflight_done(task, sz, conflicts, twins))

    def _preflight_done(self, task: "QueueTask", sz: int,
                        conflicts: list, twins: list):
        """Main thread: fold the scan result into the task and let it run."""
        task.size_bytes        = sz
        # Files that are the SAME file — same size, same modified time — are
        # not a decision worth making.  With the setting on they are dropped
        # from the clash list here (and skipped again in the worker), so
        # re-copying a folder you already copied asks nothing at all.
        if conflicts and self._editor.settings.get("conflict_skip_identical", False):
            kept = [c for c in conflicts
                    if not _same_file_enough(c.get("src", ""), c.get("dst", ""))]
            if len(kept) != len(conflicts):
                _log(f"Task {task.task_id}: {len(conflicts) - len(kept)} "
                     f"identical file(s) will be skipped without asking")
            conflicts = kept
        task.pending_conflicts = conflicts
        task.twins             = twins
        mode = task.requested_mode or "ask"
        if conflicts and mode in ("ask", "pending_conflicts"):
            # "dialog" alert mode does NOT park the job: leaving the mode at
            # "ask" makes the worker stop on each clash and put the per-file
            # dialog up, which is the old, interrupt-me-now behaviour.
            try:
                parks = self._editor._conflict_alert_mode() != "dialog"
            except Exception:
                parks = True
            mode = "pending_conflicts" if parks else "ask"
        task.conflict_mode = mode

        if twins and not conflicts:
            # "Foo (3).py" landing beside an existing "Foo.py" (DEL 04c).  The
            # job is HELD until that is answered — a small file would otherwise
            # be through the fast lane before the question was on screen.
            task.preflight = "twins"
            self._update_ui()
            try:
                self._editor._ask_suffix_twins(task)
            except Exception as exc:
                _log(f"Twin question failed for task {task.task_id}: {exc}")
                self.release_preflight(task)
            return

        # Only a PARKED job raises the alert; in "dialog" mode the job runs
        # straight away and the dialog is the alert.
        self.release_preflight(
            task, conflicts_alert=bool(conflicts) and mode == "pending_conflicts")

    def release_preflight(self, task: "QueueTask", conflicts_alert: bool = False):
        """Let a held job go: give it its lane, re-sort, start the workers."""
        task.preflight = "done"
        # Now that the size is known the job can be given its lane.
        task.fast = self._classify_fast(task)
        self.smart_sort()
        self._update_ui()
        if task.fast:
            self._start_fast_worker()
        if getattr(task, "reloc", False):
            self._start_reloc_worker()
        if not self._running:
            self.start(resume=False)
        try:
            self._editor._update_queue_btn()
            if conflicts_alert:
                # Parked on a name clash — say so, and bring the queue forward.
                self._editor._after_task_enqueued("", has_conflict=True)
        except Exception as exc:
            _log(f"Preflight follow-up failed for task {task.task_id}: {exc}")

    def add_pack(self, source: str, dest_dir: str, zip_name: str) -> QueueTask:
        sz   = self._estimate_size([source])
        desc = f"{os.path.basename(source)}  →  {zip_name}"
        t    = self._enqueue(TaskType.PACK, desc, [source], dest_dir, "ask", sz)
        t.zip_name = zip_name
        return t

    def add_unpack(self, archive_path: str, dest_dir: str) -> QueueTask:
        """Queue one archive — or one SPLIT SET, which is the same job.

        Whatever part is handed in, the set is entered from its first file and
        the whole set is remembered: that is what stops 43 dropped .r-files
        from becoming 43 jobs, and what makes the size (and a later delete)
        cover all of it."""
        start = archive_start_of(archive_path)
        parts = archive_part_files(start)
        sz = 0
        for f in parts:
            try:
                sz += os.path.getsize(f)
            except OSError:
                pass
        name = os.path.basename(start)
        desc = (f"{name}  ({len(parts)} parts)  →  {dest_dir}" if len(parts) > 1
                else f"{name}  →  {dest_dir}")
        task = self._enqueue(TaskType.UNPACK, desc, [start], dest_dir, "ask", sz)
        task.parts = parts
        return task

    # ── Queue manipulation ────────────────────────────────────────────────

    def smart_sort(self):
        """Sort pending unlocked tasks by auto_priority; locked tasks stay put.

        After sorting, detect tasks whose destination drive won't have enough
        free space given the tasks that will run before them.  Those tasks are
        moved to the end of the unlocked pending block and get a space_warning
        so QueueWindow can display a banner and start an auto-recheck timer.
        """
        with self._lock:
            pending_indices = [i for i, t in enumerate(self._tasks)
                               if t.status == TaskStatus.PENDING]
            unlocked_indices = [i for i in pending_indices
                                if not self._tasks[i].locked]
            unlocked_sorted = sorted(
                [self._tasks[i] for i in unlocked_indices],
                key=lambda t: t.auto_priority()
            )
            # …then put back any job that just overtook an earlier job holding
            # the same file.  The scheduler would refuse to start it anyway;
            # doing it here as well means the LIST shows the true running
            # order instead of a promise it will not keep.
            unlocked_sorted = self._order_respecting_deps(unlocked_sorted)
            for i, t in zip(unlocked_indices, unlocked_sorted):
                self._tasks[i] = t

            # Clear old warnings before recomputing
            for t in self._tasks:
                t.space_warning = ""

            # ── Space-awareness pass ──────────────────────────────────────
            # For each destination drive, walk pending tasks in queue order.
            # Track how much space will be consumed by tasks that run before
            # each task.  If a task won't fit, bump it to the end of the
            # unlocked-pending block and record a warning.
            #
            # "Consumed" = bytes written to that drive minus bytes freed by
            # MOVE operations whose source is on the same drive.

            def _drive(path: str) -> str:
                try:
                    return os.path.splitdrive(os.path.abspath(path))[0].upper()
                except Exception:
                    return ""

            # Collect all pending tasks in current order
            pending_tasks = [t for t in self._tasks if t.status == TaskStatus.PENDING]

            # Per-drive: cumulative bytes that will be written before each task
            drive_consumed: dict[str, int] = {}

            bumped_ids: set = set()

            for t in pending_tasks:
                dst_drv = _drive(t.dest_dir)
                consumed_before = drive_consumed.get(dst_drv, 0)
                free = _free_space(t.dest_dir)

                if free >= 0:
                    available = free - consumed_before
                    needed    = t.size_bytes
                    if available < needed:
                        shortage = needed - available
                        dst_name = (os.path.splitdrive(t.dest_dir)[0] or t.dest_dir[:20])
                        t.space_warning = (
                            f"Waiting for space: needs {_fmt_size(shortage)} more "
                            f"free on {dst_name}  "
                            f"(available after earlier jobs: {_fmt_size(max(0, available))}, "
                            f"required: {_fmt_size(needed)})"
                        )
                        bumped_ids.add(t.task_id)

                # This task will consume space on its destination drive.
                # For a MOVE from the same drive, it also frees space on the source.
                net = t.size_bytes
                if t.task_type == TaskType.MOVE:
                    src_drv = _drive(t.sources[0]) if t.sources else ""
                    if src_drv == dst_drv:
                        net = 0   # rename: no net change
                drive_consumed[dst_drv] = drive_consumed.get(dst_drv, 0) + net

            # Move space-blocked tasks to end of unlocked-pending block
            if bumped_ids:
                ok_tasks     = [t for t in pending_tasks if t.task_id not in bumped_ids]
                bumped_tasks = [t for t in pending_tasks if t.task_id in bumped_ids]
                reordered    = ok_tasks + bumped_tasks

                # Write back — maintain locked tasks at their original positions
                pending_indices_now = [i for i, t in enumerate(self._tasks)
                                       if t.status == TaskStatus.PENDING]
                for list_idx, task_obj in zip(pending_indices_now, reordered):
                    self._tasks[list_idx] = task_obj

    @staticmethod
    def _order_respecting_deps(tasks: list) -> list:
        """Keep the priority order, but never let a job overtake an EARLIER one
        that holds the same file.

        Jobs that share a file form a GROUP.  The group travels together, to
        wherever its best-placed member had got to, and inside the group the
        order is the order they were asked for (task_id).  Jobs that share
        nothing — nearly all of them — come out exactly as they went in.
        """
        n = len(tasks)
        if n < 2 or n > 300:        # a queue that big: the scheduler's own gate
            return list(tasks)      # still holds the order, this is cosmetics
        parent = list(range(n))

        def find(i):
            while parent[i] != i:
                parent[i] = parent[parent[i]]
                i = parent[i]
            return i

        joined = False
        for i in range(n):
            for j in range(i + 1, n):
                if _tasks_clash(tasks[i], tasks[j]):
                    ri, rj = find(i), find(j)
                    if ri != rj:
                        parent[rj] = ri
                        joined = True
        if not joined:
            return list(tasks)

        groups = {}
        for i in range(n):
            groups.setdefault(find(i), []).append(i)
        out = []
        for members in sorted(groups.values(), key=min):
            out.extend(tasks[i] for i in sorted(members,
                                                key=lambda k: tasks[k].task_id))
        return out

    def move_up(self, task_id: int):
        with self._lock:
            pending = [i for i, t in enumerate(self._tasks)
                       if t.status == TaskStatus.PENDING]
            idx = next((i for i, t in enumerate(self._tasks)
                        if t.task_id == task_id), -1)
            if idx < 0 or idx not in pending:
                return
            prev = max((p for p in pending if p < idx), default=None)
            if prev is None:
                return
            self._tasks[idx], self._tasks[prev] = self._tasks[prev], self._tasks[idx]
            # Mark both as locked so smart-sort won't undo the manual choice
            self._tasks[idx].locked  = True
            self._tasks[prev].locked = True

    def move_down(self, task_id: int):
        with self._lock:
            pending = [i for i, t in enumerate(self._tasks)
                       if t.status == TaskStatus.PENDING]
            idx = next((i for i, t in enumerate(self._tasks)
                        if t.task_id == task_id), -1)
            if idx < 0 or idx not in pending:
                return
            nxt = min((p for p in pending if p > idx), default=None)
            if nxt is None:
                return
            self._tasks[idx], self._tasks[nxt] = self._tasks[nxt], self._tasks[idx]
            self._tasks[idx].locked = True
            self._tasks[nxt].locked = True

    def toggle_lock(self, task_id: int):
        with self._lock:
            for t in self._tasks:
                if t.task_id == task_id:
                    t.locked = not t.locked
                    break

    def set_bus(self, task_ids, on: bool = True) -> int:
        """🚌 "Do it now" — put the picked jobs in the BUS LANE.

        The fast lane already exists for small files.  This is the hand-driven
        version of it, for the case a size rule can never know about: THIS file
        is the one being waited for, and it is not going to sit behind a 9 GB
        transfer just because it happens to be 400 MB itself.

        A bus job runs in the second worker, ALONGSIDE whatever is already
        running — not instead of it, so a transfer half-way through a 9 GB file
        is never thrown away.  A small one still makes the big job stand aside
        for a moment (it is over in seconds); a big one runs beside it and the
        two share the disk.

        The one rule that is NOT waived: a job may still not overtake an
        EARLIER job holding the same file.  "Copy X, then move X" queued in
        that order stays in that order — the other way round the copy would
        find nothing left to copy.  Such a row keeps saying "⏳ after #n" and
        takes the lane the moment that one is out of the way.

        Returns how many jobs actually changed.
        """
        if isinstance(task_ids, int):
            task_ids = [task_ids]
        want    = set(task_ids)
        changed = []
        with self._lock:
            for t in self._tasks:
                if t.task_id not in want or t.status != TaskStatus.PENDING:
                    continue
                if getattr(t, "reloc", False):
                    continue
                if on:
                    if t.bus:
                        continue
                    t.bus       = True
                    t.main_only = False
                else:
                    # OUT of the lane means the lane — bus OR the automatic ⚡
                    # one (revision CL).  A job already in the main queue has
                    # nothing to leave.
                    if not (t.bus or t.fast):
                        continue
                    t.bus       = False
                    t.main_only = True
                changed.append(t)
        if not changed:
            return 0
        # _classify_fast honours main_only / bus, so this puts every changed
        # job in the lane it was just given.
        for t in changed:
            t.fast = self._classify_fast(t)
        # smart_sort below orders the lane SHORTEST FIRST (revBT), so a big one
        # dropped into it goes behind the small ones already there instead of
        # in front of them.
        self.smart_sort()
        self._update_ui()
        if on:
            self._start_fast_worker()
            if not self._running:
                self.start(resume=False)
        return len(changed)

    def set_auto_lane(self, task_ids) -> int:
        """Undo "Out of lane": let the size rule choose the lane again."""
        if isinstance(task_ids, int):
            task_ids = [task_ids]
        want    = set(task_ids)
        changed = []
        with self._lock:
            for t in self._tasks:
                if (t.task_id in want and t.status == TaskStatus.PENDING
                        and getattr(t, "main_only", False)):
                    t.main_only = False
                    changed.append(t)
        if not changed:
            return 0
        for t in changed:
            t.fast = self._classify_fast(t)
        self.smart_sort()
        self._update_ui()
        self._start_fast_worker()
        if not self._running:
            self.start(resume=False)
        return len(changed)

    # ── The queue survives a restart ─────────────────────────────
    #
    # Closing the file manager while the queue still had work in it used to
    # throw that work away without a word — one stray click on the X and forty
    # queued transfers were gone.  Now the unfinished list is written to
    # Helpfiles/redigerare/task_queue.json as it changes, and comes back at the
    # next start: PAUSED, with the Task Queue in front, so nothing moves until
    # it is looked at and ▶ Start is pressed.

    _STATE_VERSION = 1

    def unfinished(self) -> list:
        """Every job that has not finished — waiting AND the one running."""
        with self._lock:
            return [t for t in self._tasks
                    if t.status in (TaskStatus.PENDING, TaskStatus.RUNNING)]

    def to_state(self, tasks=None) -> list:
        """The unfinished queue as plain, JSON-able data.

        Pass *tasks* to record a hand-picked set instead (💾 Save queue…); the
        record format is identical either way, so a saved queue and a
        carried-over one come back through exactly the same code.
        """
        out = []
        for t in (self.unfinished() if tasks is None else list(tasks)):
            try:
                out.append({
                    "v":           self._STATE_VERSION,
                    "type":        t.task_type.value,
                    "description": t.description,
                    "sources":     list(t.sources or []),
                    "dest_dir":    t.dest_dir or "",
                    "zip_name":    t.zip_name or "",
                    "mode":        t.requested_mode or "ask",
                    "size_bytes":  int(t.size_bytes or 0),
                    "locked":      bool(t.locked),
                    "bus":         bool(getattr(t, "bus", False)),
                    "main_only":   bool(getattr(t, "main_only", False)),
                    "reloc":      bool(getattr(t, "reloc", False)),
                    "added_at":    float(t.added_at or 0.0),
                    "rename_map":  dict(t.rename_map or {}),
                    # Already part-written once — skip what is there and
                    # identical rather than asking about every file of it.
                    "resume_skip": bool(getattr(t, "resume_skip", False)),
                    # The job that was mid-transfer.  Its destination may hold
                    # a part-written file, so the row says so next time round
                    # instead of pretending the job never started.
                    "interrupted": (t.status == TaskStatus.RUNNING
                                    or bool(getattr(t, "was_interrupted", False))),
                })
            except Exception as exc:
                _log(f"Queue state: could not record task {t.task_id}: {exc}")
        return out

    def save_state_now(self, freeze: bool = False):
        """Write the unfinished queue out (skipped when nothing changed).

        freeze=True makes this snapshot the LAST one.  The close path writes
        the list and only then cancels the file that is mid-transfer — without
        the freeze, the save that shutdown() does a moment later would write
        the list again with that job gone from it, which is precisely the job
        that most needs to come back.
        """
        if self._state_frozen:
            return
        if freeze:
            self._state_frozen = True
        try:
            data = self.to_state()
        except Exception as exc:
            _log(f"Queue state: could not be collected: {exc}")
            return
        try:
            sig = json.dumps(data, sort_keys=True, ensure_ascii=False)
        except Exception:
            sig = None
        if sig is not None and sig == self._state_last:
            return
        self._state_last = sig
        _save_json_list(QUEUE_STATE_PATH, data)

    def save_state_soon(self, delay_ms: int = 3000):
        """Debounced save.

        _update_ui is called many times a second while a copy runs; the LIST
        itself changes a handful of times an hour.  Writing on every call would
        be a JSON dump per progress tick for no gain whatsoever.
        """
        if self._state_save_id is not None:
            return                       # one is already on its way
        try:
            self._state_save_id = self._editor.after(delay_ms, self._state_tick)
        except Exception:
            self._state_save_id = None
            self.save_state_now()

    def _state_tick(self):
        self._state_save_id = None
        self.save_state_now()

    def discard_state(self):
        """Forget the saved queue — the ‘drop them’ answer."""
        self._state_last = None
        try:
            QUEUE_STATE_PATH.unlink()
        except FileNotFoundError:
            pass
        except Exception as exc:
            _log(f"Queue state: could not be removed: {exc}")

    # ── One way in for every kind of "put these jobs back" (revBN) ────────
    #
    # Carried over from the last session, loaded from a queue saved by hand,
    # or put back by ↺ Resume: all three are the same operation on the same
    # records, and they used to be one of them plus two that did not exist.

    def queue_from_records(self, data: list, resume: bool = False,
                           force_bus: "bool | None" = None) -> tuple:
        """Queue jobs from saved records.  Returns (queued, dropped).

        Everything goes back through the ORDINARY add path, so each job is
        measured and re-scanned against the disk as it is NOW: files deleted,
        moved or already copied since are picked up exactly as they would be
        for a job queued by hand this minute.  A job whose sources are all
        gone is dropped and said so, not queued to fail.

        resume=True marks them "already part-written": the clash policy is
        kept, but a destination file that is there AND identical is skipped in
        silence instead of being asked about.  That is what makes picking a
        33 GB copy back up a button press rather than four thousand answers.
        """
        # Paused BEFORE the first job is queued: adding one starts the workers,
        # and a queue that resumed itself behind your back is exactly what this
        # is here to prevent.
        self._paused = True
        by_name = {"copy": TaskType.COPY, "move": TaskType.MOVE,
                   "pack": TaskType.PACK, "unpack": TaskType.UNPACK}
        n, dropped = 0, 0
        for rec in data:
            if not isinstance(rec, dict):
                continue
            typ = by_name.get(str(rec.get("type", "")).lower())
            if typ is None:
                continue
            asked = list(rec.get("sources") or [])
            srcs  = [p for p in asked if os.path.exists(p)]
            if not srcs:
                dropped += 1
                _log(f"Queue restore: dropped ‘{rec.get('description', '')}’ "
                     f"— none of its {len(asked)} source(s) are there any more")
                continue
            dest = rec.get("dest_dir") or ""
            # "pending_conflicts" is a PARKED state, not a policy — asking for
            # it again would queue a job that waits for an answer to a question
            # nobody has been shown.  The fresh scan raises the clashes itself.
            mode = str(rec.get("mode") or "ask")
            if mode == "pending_conflicts":
                mode = "ask"
            try:
                if typ in (TaskType.COPY, TaskType.MOVE):
                    t = self.add_copy_move(
                        srcs, dest, move=(typ is TaskType.MOVE),
                        conflict_mode=mode,
                        rename_map=(rec.get("rename_map") or None),
                        reloc=bool(rec.get("reloc")))
                elif typ is TaskType.PACK:
                    t = self.add_pack(srcs[0], dest, str(rec.get("zip_name") or ""))
                else:
                    t = self.add_unpack(srcs[0], dest)
            except Exception as exc:
                _log(f"Queue restore failed for ‘{rec.get('description', '')}’: {exc}")
                continue
            t.locked          = bool(rec.get("locked"))
            t.bus             = ((bool(rec.get("bus")) if force_bus is None
                                  else bool(force_bus))
                                 and not getattr(t, "reloc", False))
            t.restored        = True
            t.was_interrupted = bool(rec.get("interrupted"))
            # A job that was mid-transfer has already written part of itself,
            # so it is a resume whether the caller said so or not.
            t.resume_skip     = bool(resume or rec.get("resume_skip")
                                     or rec.get("interrupted"))
            t.main_only       = (bool(rec.get("main_only")) and not t.bus
                                 and not getattr(t, "reloc", False))
            if t.bus:
                t.fast = self._classify_fast(t)
            n += 1
        return n, dropped

    # ── Queues saved by hand ─────────────────────────────────────────────
    #
    # "Pausa och spara en queue … och ladda in och resume senare."  The
    # automatic file already survives a close; this is the deliberate version,
    # so a big job can be parked under a name and picked up next week without
    # having to be the thing the program happened to be doing when it shut.

    @staticmethod
    def _queue_file(name: str) -> Path:
        safe = _re.sub(r'[<>:"/\\|?*\x00-\x1f]', "_", (name or "").strip())
        safe = safe.rstrip(". ") or "queue"
        return QUEUE_DIR / f"{safe[:80]}.json"

    def list_saved_queues(self) -> list:
        """[(name, job count, total bytes, mtime)] newest first."""
        out = []
        try:
            QUEUE_DIR.mkdir(parents=True, exist_ok=True)
            for p in QUEUE_DIR.glob("*.json"):
                try:
                    recs  = _load_json_list(p)
                    total = sum(int(r.get("size_bytes") or 0)
                                for r in recs if isinstance(r, dict))
                    out.append((p.stem, len(recs), total, p.stat().st_mtime))
                except Exception as exc:
                    _log(f"Saved queue ‘{p.name}’ could not be read: {exc}")
        except Exception as exc:
            _log(f"Saved queues could not be listed: {exc}")
        out.sort(key=lambda r: r[3], reverse=True)
        return out

    def save_queue_as(self, name: str, task_ids=None) -> tuple:
        """Write the picked jobs (or every unfinished one) to a named file.

        Returns (count, path).  The jobs stay in the queue — saving is not
        removing; 🗑 Remove is for that.
        """
        if task_ids is None:
            tasks = self.unfinished()
        else:
            want  = set(task_ids)
            with self._lock:
                tasks = [t for t in self._tasks if t.task_id in want]
        data = self.to_state(tasks)
        if not data:
            return 0, None
        QUEUE_DIR.mkdir(parents=True, exist_ok=True)
        path = self._queue_file(name)
        _save_json_list(path, data)
        _log(f"Queue saved: {len(data)} job(s) → {path}")
        return len(data), path

    def load_saved_queue(self, name: str, resume: bool = True) -> tuple:
        """Put a saved queue back, PAUSED.  Returns (queued, dropped)."""
        path = self._queue_file(name)
        data = _load_json_list(path)
        if not data:
            return 0, 0
        n, dropped = self.queue_from_records(data, resume=resume)
        self._paused = True
        if n:
            self._restored_note = (
                f"📂  {n} job(s) loaded from ‘{name}’ — the queue is PAUSED. "
                f"Press ▶ Start when you are ready."
                + ("  Files already at the destination and identical will be "
                   "skipped without asking." if resume else ""))
        self._update_ui()
        return n, dropped

    def delete_saved_queue(self, name: str) -> bool:
        try:
            self._queue_file(name).unlink()
            return True
        except FileNotFoundError:
            return False
        except Exception as exc:
            _log(f"Saved queue ‘{name}’ could not be deleted: {exc}")
            return False

    def force_unpack_tasks(self, task_ids) -> int:
        """⏩ Unpack anyway - drop the completeness wait for the picked unpack
        jobs (a waiting one, or one that gave up waiting) and run them now."""
        want = set(task_ids)
        n = 0
        with self._lock:
            for t in self._tasks:
                if (t.task_id in want and t.task_type == TaskType.UNPACK
                        and t.status in (TaskStatus.PENDING, TaskStatus.ERROR)):
                    t.force_unpack = True
                    t.wait_until   = 0.0
                    t.wait_reason  = ""
                    t.wait_tries   = 0
                    t.error_msg    = ""
                    t.status       = TaskStatus.PENDING
                    n += 1
        if n:
            self._paused = False
            self._start_fast_worker()
            if not self._running:
                self.start()
            self._update_ui()
        return n

    def resume_tasks(self, task_ids) -> int:
        """↺ Resume — put finished / cancelled / failed jobs back to work.

        THE ANSWER TO "the ones I cancel, do I have to start over?".  No: the
        job is queued again exactly as it was, marked as a resume, so every
        file it already wrote is skipped in silence and it carries on from
        where it stopped.  Only the file that was mid-copy when it was
        cancelled is done again — a cancel deletes that one on purpose, so
        there is never a half-written file wearing the right name.
        """
        want = set(task_ids)
        with self._lock:
            tasks = [t for t in self._tasks
                     if t.task_id in want
                     and t.status in (TaskStatus.DONE, TaskStatus.CANCELLED,
                                      TaskStatus.ERROR)]
        if not tasks:
            return 0
        data = self.to_state(tasks)
        n, _dropped = self.queue_from_records(data, resume=True)
        if n:
            self._paused = False         # asked for by hand — get on with it
            self._restored_note = ""
            self.smart_sort()
            self._start_fast_worker()
            if not self._running:
                self.start()
            self._update_ui()
        return n

    def restore_state(self) -> int:
        """Put the last session’s unfinished jobs back — PAUSED.

        They go back through the ordinary add path, so every one of them is
        MEASURED AND SCANNED AGAIN against the disk as it is now: files that
        have since been deleted, moved or already copied are picked up as they
        would be for a job queued by hand this minute.  A job whose sources are
        all gone is dropped and logged rather than queued to fail.

        Returns how many jobs came back.
        """
        data = _load_json_list(QUEUE_STATE_PATH)
        if not data:
            return 0
        n, dropped = self.queue_from_records(data)
        self._paused = True              # the add path started the threads
        if not n:
            self.discard_state()
            self._update_ui()
            return 0
        note = (f"↺  {n} job(s) carried over from the last session — the queue "
                f"is PAUSED.  Look them over, then press ▶ Start.")
        if dropped:
            note += (f"\n     {dropped} more could not come back: nothing is left "
                     f"of them on disk (see the log).")
        if any(bool(r.get("interrupted")) for r in data if isinstance(r, dict)):
            note += ("\n     ↺ A job was mid-transfer.  It comes back as a "
                     "RESUME: every file it already wrote is skipped in "
                     "silence, so it carries on from where it stopped instead "
                     "of asking about each one.  Its part-written file was "
                     "removed on the way out; if the machine lost power "
                     "instead, the ‘Src size / Dst size’ columns in the clash "
                     "list are where a half-copied file shows up.")
        self._restored_note = note
        self._update_ui()
        return n

    def shutdown_stop(self, root=None, wait_s: float = 5.0):
        """Stand both lanes down for a close, and wait for them to let go.

        CANCEL, not pause: _copy_file_chunked DELETES the part-written
        destination file when it is cancelled and leaves it exactly where it is
        when it is merely paused — and a half-written file under the right name
        is the one thing that must not be left behind, because next time it
        looks like a file that is already there.  The pause stays on, so the
        job after it cannot start while we are on our way out.

        The wait pumps the event loop, because the copy reports back through
        it; it gives up after wait_s rather than hanging the close.
        """
        self._paused = True
        self._reloc_stop = True
        self._cancel_current = True
        t = self._current_fast
        if t is not None:
            t.cancel_requested = True
        t = self._current_bus
        if t is not None:
            t.cancel_requested = True
        t = self._current_reloc
        if t is not None:
            t.cancel_requested = True
        end = _time.monotonic() + max(0.0, wait_s)
        while _time.monotonic() < end:
            if (self._current_task is None and self._current_fast is None
                    and self._current_bus is None
                    and self._current_reloc is None):
                return True
            if root is not None:
                try:
                    root.update()
                except Exception:
                    break
            _time.sleep(0.05)
        return (self._current_task is None and self._current_fast is None
                and self._current_bus is None
                and self._current_reloc is None)

    def bus_ids(self) -> set:
        """The ids currently in the fast/bus lane (for the window's toggle).
        The automatic ⚡ jobs count too (revision CL) — they can be moved out."""
        with self._lock:
            return {t.task_id for t in self._tasks
                    if getattr(t, "bus", False)
                    or (t.fast and t.status == TaskStatus.PENDING)}

    def cancel_task(self, task_id: int):
        with self._lock:
            for t in self._tasks:
                if t.task_id == task_id and t.status == TaskStatus.PENDING:
                    t.status = TaskStatus.CANCELLED
                    break
        self._update_ui()

    def remove_tasks(self, task_ids) -> tuple:
        """Take jobs out of the list for good.  Returns (removed, left running).

        A job that has not started is cancelled on the way out, so nothing can
        pick it up between the two steps.  A RUNNING job is never removed —
        pulling the row out from under a live copy would leave a half-written
        file with nothing watching it; that is what the progress bar's ✖ is
        for."""
        want = set(task_ids)
        removed = running = 0
        with self._lock:
            keep = []
            for t in self._tasks:
                if t.task_id in want:
                    if t.status == TaskStatus.RUNNING:
                        running += 1
                        keep.append(t)
                        continue
                    if t.status == TaskStatus.PENDING:
                        t.status = TaskStatus.CANCELLED
                        t.cancel_requested = True
                    removed += 1
                    continue
                keep.append(t)
            self._tasks = keep
        self._update_ui()
        try:
            self._editor._update_queue_btn()
        except Exception:
            pass
        return removed, running

    def remove_finished(self):
        with self._lock:
            self._tasks = [t for t in self._tasks
                           if t.status not in (TaskStatus.DONE,
                                               TaskStatus.CANCELLED,
                                               TaskStatus.ERROR)]
        self._update_ui()

    def pending_count(self) -> int:
        with self._lock:
            return sum(1 for t in self._tasks
                       if t.status in (TaskStatus.PENDING, TaskStatus.RUNNING))

    def get_tasks(self) -> list:
        with self._lock:
            return list(self._tasks)

    def first_conflict_task(self):
        """The job at the front of the queue that is parked on a name clash.

        Both the Task Queue's own banner and the inline bar in the main
        window ask for it, so there is one answer to "which job is the
        question about" instead of two that could disagree."""
        with self._lock:
            for t in self._tasks:
                if (t.status == TaskStatus.PENDING
                        and t.conflict_mode == "pending_conflicts"
                        and t.pending_conflicts):
                    return t
        return None

    def resolve_pending_conflicts(self, mode: str) -> bool:
        """Apply *mode* to every job waiting on a name clash and let them run.

        Shared by the Task Queue banner and the inline conflict bar — the two
        must do exactly the same thing, or which one you happened to answer
        would change the outcome."""
        changed = False
        with self._lock:
            tasks = list(self._tasks)
        for t in tasks:
            if (t.status == TaskStatus.PENDING
                    and t.conflict_mode == "pending_conflicts"):
                t.conflict_mode     = mode
                t.pending_conflicts = []      # cleared — no longer blocking
                t.space_warning     = ""
                changed = True
        if changed:
            self.smart_sort()
            self._update_ui()
            # BOTH lanes have to be woken.  A small job (most of them) sits in
            # the FAST lane, and its worker walks away when there is nothing
            # runnable — which is exactly what a job parked on a name clash
            # looks like.  Starting only the big lane left such a job answered
            # but stranded, with the queue apparently doing nothing.
            for t in tasks:
                if (t.status == TaskStatus.PENDING and getattr(t, "fast", False)):
                    self._start_fast_worker()
                    break
            self._start_reloc_worker()
            if not self._running:
                self.start()
            try:
                self._editor._update_queue_btn()
            except Exception:
                pass
        return changed

    def waiting_count(self) -> int:
        """Jobs that are parked until the user does something — a name clash
        or a destination with no room.  (A job still being measured is not
        waiting for anyone, so it does not count.)"""
        with self._lock:
            return sum(1 for t in self._tasks
                       if t.status == TaskStatus.PENDING
                       and (t.conflict_mode == "pending_conflicts"
                            or t.space_warning))

    # ── Start / pause ─────────────────────────────────────────────────────

    # ── Fast lane ─────────────────────────────────────────────────────────

    def _fast_settings(self) -> tuple:
        """(enabled, size limit in bytes, pause-the-big-one)."""
        s = self._editor.settings
        try:
            mb = float(s.get("fastlane_max_mb", 50))
        except (TypeError, ValueError):
            mb = 50.0
        return (bool(s.get("fastlane_enabled", True)),
                int(max(0.0, mb) * 1024 * 1024),
                bool(s.get("fastlane_pause_big", True)))

    def _classify_fast(self, task: QueueTask) -> bool:
        """Should this job skip the queue and run in the fast lane?

        Yes when it is a copy/move that is either SMALL (under the size limit)
        or INSTANT (a same-drive move, which is only a rename).  Pack/unpack
        stay in the main queue — they are CPU-bound and would fight the big
        transfer instead of slipping past it."""
        # A Relocator job has a lane of its own and is in neither of the others.
        if getattr(task, "reloc", False):
            return False
        # Taken out of the lane by hand (revision CL): stays in the main queue.
        if getattr(task, "main_only", False):
            return False
        # Asked for by hand: no size rule, no on/off switch, no job type.
        # (Checked FIRST so re-measuring a job — release_preflight — cannot
        # quietly take it back out of the lane you put it in.)
        if getattr(task, "bus", False):
            return True
        enabled, limit, _pause = self._fast_settings()
        if not enabled:
            return False
        if task.task_type not in (TaskType.COPY, TaskType.MOVE):
            return False
        if getattr(task, "preflight", "done") == "scanning":
            return False        # its size is not known yet — decide when it is
        if task.is_instant():
            return True
        return 0 <= task.size_bytes <= limit

    def _big_should_yield(self) -> bool:
        """True while the fast lane is running and the big job should hold off.

        The chunked copy checks this on every block, so the pause takes effect
        within a megabyte or so.  A safety cap stops a stuck fast job from
        freezing the big one for ever."""
        if self._current_fast is None and self._current_bus is None:
            return False
        if not self._fast_settings()[2]:
            return False
        limit = self._fast_settings()[1]
        # Two small lanes now (revision CL): the main job stands aside for
        # EITHER of them, by the same rules.
        for cur, since in ((self._current_fast, self._fast_busy_since),
                           (self._current_bus,  self._bus_busy_since)):
            if cur is None:
                continue
            # 🚌 paused: the lane is HELD, so the job in it is not moving a
            # byte.  Standing the big transfer down for it would stop BOTH
            # lanes dead until the 120 s cap below let go — the whole machine
            # idle, waiting for something that has been told not to move.
            if self._bus_paused and getattr(cur, "bus", False):
                continue
            # A hand-picked BIG job is a BUS LANE, not a queue jump: it runs
            # ALONGSIDE the big transfer and the two share the disk.  A small
            # one still gets the road to itself; it is over in seconds.
            if getattr(cur, "bus", False) and cur.size_bytes > limit:
                continue
            if _time.monotonic() - since > 120:
                continue           # not so fast after all — carry on
            return True
        return False

    # ── 🚌 The bus lane as a lane of its own (revBN) ──────────────────────

    def bus_queue(self) -> list:
        """Everything in the bus lane, in the order it will run."""
        with self._lock:
            return [t for t in self._tasks
                    if getattr(t, "bus", False)
                    and t.status in (TaskStatus.PENDING, TaskStatus.RUNNING)]

    def set_bus_paused(self, on: bool):
        """🚌 paused — hold the bus lane still; the main lane carries on.

        The answer to "I hit 🚌 on the 35 GB transfer by mistake and now it is
        in front of my three small ones": you do not have to cancel it and
        throw the progress away — hold the lane, let the main queue get on
        with it, and let it go again when you want it.
        """
        self._bus_paused = bool(on)
        if not on:
            # The lane's worker walks away when it finds nothing it may run,
            # so releasing the hold has to wake it — otherwise the jobs would
            # sit there with nobody coming back for them.
            self._start_fast_worker()
        self._update_ui()

    def clear_bus_lane(self) -> int:
        """RIGHT-click 🚌 — take every job that has not started yet OUT of the
        bus lane, back into the normal queue.  One press to undo a mis-click.

        A job that is already RUNNING in the lane stays where it is: it is
        moving bytes, and there is nowhere to move it to.  ✖ Cancel stops that
        one, and ↺ Resume carries it on later from where it stopped."""
        with self._lock:
            ids = [t.task_id for t in self._tasks
                   if (getattr(t, "bus", False) or t.fast)
                   and not getattr(t, "reloc", False)
                   and t.status == TaskStatus.PENDING]
        return self.set_bus(ids, False) if ids else 0

    def set_bus_solo(self, on: bool):
        """🚌 only — hold the main lane while there is bus work to do."""
        self._bus_solo = bool(on)
        try:
            self._editor.settings["queue_bus_solo"] = bool(on)
            self._editor.save_settings()
        except Exception as exc:
            _log(f"Bus-solo setting could not be saved: {exc}")
        self._update_ui()

    def bus_holds_main(self) -> bool:
        """True while the main lane must stand down for the bus lane.

        Asked for in as many words: "den får även ha funktionen att den kan
        pausa huvudgrejen = kör bara bus-lane".  With 🚌 only ticked the big
        transfer stops at the next block boundary and stays stopped until the
        bus queue is empty — not sharing the disk, not taking half of it.

        THE ONE THING IT MUST NOT DO IS DEADLOCK.  A bus job that cannot run —
        parked on a name clash, waiting for room, or held back because an
        EARLIER job has the same file open (which may well be the very job we
        would be pausing) — holds nothing.  Only bus work that could actually
        start counts, so the two lanes can never sit waiting for each other.
        """
        if not self._bus_solo or self._bus_paused:
            # Held lanes hold nobody: standing the main lane down for a lane
            # that is not allowed to move is the one way these two could sit
            # waiting for each other for ever.
            return False
        with self._lock:
            for t in self._tasks:
                if not getattr(t, "bus", False):
                    continue
                if t.status == TaskStatus.RUNNING:
                    return True
                if (t.status == TaskStatus.PENDING
                        and not t.space_warning
                        and getattr(t, "preflight", "done") == "done"
                        and t.conflict_mode != "pending_conflicts"
                        and getattr(t, "wait_until", 0.0) <= _time.time()
                        and self.held_by(t) is None):
                    return True
        return False

    def start(self, resume: bool = True):
        """Start the queue worker(s) (idempotent).

        resume=False starts the THREADS but leaves any pause in place.  That is
        what queueing a job does now: a queue you paused on purpose — or one
        restored paused from the last session — must not quietly start moving
        again because you dragged another file onto a panel.  Only ▶ Start and
        the Pause button lift a pause.
        """
        self._start_fast_worker()
        if resume:
            self._paused = False
            self._restored_note = ""
        if self._running:
            self._update_ui()
            return
        self._running = True
        threading.Thread(target=self._run_loop, daemon=True).start()
        self._update_ui()

    def _start_fast_worker(self):
        """Spin up the fast-lane worker if there is small work waiting."""
        # Every caller of this is asking "did something just become runnable?",
        # which is the Relocator lane's question too (revBZ).
        self._start_reloc_worker()
        # The bus lane has a worker of its own (revision CL).
        self._start_bus_worker()
        if self._fast_running:
            return
        with self._lock:
            has_fast = any(t.fast and not getattr(t, "bus", False)
                           and t.status == TaskStatus.PENDING
                           for t in self._tasks)
        if not has_fast:
            return
        # The AUTOMATIC lane can be switched off in Settings.  (The bus lane is
        # an explicit instruction and ignores that switch.)
        if not self._fast_settings()[0]:
            return
        self._fast_running = True
        threading.Thread(target=self._run_fast_loop, daemon=True).start()

    def _fast_held_waiting(self) -> bool:
        """Is a small job sitting still ONLY because an earlier job has the
        same file?  (Anything else — a clash to answer, no room on the drive —
        is not ours to wait for, and the lane closes as it always did.)"""
        with self._lock:
            for t in self._tasks:
                if (t.fast and not getattr(t, "bus", False)
                        and t.status == TaskStatus.PENDING
                        and not t.space_warning
                        and getattr(t, "preflight", "done") == "done"
                        and t.conflict_mode != "pending_conflicts"
                        and self.held_by(t) is not None):
                    return True
        return False

    def _next_runnable_fast(self) -> "QueueTask | None":
        with self._lock:
            # The AUTOMATIC lane only: hand-picked (🚌) jobs have their own
            # worker (revision CL), so a long one never blocks these.
            ready = [t for t in self._tasks
                     if (t.fast and t.status == TaskStatus.PENDING
                         and not getattr(t, "bus", False)
                         and not t.space_warning
                         and getattr(t, "preflight", "done") == "done"
                         and t.conflict_mode != "pending_conflicts"
                         # The fast lane is exactly where the overtaking used
                         # to happen: an instant same-drive MOVE ran alongside
                         # the big transfer and beat the COPY of the same file
                         # that was queued before it.
                         and self.held_by(t) is None)]
        return ready[0] if ready else None

    # ── 🚌 The bus lane's own worker (revision CL) ────────────────────────

    def _start_bus_worker(self):
        """Spin up the bus-lane worker if a hand-picked job is waiting."""
        if self._bus_running:
            return
        with self._lock:
            has = any(getattr(t, "bus", False)
                      and t.status == TaskStatus.PENDING for t in self._tasks)
        if not has:
            return
        self._bus_running = True
        threading.Thread(target=self._run_bus_loop, daemon=True).start()

    def _bus_held_waiting(self) -> bool:
        """A bus job sitting still ONLY because an earlier job has its file."""
        with self._lock:
            for t in self._tasks:
                if (getattr(t, "bus", False) and t.status == TaskStatus.PENDING
                        and not t.space_warning
                        and getattr(t, "preflight", "done") == "done"
                        and t.conflict_mode != "pending_conflicts"
                        and self.held_by(t) is not None):
                    return True
        return False

    def _next_runnable_bus(self) -> "QueueTask | None":
        """The shortest bus job that may run now (the list is kept sorted)."""
        if self._bus_paused:
            return None            # 🚌 paused: the lane is held
        with self._lock:
            for t in self._tasks:
                if (getattr(t, "bus", False) and t.status == TaskStatus.PENDING
                        and not t.space_warning
                        and getattr(t, "preflight", "done") == "done"
                        and t.conflict_mode != "pending_conflicts"
                        and self.held_by(t) is None):
                    return t
        return None

    def _run_bus_loop(self):
        """Worker thread for hand-picked (🚌) jobs, one after another.

        Same shape as the fast loop, with its own current job, its own clock
        and its own progress numbers — so it can run at the same moment as the
        ⚡ worker and the main lane."""
        try:
            while True:
                task = self._next_runnable_bus()
                if task is None:
                    if self._bus_held_waiting():
                        _time.sleep(0.3)
                        continue
                    break
                while self._paused:
                    _time.sleep(0.1)
                task.status           = TaskStatus.RUNNING
                task.cancel_requested = False
                self._current_bus     = task
                self._bus_busy_since  = _time.monotonic()
                _ui_call(self._editor, self._update_ui)
                try:
                    self._execute(task)
                    if task.status == TaskStatus.RUNNING:
                        task.status = TaskStatus.DONE
                except Exception as exc:
                    task.status    = TaskStatus.ERROR
                    task.error_msg = str(exc)
                task.finished_at  = _time.time()
                self._current_bus = None
                _ui_call(self._editor, self._update_ui)
                _ui_call(self._editor, self._editor._update_queue_btn)
                _ui_call(self._editor, self._editor._refresh_and_refocus, 150)
        finally:
            self._current_bus = None
            self._bus_running = False
            _ui_call(self._editor, self._update_ui)
            # Lost-wakeup guard, as in the fast lane.
            try:
                if self._next_runnable_bus() is not None:
                    self._start_bus_worker()
            except Exception as exc:
                _log(f"Bus-lane restart check failed: {exc}")

    def _run_fast_loop(self):
        """Worker thread for small / instant jobs only.

        Deliberately simple: it never touches _current_task, _cancel_current or
        the progress bar, so it cannot disturb the big transfer's display.  Its
        own task carries its cancel flag.
        """
        try:
            while True:
                task = self._next_runnable_fast()
                if task is None:
                    # Nothing to do — unless the only thing stopping a small
                    # job is an EARLIER job holding the same file.  Walking
                    # away then would strand it: the big lane never takes a
                    # fast task, so nobody would come back for it.
                    if self._fast_held_waiting():
                        _time.sleep(0.3)
                        continue
                    break
                while self._paused:
                    _time.sleep(0.1)
                task.status           = TaskStatus.RUNNING
                task.cancel_requested = False
                self._current_fast    = task
                self._fast_busy_since = _time.monotonic()
                _ui_call(self._editor, self._update_ui)
                try:
                    self._execute(task)
                    if task.status == TaskStatus.RUNNING:
                        task.status = TaskStatus.DONE
                except Exception as exc:
                    task.status    = TaskStatus.ERROR
                    task.error_msg = str(exc)
                task.finished_at   = _time.time()
                self._current_fast = None
                _ui_call(self._editor, self._update_ui)
                _ui_call(self._editor, self._editor._update_queue_btn)
                _ui_call(self._editor, self._editor._refresh_and_refocus, 150)
        finally:
            self._current_fast = None
            self._fast_running = False
            _ui_call(self._editor, self._update_ui)
            # Lost-wakeup guard.  Between this loop deciding "nothing to do"
            # and the line above lowering the flag, anything that queued a
            # small job — or answered a name clash — asked _start_fast_worker
            # for a worker, was told one was already running, and did nothing.
            # The thread it was counting on was this one, on its way out, so
            # the job would have sat there for ever.  Now that the flag really
            # is down, look once more.
            try:
                if self._next_runnable_fast() is not None:
                    self._start_fast_worker()
            except Exception as exc:
                _log(f"Fast-lane restart check failed: {exc}")

    # ── ⤴ The Relocator lane (revision BZ) ────────────────────────────────

    def _start_reloc_worker(self):
        """Spin up the Relocator lane's worker if a rule's job is waiting."""
        if self._reloc_running or self._reloc_stop:
            return
        with self._lock:
            has = any(getattr(t, "reloc", False)
                      and t.status == TaskStatus.PENDING for t in self._tasks)
        if not has:
            return
        self._reloc_running = True
        threading.Thread(target=self._run_reloc_loop, daemon=True).start()

    def _reloc_held_waiting(self) -> bool:
        """Is a rule's job sitting still ONLY because an earlier job has the
        same file?  Then the lane waits for it instead of walking away."""
        with self._lock:
            for t in self._tasks:
                if (getattr(t, "reloc", False)
                        and t.status == TaskStatus.PENDING
                        and not t.space_warning
                        and getattr(t, "preflight", "done") == "done"
                        and t.conflict_mode != "pending_conflicts"
                        and self.held_by(t) is not None):
                    return True
        return False

    def _next_runnable_reloc(self) -> "QueueTask | None":
        with self._lock:
            for t in self._tasks:
                if (getattr(t, "reloc", False)
                        and t.status == TaskStatus.PENDING
                        and not t.space_warning
                        and getattr(t, "preflight", "done") == "done"
                        and t.conflict_mode != "pending_conflicts"
                        and self.held_by(t) is None):
                    return t
        return None

    def _run_reloc_loop(self):
        """Worker thread for the Relocator's jobs, and nothing else.

        Like the fast lane it touches neither _current_task nor _cancel_current
        nor the big bar, so it cannot disturb the transfer it runs beside.
        Unlike the fast lane it does not wait for Pause, for 🚌 only, or for a
        fast job to finish: the Relocator is what you press when you want the
        files there now."""
        try:
            while not self._reloc_stop:
                task = self._next_runnable_reloc()
                if task is None:
                    if self._reloc_held_waiting():
                        _time.sleep(0.3)
                        continue
                    break
                task.status           = TaskStatus.RUNNING
                task.cancel_requested = False
                self._current_reloc   = task
                _ui_call(self._editor, self._update_ui)
                try:
                    self._execute(task)
                    if task.status == TaskStatus.RUNNING:
                        task.status = TaskStatus.DONE
                except Exception as exc:
                    task.status    = TaskStatus.ERROR
                    task.error_msg = str(exc)
                task.finished_at    = _time.time()
                self._current_reloc = None
                _ui_call(self._editor, self._update_ui)
                _ui_call(self._editor, self._editor._update_queue_btn)
                _ui_call(self._editor, self._editor._refresh_and_refocus, 150)
        finally:
            self._current_reloc = None
            self._reloc_running = False
            _ui_call(self._editor, self._update_ui)
            # Same lost-wakeup guard as the fast lane: a job queued (or a
            # clash answered) between "nothing to do" and the flag going down
            # was told a worker already existed.
            try:
                if not self._reloc_stop and self._next_runnable_reloc() is not None:
                    self._start_reloc_worker()
            except Exception as exc:
                _log(f"Relocator-lane restart check failed: {exc}")

    def pause_resume(self):
        self._paused = not self._paused
        if not self._paused:
            self._restored_note = ""
        self._update_ui()

    def ensure_window(self) -> "QueueWindow":
        """The queue window, created (still hidden) if it does not exist yet."""
        if not (self._window and self._window.winfo_exists()):
            self._window = QueueWindow(self._editor, self)
        return self._window

    def open_window(self, activate: bool = False):
        """Show the Task Queue window.

        The ⚡ button in the file manager owns the four states now, so "open
        it" means "lift the state to at least 1" — this never LOWERS a state
        the user picked, and *activate* no longer changes the z-order (the
        state does).  The window never takes the keyboard in any state.
        """
        try:
            ed = self._editor
            ed._set_queue_top_mode(max(QUEUE_MODE_FREE, ed._queue_top_mode()))
        except Exception as exc:
            _log(f"Task Queue could not be shown: {exc}")

    def alert_window(self):
        """Pop the Task Queue up because a task is parked and needs an answer.

        It lifts the state to at least 2 (above the file manager) so the
        question cannot sit behind the main window, and to 3 (above
        everything) when Settings ▸ General ▸ "Bring the Task Queue window to
        the FRONT" is ticked.  It never lowers a state you chose yourself, and
        it still never steals the keyboard — the arrow keys stay in the file
        manager."""
        try:
            ed   = self._editor
            want = (QUEUE_MODE_OVER_ALL
                    if ed.settings.get("queue_alert_front", False)
                    else QUEUE_MODE_OVER_FM)
            ed._set_queue_top_mode(max(want, ed._queue_top_mode()))
        except Exception as exc:
            _log(f"Task Queue could not be brought up: {exc}")

    # ── Internal execution loop ───────────────────────────────────────────

    def _enqueue(self, typ, desc, sources, dest_dir, conflict_mode, sz,
                 preflight: str = "done") -> QueueTask:
        with self._lock:
            t = QueueTask(
                task_id       = self._next_id,
                task_type     = typ,
                description   = desc,
                sources       = list(sources),
                dest_dir      = dest_dir,
                conflict_mode = conflict_mode,
                size_bytes    = sz,
            )
            self._next_id += 1
            t.preflight = preflight
            self._tasks.append(t)
        # Decide the lane BEFORE anything starts: small / instant jobs get the
        # fast lane so they never queue up behind a huge transfer.  (A job still
        # being measured gets its lane when the measurement comes back.)
        t.fast = self._classify_fast(t)
        self.smart_sort()
        self._update_ui()
        if t.fast:
            self._start_fast_worker()
        if not self._running:
            self.start(resume=False)
        return t

    @staticmethod
    def _estimate_size(sources: list) -> int:
        total = 0
        for s in sources:
            try:
                if os.path.isfile(s):
                    total += os.path.getsize(s)
                elif os.path.isdir(s):
                    for dp, _, fns in os.walk(s):
                        for fn in fns:
                            try:
                                total += os.path.getsize(os.path.join(dp, fn))
                            except Exception:
                                pass
            except Exception:
                pass
        return total

    def _run_loop(self):
        """Worker thread: execute tasks one by one."""
        while True:
            task = self._next_runnable_task()

            if task is None:
                # No runnable task — either truly empty or all remaining are blocked
                any_pending = self._next_pending_task()
                if any_pending is None:
                    # Queue fully done
                    self._running = False
                    self._space_blocked = False
                    _ui_call(self._editor, self._update_ui)
                    _ui_call(self._editor, self._editor._update_queue_btn)
                    break
                # There are pending tasks but all are blocked (space / conflicts).
                # Sleep and recheck until something unblocks.
                if not self._space_blocked:
                    self._space_blocked = True
                    _ui_call(self._editor, self._update_ui)
                    _ui_call(self._editor, self._schedule_space_recheck)
                _time.sleep(0.5)
                self.smart_sort()
                continue

            self._space_blocked = False

            # Respect pause — and 🚌 only, which holds this lane shut while
            # there is bus work that can run (revBN).
            while self._paused or self.bus_holds_main():
                _time.sleep(0.1)

            task.status = TaskStatus.RUNNING
            self._current_task = task
            self._cancel_current = False
            self._prog_start     = None
            _ui_call(self._editor, self._update_ui)

            try:
                self._execute(task)
                if task.status == TaskStatus.RUNNING:
                    task.status = TaskStatus.DONE
            except Exception as exc:
                task.status    = TaskStatus.ERROR
                task.error_msg = str(exc)

            task.finished_at = _time.time()   # wall-clock completion time
            self._current_task = None
            # This job may have been the one holding a small job's file back;
            # the fast lane closes when it finds nothing to do, so wake it.
            self._start_fast_worker()
            _ui_call(self._editor, self._update_ui)
            _ui_call(self._editor, self._editor._update_queue_btn)
            _ui_call(self._editor, self._editor._refresh_and_refocus, 150)

    def held_by(self, task: "QueueTask") -> "int | None":
        """The id of an EARLIER job holding one of this job's files, if any.

        task_id order is the order the jobs were asked for, and that is the
        order the user expects them to happen in when they are about the same
        file.  Checked at the moment of starting, not only when sorting, so
        neither lane — nor the fast lane running alongside the big one — can
        get around it.

        Caller must hold the lock (or accept a snapshot); both callers do.
        """
        for o in self._tasks:
            if o is task or o.task_id >= task.task_id:
                continue
            if o.status not in (TaskStatus.PENDING, TaskStatus.RUNNING):
                continue
            if _tasks_clash(o, task):
                return o.task_id
        return None

    def _next_pending_task(self) -> "QueueTask | None":
        """Return next runnable pending task (skip space/conflict-blocked)."""
        with self._lock:
            for t in self._tasks:
                if (t.status == TaskStatus.PENDING and not t.fast
                        and not getattr(t, "reloc", False)):
                    return t
        return None

    def _next_runnable_task(self) -> "QueueTask | None":
        """Return the next BIG task that has no blocking issues.

        Fast-lane tasks are skipped here — they belong to _run_fast_loop, which
        runs alongside this one."""
        with self._lock:
            for t in self._tasks:
                if (t.status == TaskStatus.PENDING
                        and not t.fast
                        and not getattr(t, "reloc", False)
                        and not t.space_warning
                        and getattr(t, "preflight", "done") == "done"
                        and getattr(t, "wait_until", 0.0) <= _time.time()
                        and t.conflict_mode != "pending_conflicts"
                        and self.held_by(t) is None):
                    return t
        return None

    def _execute(self, task: QueueTask):
        """Dispatch task execution on the main thread; block until done."""
        done_evt = threading.Event()

        def _run_in_main():
            try:
                if task.task_type in (TaskType.COPY, TaskType.MOVE):
                    self._run_copy_move(task, done_evt)
                elif task.task_type == TaskType.PACK:
                    self._run_pack(task, done_evt)
                elif task.task_type == TaskType.UNPACK:
                    self._run_unpack(task, done_evt)
                else:
                    done_evt.set()
            except Exception as exc:
                task.error_msg = str(exc)
                task.status    = TaskStatus.ERROR
                done_evt.set()

        # Hand the work to the main thread.  If that fails the window is on its
        # way out — release the event, or this worker would wait for a callback
        # that can never arrive and the thread would hang on shutdown.
        try:
            self._editor.after(0, _run_in_main)
        except Exception as exc:
            _log(f"Queue: could not schedule task {task.task_id}: {exc}")
            task.error_msg = "Cancelled — the program was closing"
            task.status    = TaskStatus.ERROR
            done_evt.set()
        done_evt.wait()
        # Optional hook a caller can hang on a task (revision CF: the archive
        # copy-out uses it to remove its staging folder and, for a move, to
        # delete from the zip what really arrived).  Runs on this worker thread.
        cb = getattr(task, "on_finished", None)
        if cb is not None:
            try:
                cb(task)
            except Exception as exc:
                _log(f"Queue: on_finished hook of task {task.task_id} failed: {exc}")

    # ── Per-task execution helpers (called in main thread) ────────────────

    def _backup_existing(self, path: str) -> "str | None":
        """Rename an existing file to  Backup<code>-<basekey>  in its own folder,
        reusing the same unique-per-name code pool as the standalone Backup
        rename (backup_codes.json).  Returns the new path, or None on failure.
        Used by the 'Backup-rename old' conflict resolution."""
        try:
            ed     = self._editor
            folder = os.path.dirname(path)
            name   = os.path.basename(path)
            key    = ed._backup_base_key(name)
            codes  = ed._load_backup_codes()
            code   = ed._next_backup_code(set(codes.get(key, [])))
            new_path = os.path.join(folder, f"Backup{code}-{key}")
            if os.path.exists(new_path):
                return None
            os.rename(path, new_path)
            codes.setdefault(key, [])
            if code not in codes[key]:
                codes[key].append(code)
            ed._save_backup_codes(codes)
            try:
                ed.tagstore.remap([(path, new_path)])
            except Exception:
                pass
            return new_path
        except Exception as exc:
            _log(f"Backup-old rename failed for {path}: {exc}")
            return None

    def _run_copy_move(self, task: QueueTask, done_evt: threading.Event):
        sources       = task.sources
        dest_dir      = task.dest_dir
        move          = (task.task_type == TaskType.MOVE)
        conflict_mode = task.conflict_mode
        rename_map    = dict(getattr(task, "rename_map", {}) or {})

        os.makedirs(dest_dir, exist_ok=True)
        verb  = "Moving" if move else "Copying"
        total = _count_copy_items(sources)
        prog  = _QueueProgressProxy(self, self._editor, task)

        # ── Progress in BYTES when the job is big ────────────────────────
        # It used to count FILES, so two 6 GB files meant a bar that showed
        # 1/2, then 2/2 — nothing moved for the eight minutes in between and
        # there was no speed and no ETA to look at either.  Bytes are posted
        # per block; the file count is kept for jobs of many small files,
        # where "412 / 900 files" is the more useful line.
        big_bytes  = task.size_bytes if task.size_bytes > 8 * 1024 * 1024 else 0
        bytes_done = [0]
        last_post  = [0.0]
        cur_name   = [""]

        def _on_bytes(n: int):
            bytes_done[0] += n
            now = _time.monotonic()
            # 10 posts a second is plenty; every 4 MB block on a fast SSD
            # would otherwise be a UI message.
            if now - last_post[0] >= 0.1:
                last_post[0] = now
                prog.post("progress", bytes_done[0], big_bytes,
                          cur_name[0], "bytes")

        on_bytes = _on_bytes if big_bytes else None

        # A BIG job steps aside while the fast lane is pushing a small file
        # through, so the small one gets the whole disk and finishes in the
        # blink it should take.  A fast job never yields — it IS the small one.
        #
        # With 🚌 only ticked the big job stands down for the WHOLE bus queue,
        # not just for the moment a small file slips past (revBN).  It is
        # checked here rather than only at the top of the run loop so a
        # transfer already half-way through a 9 GB file steps aside too — at
        # the next block boundary, with nothing half-written.
        if getattr(task, "reloc", False):
            def _hold():
                # The Relocator lane ignores Pause, 🚌 and the yield rules.
                # A close stops it by CANCEL (shutdown_stop), not by holding.
                return False
        elif task.fast:
            def _hold():
                # 🚌 paused stops a job that is already running IN the lane,
                # at the next block boundary — nothing half-written.
                return (self._paused
                        or (self._bus_paused and getattr(task, "bus", False)))
        else:
            def _hold():
                return (self._paused or self._big_should_yield()
                        or self.bus_holds_main())

        # Throttle settings + the moment this whole job began, so the chunked
        # copy can drop its I/O priority / cap speed / pause / cancel mid-file.
        #
        # A CALLABLE, not a snapshot: watching a 10 GB copy hold the machine
        # down and being told the switch only applies to the NEXT job is no
        # help at all.  _copy_file_chunked re-reads this twice a second.
        def thr():
            s = self._editor.settings
            return {k: s.get(k, d) for k, d in (
                ("throttle_enabled", False), ("throttle_soft_after_s", 60),
                ("throttle_soft_pct", 80), ("throttle_hard_after_s", 300),
                ("throttle_hard_pct", 60), ("throttle_batch_after_s", 600),
                ("throttle_batch_pct", 70), ("copy_chunk_kb", 4096),
                ("io_background", True), ("copy_flush_mb", 64))}
        batch_start = _time.monotonic()

        def _worker():
            cm      = conflict_mode
            # Read once, not per file: a settings lookup inside the copy loop
            # would be one dictionary hit per file for no reason.
            #
            # A RESUMED job forces it on regardless of the setting (revBN).
            # Everything it already wrote is sitting at the destination, and
            # being asked about each of those files in turn is the reason a
            # resume used to be no better than starting again.
            skip_identical = bool(
                self._editor.settings.get("conflict_skip_identical", False)
                or getattr(task, "resume_skip", False))
            counter = [0]
            abort   = [False]
            # Every file actually written, for the undo history
            recorded: list = []
            # Files that could NOT be handled, with a plain-language reason.
            # Collected instead of raising, so one locked file cannot abort a
            # 500-file job — reported together when the task finishes.
            failures: list = []
            # Locked files that were copied across, their originals queued for
            # removal once the other program lets go (DEL 49).
            deferred: list = []
            # The answer to "this file is in use", once "do the same for the
            # rest" has been ticked.  None = ask again.
            locked_mode: list = [None]

            def _ask_conflict(src, dst) -> str:
                nonlocal cm
                # Same size, same date = the same file.  With the setting
                # on it is skipped without a question at all, so copying a
                # folder you already copied asks nothing.
                if skip_identical and _same_file_enough(src, dst):
                    return _ConflictDlg.SKIP
                if cm == "ask":
                    result_list = [None]
                    evt         = threading.Event()
                    prog.post("conflict", src, dst, result_list, evt)
                    evt.wait()
                    action = result_list[0]
                    if action == _ConflictDlg.OVERWRITE_ALL:
                        cm = "overwrite_all"; action = _ConflictDlg.OVERWRITE
                    elif action == _ConflictDlg.SKIP_ALL:
                        cm = "skip_all";      action = _ConflictDlg.SKIP
                    elif action == _ConflictDlg.BACKUP_OLD_ALL:
                        cm = "backup_old";    action = _ConflictDlg.BACKUP_OLD
                    elif action == _ConflictDlg.AUTO_RENAME_ALL:
                        cm = "auto_rename";   action = _ConflictDlg.AUTO_RENAME
                    return action
                elif cm == "overwrite_all":   return _ConflictDlg.OVERWRITE
                elif cm == "skip_all":        return _ConflictDlg.SKIP
                elif cm == "auto_rename":     return _ConflictDlg.AUTO_RENAME
                elif cm == "backup_old":      return _ConflictDlg.BACKUP_OLD
                elif cm == "overwrite_older":
                    try:
                        if os.path.getmtime(src) <= os.path.getmtime(dst):
                            return _ConflictDlg.SKIP
                    except Exception:
                        pass
                    return _ConflictDlg.OVERWRITE
                return _ConflictDlg.OVERWRITE

            def _copy_one(fsrc, fdst):
                if prog.cancelled: return False
                counter[0] += 1
                cur_name[0] = fsrc
                if big_bytes:
                    prog.post("progress", bytes_done[0], big_bytes, fsrc, "bytes")
                else:
                    prog.post("progress", counter[0], total, fsrc)
                overwrote = False
                if os.path.exists(fdst):
                    action = _ask_conflict(fsrc, fdst)
                    if action == _ConflictDlg.CANCEL:
                        abort[0] = True; return False
                    if action == _ConflictDlg.SKIP:
                        return True
                    if action == _ConflictDlg.AUTO_RENAME:
                        fdst = _auto_rename_path(fdst)
                    elif action == _ConflictDlg.BACKUP_OLD:
                        # Keep the existing file, renamed Backup<code>-… , so the
                        # new file can take the original name without data loss.
                        if not self._backup_existing(fdst):
                            # Backup failed — fall back to overwriting
                            overwrote = True
                            _force_remove(fdst)
                    else:
                        # The old file is destroyed here — undo can never
                        # bring it back, so the log marks the item.
                        overwrote = True
                        # _force_remove, not a swallowed os.remove: a READ-ONLY
                        # old file made the delete fail silently, and the copy
                        # then died on the same file one step later with a
                        # "Permission denied" that named the wrong path
                        # entirely (revBI).
                        _force_remove(fdst)
                # One unusable file must never kill the whole job.  A file open
                # in another program (Cubase holding a .wav), a read-only folder
                # or a full disk raises OSError here; that is a fact about ONE
                # file, so it is written down and the rest of the batch carries
                # on.  Everything is reported together at the end.
                try:
                    os.makedirs(os.path.dirname(fdst), exist_ok=True)
                    if move and _same_drive(fsrc, fdst):
                        # Same drive → instant, safe rename (no partial state).
                        os.replace(fsrc, fdst)
                    elif move:
                        # Cross-drive MOVE = chunked COPY, then delete the source
                        # — so a Cancel just removes the half-written destination
                        # and leaves the original file untouched.  (A move never
                        # changes the file's own date.)
                        okc = _copy_file_chunked(
                            fsrc, fdst, is_cancelled=lambda: prog.cancelled,
                            is_paused=_hold, throttle=thr,
                            batch_start=batch_start, keep_date=True,
                            on_bytes=on_bytes)
                        if not okc:
                            abort[0] = True
                            return False
                        try:
                            # A read-only ORIGINAL cannot be deleted either, so
                            # a move of his read-only trees left every file
                            # behind with a warning.  Clearing the attribute is
                            # what "move it" asked for (revBI).
                            if not _force_remove(fsrc):
                                raise PermissionError(
                                    errno.EACCES, "Access is denied", fsrc)
                        except OSError as exc:
                            # The copy IS there; only the original could not be
                            # removed, so this is a warning, not a loss.
                            failures.append((fsrc, "copied, but the original "
                                             "could not be removed — "
                                             + _friendly_oserror(exc)))
                            _log(f"Move: copied but could not delete source "
                                 f"{fsrc}: {exc}")
                    else:
                        # COPY, in blocks so it can be cancelled/paused/throttled.
                        okc = _copy_file_chunked(
                            fsrc, fdst, is_cancelled=lambda: prog.cancelled,
                            is_paused=_hold, throttle=thr,
                            batch_start=batch_start,
                            keep_date=DATE_POLICY.get("copy", True),
                            on_bytes=on_bytes)
                        if not okc:
                            abort[0] = True
                            return False
                except OSError as exc:
                    # A LOCKED file during a MOVE is worth offering a way out:
                    # it can still be read, so copy it now and delete the
                    # original when its program lets go (DEL 49).
                    if move and getattr(exc, "winerror", None) in (32, 33):
                        if _handle_locked(fsrc, fdst, _friendly_oserror(exc)):
                            return True
                        if abort[0]:
                            return False
                        return True
                    # NAME THE FILE THE ERROR IS ACTUALLY ABOUT.  This line used
                    # to print the SOURCE always, while the exception carried
                    # the DESTINATION — so "Copy failed for <source>: Permission
                    # denied: '<source-looking path>'" was read, quite
                    # reasonably, as "the source is locked".  It was the
                    # destination's read-only attribute every time (revBI).
                    blamed = getattr(exc, "filename", None) or fsrc
                    where = ("" if os.path.normcase(str(blamed))
                             == os.path.normcase(fsrc)
                             else f"  (on the DESTINATION {blamed})")
                    failures.append((fsrc, _friendly_oserror(exc)
                                     + (" — on the destination file, not this one"
                                        if where else "")))
                    _log(f"{'Move' if move else 'Copy'} failed for {fsrc}: "
                         f"{exc}{where}")
                    return True        # skip this one, keep going
                recorded.append({"src": fsrc, "dst": fdst, "overwrote": overwrote})
                return True

            def _handle_locked(fsrc, fdst, reason) -> bool:
                """Ask (once) what to do with a file another program holds open.

                Returns True when the file has been dealt with.  Sets abort[0]
                when the user chooses to stop the whole job."""
                choice = locked_mode[0]
                if choice is None:
                    result = [None, False]
                    evt    = threading.Event()
                    prog.post("locked", fsrc, reason, fdst, result, evt)
                    evt.wait()
                    choice = result[0] or _LockedDlg.SKIP
                    if result[1]:                       # "do the same for the rest"
                        locked_mode[0] = choice

                if choice == _LockedDlg.ABORT:
                    abort[0] = True
                    failures.append((fsrc, reason + " — job aborted here"))
                    return False

                if choice == _LockedDlg.RETRY:
                    try:
                        os.replace(fsrc, fdst)
                        recorded.append({"src": fsrc, "dst": fdst,
                                         "overwrote": False})
                        return True
                    except OSError as exc2:
                        # Still locked.  Ask again next time rather than
                        # silently giving up on a one-off retry.
                        locked_mode[0] = None
                        failures.append((fsrc, _friendly_oserror(exc2)))
                        return True

                if choice == _LockedDlg.COPY_LATER:
                    # Most programs share READ access, which is what makes this
                    # offer work — but not all of them.  If even reading is
                    # refused, say so plainly instead of dying.
                    try:
                        okc = _copy_file_chunked(
                            fsrc, fdst, is_cancelled=lambda: prog.cancelled,
                            is_paused=_hold, throttle=thr,
                            batch_start=batch_start, keep_date=True,
                            on_bytes=on_bytes)
                    except OSError as exc3:
                        try:
                            if os.path.exists(fdst):
                                os.remove(fdst)      # drop any partial copy
                        except OSError:
                            pass
                        failures.append(
                            (fsrc, "the other program will not even allow it to "
                                   "be READ — " + _friendly_oserror(exc3)
                                   + ".  Close that program and try again"))
                        return True
                    if not okc:
                        failures.append((fsrc, "the copy was cancelled — "
                                               "the original is untouched"))
                        return True
                    # The copy is safely there; only NOW is the original queued
                    # for removal, and only ever while the copy still exists.
                    _ui_call(self._editor,
                             lambda s=fsrc, d=fdst:
                             self._editor.schedule_delete_when_unlocked(s, d))
                    recorded.append({"src": fsrc, "dst": fdst, "overwrote": False})
                    deferred.append(fsrc)
                    return True

                # SKIP
                failures.append((fsrc, reason + " — skipped"))
                return True

            def _prune_empty_dirs(root):
                """Remove empty directories bottom-up (deepest first).  Only
                truly-empty folders are removed, so any file left behind by a
                Skip keeps its folder — and the whole source tree survives if
                nothing could be moved."""
                for dirpath, _dirs, _files in os.walk(root, topdown=False):
                    try:
                        if not os.listdir(dirpath):
                            os.rmdir(dirpath)
                    except Exception:
                        pass

            def _process(src):
                # A source may be told to land under a DIFFERENT name — that is
                # how "drop the (2) suffix" and the Relocator's rules rename on
                # arrival.  Everything else keeps its own name.
                dst_name = rename_map.get(
                    os.path.normcase(os.path.abspath(src)),
                    os.path.basename(src))
                dst_root = os.path.join(dest_dir, dst_name)
                if os.path.isfile(src):
                    _copy_one(src, dst_root)
                elif os.path.isdir(src):
                    os.makedirs(dst_root, exist_ok=True)
                    for dirpath, _, fnames in os.walk(src):
                        if prog.cancelled or abort[0]: break
                        rel         = os.path.relpath(dirpath, src)
                        dst_dir_cur = os.path.join(dst_root, rel) if rel != "." else dst_root
                        os.makedirs(dst_dir_cur, exist_ok=True)
                        for fname in fnames:
                            if prog.cancelled or abort[0]: break
                            _copy_one(os.path.join(dirpath, fname),
                                      os.path.join(dst_dir_cur, fname))
                    # MOVE relocates files one by one, which leaves the source
                    # folder shell behind — delete it now, or the operation
                    # looks like a copy.  Only empty dirs are removed, so a
                    # Skipped file keeps its folder.
                    if move and not prog.cancelled and not abort[0]:
                        _prune_empty_dirs(src)

            # SAFETY NET.  Anything unexpected in here used to kill the worker
            # thread outright: the task stayed RUNNING for ever, done_evt was
            # never set, and the queue thread waited on it until the program
            # closed — one bad file could stop every later job.  Now the error
            # is recorded like any other per-file problem and the job finishes.
            try:
                for src in sources:
                    if prog.cancelled or abort[0]: break
                    _process(src)
            except Exception as exc:
                failures.append((dest_dir, "unexpected error — "
                                 + _friendly_oserror(exc)
                                 if isinstance(exc, OSError) else
                                 f"unexpected error — {exc}"))
                _log(f"{verb} aborted by an unexpected error: {exc}")
                _crash_report(type(exc), exc, exc.__traceback__,
                              f"copy/move task {task.task_id}")

            # A cancelled / aborted job is marked CANCELLED (not DONE).  The
            # run-loop only auto-marks a still-RUNNING task DONE, so setting it
            # here wins.  Whatever WAS copied before the stop is still logged
            # below, so those files can be undone.
            if prog.cancelled or abort[0]:
                task.status = TaskStatus.CANCELLED

            # Log what really happened, so it can be stepped back later
            if recorded:
                try:
                    self._editor.oplog.record(
                        "move" if move else "copy", recorded,
                        note=f"to {dest_dir}")
                except Exception as exc:
                    _log(f"Could not write the undo log: {exc}")
                # Tags are keyed by path, so a move has to take them along.
                # A copy leaves the original where it is and does NOT copy the
                # tags — the new file is a new thing until you tag it.
                if move:
                    try:
                        self._editor.tagstore.remap(
                            [(r["src"], r["dst"]) for r in recorded])
                    except Exception as exc:
                        _log(f"Could not move tags with the files: {exc}")

            # ── Tell the user what did NOT work ───────────────────────────
            # One locked or unreadable file used to take the whole job down
            # with a crash report.  Now the job finishes, and the leftovers
            # are reported together in plain language.
            if failures or deferred:
                task.failures = list(failures)
                task.deferred = list(deferred)
                bits = []
                if failures:
                    bits.append(f"{len(failures)} not {'moved' if move else 'copied'}")
                if deferred:
                    bits.append(f"{len(deferred)} copied, original waiting")
                task.error_msg = ", ".join(bits)
                if failures and task.status == TaskStatus.RUNNING:
                    task.status = TaskStatus.ERROR
                _ui_call(self._editor,
                         lambda f=list(failures), d=list(deferred),
                                v=verb, n=len(recorded):
                         self._editor.show_transfer_report(f, d, v, n))

            prog.post("done")
            done_evt.set()

        def _worker_guarded():
            """done_evt MUST be set whatever happens — the queue thread is
            blocked on it, so an unset event stalls every remaining job."""
            try:
                _worker()
            except Exception as exc:
                _log(f"Copy/move worker died: {exc}")
                try:
                    task.status    = TaskStatus.ERROR
                    task.error_msg = f"unexpected error: {exc}"
                    _crash_report(type(exc), exc, exc.__traceback__,
                                  "copy/move worker")
                except Exception:
                    pass
            finally:
                try:
                    prog.post("done")
                except Exception:
                    pass
                done_evt.set()

        threading.Thread(target=_worker_guarded, daemon=True).start()

    def _run_pack(self, task: QueueTask, done_evt: threading.Event):
        source   = task.sources[0]
        dest_dir = task.dest_dir
        zip_name = task.zip_name or (os.path.splitext(os.path.basename(source))[0] + ".zip")
        out      = os.path.join(dest_dir, zip_name)
        os.makedirs(dest_dir, exist_ok=True)

        if os.path.isdir(source):
            file_list = []
            for root, _, files in os.walk(source):
                for fn in files:
                    file_list.append(os.path.join(root, fn))
        else:
            file_list = [source]
        total = max(1, len(file_list))
        # Pass the task: a pack sent down the BUS LANE runs in the second
        # worker, and without this its progress was posted into the main
        # lane's numbers — the wrong bar, and with revBN's stricter test the
        # strip would not have been drawn at all.
        prog  = _QueueProgressProxy(self, self._editor, task)

        def _worker():
            try:
                with zipfile.ZipFile(out, "w", zipfile.ZIP_DEFLATED) as zf:
                    for n, fp in enumerate(file_list, 1):
                        if prog.cancelled: break
                        prog.post("progress", n, total, fp)
                        arcname = (os.path.relpath(fp, os.path.dirname(source))
                                   if os.path.isdir(source)
                                   else os.path.basename(fp))
                        zf.write(fp, arcname)
                if prog.cancelled:
                    try: os.remove(out)
                    except Exception: pass
            except Exception as exc:
                task.error_msg = str(exc)
                task.status    = TaskStatus.ERROR
            prog.post("done")
            done_evt.set()

        threading.Thread(target=_worker, daemon=True).start()

    def _run_unpack(self, task: QueueTask, done_evt: threading.Event):
        """Extract an archive of ANY supported format, through the queue.

        Four things this does that a plain extractall does not:
          • it waits for a set whose parts are still being downloaded, instead
            of failing on a half-arrived release;
          • it takes back exactly what a failed or cancelled run wrote, so a
            broken attempt does not leave a folder half full;
          • it can put the files in a folder of their own — unless the archive
            already makes one, which is the difference between  Film/  and
            Film/Film/ ;
          • it can clear the archive away afterwards (the whole split set), and
            mark the folder it came from as done.
        """
        s        = self._editor.settings
        archive  = task.sources[0]
        dest_dir = task.dest_dir

        # ── Is the set even complete? ────────────────────────────────────
        if (s.get("unpack_wait_enabled", True)
                and not getattr(task, "force_unpack", False)):
            try:
                ready, why = archive_parts_ready(archive)
            except Exception:
                ready, why = True, ""
            if not ready:
                try:
                    every  = max(5, int(s.get("unpack_wait_seconds", 20)))
                    give_up = max(1, float(s.get("unpack_wait_max_minutes", 60)))
                except (TypeError, ValueError):
                    every, give_up = 20, 60.0
                max_tries = max(1, int((give_up * 60) / every))
                task.wait_tries += 1
                if task.wait_tries >= max_tries:
                    task.status    = TaskStatus.ERROR
                    task.error_msg = f"gave up waiting — {why}"
                    _log(f"Unpack gave up on {archive}: {why}")
                else:
                    task.status      = TaskStatus.PENDING
                    task.wait_reason = why
                    task.wait_until  = _time.time() + every
                _ui_call(self._editor, self._update_ui)
                done_evt.set()
                return
        task.wait_reason = ""
        task.wait_until  = 0.0

        # ── Where do the files go? ───────────────────────────────────────
        target = dest_dir
        if s.get("unpack_subfolder", False):
            stem = os.path.basename(archive)
            for cut in (".tar.gz", ".tar.bz2", ".tar.xz", ".7z.001"):
                if stem.lower().endswith(cut):
                    stem = stem[:-len(cut)]
                    break
            else:
                stem = os.path.splitext(stem)[0]
                if _re.search(r"\.part\d+$", stem, _re.IGNORECASE):
                    stem = _re.sub(r"\.part\d+$", "", stem, flags=_re.IGNORECASE)
                stem = os.path.splitext(stem)[0] if stem.lower().endswith(".7z") else stem
            if stem and not _archive_makes_own_folder(archive, stem):
                target = os.path.join(dest_dir, stem)

        try:
            os.makedirs(target, exist_ok=True)
        except Exception as exc:
            task.error_msg = str(exc)
            task.status    = TaskStatus.ERROR
            done_evt.set()
            return

        # Unpacking is the lowest priority job in the program: watch the
        # keyboard and mouse so it can step aside while you work.
        try:
            if not getattr(self._editor, "_fm_input_bound", False):
                for _ev in ("<Motion>", "<Key>", "<Button>", "<MouseWheel>"):
                    self._editor.bind_all(_ev, _fm_note_input, add="+")
                self._editor._fm_input_bound = True
        except Exception:
            pass

        # Pass the task — same reason as _run_pack above: an unpack in the bus
        # lane must report into the bus lane's own numbers.
        prog   = _QueueProgressProxy(self, self._editor, task)

        def _worker():
            wrote = 0
            # The snapshot walks the whole target folder — on a big one that
            # is seconds to minutes, and it used to run HERE ON THE WINDOW
            # THREAD, which is what made the file manager lock up.
            before = _dir_snapshot(target)
            try:
                last_post = [0.0]

                def _tick(i, total, name):
                    if prog.cancelled:
                        return False
                    # At most ~4 updates a second: 50 000 tiny files used to
                    # mean 50 000 repaints of the queue window.
                    now = _time.monotonic()
                    if now - last_post[0] >= 0.25 or i >= total:
                        last_post[0] = now
                        prog.post("progress", i, max(1, total), name)
                    return True

                wrote = archive_extract(archive, target, progress=_tick,
                                        polite=_fm_be_polite)
                if prog.cancelled:
                    task.status = TaskStatus.CANCELLED
                    _dir_take_back(target, before)
                else:
                    _log(f"Unpacked {archive} → {target}  ({wrote} item(s))")
            except Exception as exc:
                # A cancel travels out of archive_extract as an exception too —
                # that is a stop, not a fault.
                if prog.cancelled:
                    task.status = TaskStatus.CANCELLED
                else:
                    task.error_msg = str(exc)
                    task.status    = TaskStatus.ERROR
                # A half-written folder is worse than none: take back exactly
                # what this attempt put there, and nothing else.
                _dir_take_back(target, before)
            prog.post("done")

            if task.status not in (TaskStatus.ERROR, TaskStatus.CANCELLED):
                _ui_call(self._editor,
                         lambda: self._editor._after_unpack(task, archive, target))
            done_evt.set()

        threading.Thread(target=_worker, daemon=True).start()

    def _proxy_progress(self, cur: int, total: int, filename: str,
                        unit: str = "files", task=None):
        """Called by _QueueProgressProxy to update inline progress in QueueWindow.

        Two lanes, two sets of numbers.  A fast / bus job posts into the
        _fprog_* fields so the big transfer's bar and ETA stay its own; with
        one shared set the bar flipped between the two jobs ten times a second
        and neither reading meant anything.
        """
        # The Relocator lane posts nothing to either strip: two bars are one
        # too many already, and its own ⤴ "running" window says what it is at.
        if task is not None and getattr(task, "reloc", False):
            return
        fast = bool(getattr(task, "fast", False)) if task is not None else False
        now  = _time.monotonic()
        if fast:
            # Three sets of numbers (revision CL): main, ⚡ and 🚌.
            p = "_bprog_" if getattr(task, "bus", False) else "_fprog_"
            g = lambda n: getattr(self, p + n)
            s = lambda n, v: setattr(self, p + n, v)
            if cur > 0 and g("start") is None:
                s("start", now)
            if cur == 0 and total == 0:   # "done" signal
                s("cur", 0)
                s("total", 0)
                s("file", "")
                s("start", None)
                s("unit", "files")
                s("rate", 0.0)
                s("seen", None)
                s("win", [None, 0, 0.0])
            else:
                if cur > g("cur"):
                    s("seen", now)
                s("cur", cur)
                s("total", max(1, total))
                s("file", filename)
                s("unit", unit)
                if unit == "bytes":
                    s("rate", self._roll_rate(g("win"), cur, now))
            self._update_ui()
            return
        if cur > 0 and self._prog_start is None:
            self._prog_start = now
        if cur == 0 and total == 0:   # "done" signal
            self._prog_cur   = 0
            self._prog_total = 0
            self._prog_file  = ""
            self._prog_start = None
            self._prog_unit  = "files"
            self._prog_rate  = 0.0
            self._prog_seen  = None
            self._prog_win   = [None, 0, 0.0]
        else:
            if cur > self._prog_cur:
                self._prog_seen = now
            self._prog_cur   = cur
            self._prog_total = max(1, total)
            self._prog_file  = filename
            self._prog_unit  = unit
            if unit == "bytes":
                self._prog_rate = self._roll_rate(self._prog_win, cur, now)
        self._update_ui()

    @staticmethod
    def _roll_rate(win: list, cur: int, now: float, span: float = 6.0) -> float:
        """Bytes per second over the last few seconds, not since the year dot.

        `win` is a 3-list [anchor time, anchor bytes, last rate] kept by the
        caller.  The reading is refreshed once a second and the anchor slides
        forward every `span`, so the number follows what the disk is doing now
        — and, crucially, FALLS TO ZERO when nothing is being written.  A
        cumulative average cannot do that: it only sags, which is why a copy
        that had been dead for half an hour still claimed 1 MB/s.
        """
        if win[0] is None:
            win[0], win[1], win[2] = now, cur, 0.0
            return 0.0
        dt = now - win[0]
        if dt >= 1.0:
            win[2] = max(0.0, (cur - win[1]) / dt)
            if dt >= span:                 # slide the window along
                win[0], win[1] = now, cur
        return win[2]

    def lane_stalled_for(self, fast=False) -> float:
        """Seconds since this lane last moved a byte (0.0 when it is moving).

        Only meaningful while a byte-counted job is running; the caller checks
        that.  This is what turns "it seems to stand still" into a number.
        fast: False = main lane, True = the ⚡ lane, "bus" = the 🚌 lane.
        """
        seen = (self._bprog_seen if fast == "bus"
                else self._fprog_seen if fast else self._prog_seen)
        if seen is None:
            return 0.0
        return max(0.0, _time.monotonic() - seen)

    def _schedule_space_recheck(self, interval_ms: int = 15_000):
        """Schedule a space recheck every *interval_ms* ms while space-blocked.
        Called from the main thread only.
        """
        if self._space_recheck_id is not None:
            try:
                self._editor.after_cancel(self._space_recheck_id)
            except Exception:
                pass
        if self._space_blocked:
            self._space_recheck_at = _time.monotonic() + interval_ms / 1000.0
            self._space_recheck_id = self._editor.after(
                interval_ms, self._do_space_recheck
            )
            self._update_ui()   # update countdown display immediately

    def _do_space_recheck(self):
        """Main-thread callback: re-run smart_sort to refresh space warnings."""
        self._space_recheck_id = None
        if not self._space_blocked:
            return
        self.smart_sort()
        self._update_ui()
        # If still blocked, reschedule
        if self._space_blocked:
            self._schedule_space_recheck()

    def space_recheck_now(self):
        """Called by QueueWindow Refresh button."""
        if self._space_recheck_id is not None:
            try:
                self._editor.after_cancel(self._space_recheck_id)
            except Exception:
                pass
            self._space_recheck_id = None
        self.smart_sort()
        self._update_ui()
        if self._space_blocked:
            self._schedule_space_recheck()

    def _update_ui(self):
        """Refresh queue window + toolbar button (always call from main thread)."""
        try:
            if self._window and self._window.winfo_exists():
                self._window.refresh()
            self._editor._update_queue_btn()
        except Exception:
            pass
        # The queue outlives the program now, so every change to it is written
        # out — debounced, see save_state_soon.
        try:
            self.save_state_soon()
        except Exception:
            pass


# ══════════════════════════════════════════════════════════════════════════
#  🖴 Disk information  —  right-click a tab  (revision BO)
# ══════════════════════════════════════════════════════════════════════════
#
# "vilket format" first, because that is the question that gets asked and the
# one nothing in the program could answer.  It is the biggest line on the
# window for that reason.  Everything else is read-only fact about the volume
# and, when PowerShell will say (it takes seconds, so it arrives on a thread),
# about the hardware underneath it.

class _DiskInfoDlg(tk.Toplevel):
    """Everything this machine will say about the disk behind a tab."""

    def __init__(self, parent, path: str):
        super().__init__(parent)
        self._parent = parent
        drv = ""
        try:
            drv = os.path.splitdrive(os.path.abspath(path))[0]
        except Exception:
            pass
        self._letter = drv[:1].upper()
        self._vol   = (self._letter + ":\\") if self._letter else path
        title = f"Disk information — {self._letter}:" if self._letter else "Disk information"
        _setup_toplevel(self, title, parent, modal=False)
        self.configure(bg=C_BG)
        self.minsize(620, 460)
        try:
            self.geometry("720x600")
        except Exception:
            pass

        # Buttons FIRST, from the bottom — a row packed after an expanding
        # widget gets one pixel and disappears.
        bot = ttk.Frame(self)
        bot.pack(side="bottom", fill="x", padx=10, pady=10)
        ttk.Button(bot, text="Close", width=10,
                   command=self.destroy).pack(side="right", padx=2)
        ttk.Button(bot, text="📋 Copy all", width=13,
                   command=self._copy_all).pack(side="right", padx=2)
        self._btn_fmt = ttk.Button(bot, text="🧨 Format this disk…", width=22,
                                   command=self._on_format)
        self._btn_fmt.pack(side="left", padx=2)
        why = _format_is_forbidden(self._letter)
        if why:
            self._btn_fmt.configure(state="disabled")
            tk.Label(bot, text=f"Formatting is refused: {why}", bg=self["bg"],
                     fg="#ffb86c", font=("Segoe UI", 8), anchor="w"
                     ).pack(side="left", padx=10)

        # ── The answer to the question that gets asked ───────────────────
        v = _volume_info(self._vol)
        head = tk.Frame(self, bg=C_BG3, padx=12, pady=10)
        head.pack(fill="x", padx=10, pady=(10, 4))
        k = _drive_kind_info(self._vol)
        name = v["label"] or "(no label)"
        tk.Label(head, text=f"{k['icon']}  {self._letter}:   {name}",
                 bg=C_BG3, fg=C_FG, font=("Segoe UI", 11, "bold"),
                 anchor="w").pack(fill="x")
        tk.Label(head, text=(v["fs"] or "unreadable").upper(),
                 bg=C_BG3, fg=C_ACCENT, font=("Segoe UI", 22, "bold"),
                 anchor="w").pack(fill="x")
        note = _FS_NOTES.get((v["fs"] or "").upper(), "")
        if note:
            tk.Label(head, text=note, bg=C_BG3,
                     fg=("#ffe066" if note.startswith("⚠") else C_FG_DIM),
                     font=("Segoe UI", 8), anchor="w", justify="left",
                     wraplength=660).pack(fill="x", pady=(2, 0))

        # ── The rest, as text that can be selected and copied ────────────
        frm = ttk.Frame(self)
        frm.pack(fill="both", expand=True, padx=10, pady=(4, 0))
        vsb = ttk.Scrollbar(frm, orient="vertical")
        vsb.pack(side="right", fill="y")
        # state="disabled" so there is no caret to blink in a read-only box.
        self._txt = tk.Text(frm, wrap="word", bg=C_BG2, fg=C_FG,
                            insertwidth=0, relief="flat",
                            font=("Consolas", 9), yscrollcommand=vsb.set)
        self._txt.pack(fill="both", expand=True)
        vsb.configure(command=self._txt.yview)
        self._txt.tag_configure("h", foreground=C_ACCENT,
                                font=("Segoe UI", 9, "bold"), spacing1=8)
        self._txt.tag_configure("warn", foreground="#ffe066")

        self._body = self._compose(v)
        self._fill(self._body)

        # The hardware underneath takes seconds (PowerShell storage cmdlets),
        # so it arrives on a thread and is appended when it lands.  The window
        # is usable the whole time.
        threading.Thread(target=self._load_physical, daemon=True).start()

    # ── Content ──────────────────────────────────────────────────────────

    def _compose(self, v: dict) -> str:
        c = _cluster_info(self._vol)
        k = _drive_kind_info(self._vol)
        L = []
        L.append(("h", "VOLUME"))
        L.append(("", f"  Letter               {self._letter}:"))
        L.append(("", f"  Label                {v['label'] or '—'}"))
        L.append(("", f"  File system          {v['fs'] or '—'}"))
        L.append(("", f"  Serial number        {v['serial'] or '—'}"))
        L.append(("", f"  Drive type           {k['kind']}"))
        L.append(("", f"  Longest name         {v['max_component'] or '—'} characters"))
        if v["readonly"]:
            L.append(("warn", "  ⚠  This volume is READ-ONLY"))

        try:
            du = shutil.disk_usage(self._vol)
            used = du.total - du.free
            pct = (used / du.total * 100.0) if du.total else 0.0
            bar_n = int(pct / 5)
            L.append(("h", "SPACE"))
            L.append(("", f"  Total                {_fmt_size(du.total)}"
                          f"   ({du.total:,} bytes)"))
            L.append(("", f"  Used                 {_fmt_size(used)}   ({pct:.1f} %)"))
            L.append(("", f"  Free                 {_fmt_size(du.free)}"
                          f"   ({du.free:,} bytes)"))
            L.append(("", "  " + "█" * bar_n + "░" * (20 - bar_n) + f"  {pct:.0f} %"))
        except Exception:
            L.append(("h", "SPACE"))
            L.append(("", "  (could not be read)"))

        if c["cluster"]:
            L.append(("h", "GEOMETRY"))
            L.append(("", f"  Allocation unit      {_fmt_size(c['cluster'])}"
                          f"   ({c['cluster']:,} bytes per cluster)"))
            L.append(("", f"  Bytes per sector     {c['sector']:,}"))
            L.append(("", f"  Clusters total       {c['clusters_total']:,}"))
            L.append(("", f"  Clusters free        {c['clusters_free']:,}"))

        if v["flags"]:
            L.append(("h", "WHAT THIS FILE SYSTEM SUPPORTS"))
            for f in v["flags"]:
                mark = "⚠" if f.startswith("READ-ONLY") else "·"
                L.append(("warn" if mark == "⚠" else "",
                          f"  {mark}  {f}"))

        boot = _looks_bootable(self._vol)
        if boot:
            L.append(("h", "BOOT"))
            L.append(("warn", f"  ⚠  This disk carries {boot}."))

        L.append(("h", "HARDWARE"))
        L.append(("", "  reading…   (the storage cmdlets take a few seconds)"))
        return L

    def _fill(self, lines):
        self._txt.configure(state="normal")
        self._txt.delete("1.0", "end")
        for tag, text in lines:
            self._txt.insert("end", text + "\n", tag or ())
        self._txt.configure(state="disabled")

    def _load_physical(self):
        data = _physical_disk_info(self._letter)
        _ui_call(self._parent, lambda: self._show_physical(data))

    def _show_physical(self, d: dict):
        if not self.winfo_exists():
            return
        lines = [ln for ln in self._body if ln[1].strip() !=
                 "reading…   (the storage cmdlets take a few seconds)"]
        if not d:
            lines.append(("", "  (Windows would not say — the storage cmdlets "
                              "are missing or refused)"))
        else:
            pretty = [
                ("Model", "Model"), ("Serial", "Disk serial"),
                ("Bus", "Connected by"), ("Media", "Media"),
                ("Spindle", "Spindle speed"), ("DiskSize", "Disk size"),
                ("DiskNumber", "Disk number"), ("PartStyle", "Partition style"),
                ("PartNumber", "Partition"), ("PartSize", "Partition size"),
                ("PartOffset", "Partition offset"), ("PartType", "Partition type"),
                ("DiskHealth", "Disk health"), ("PdHealth", "Physical health"),
                ("VolHealth", "Volume health"), ("Boot", "Is the boot disk"),
                ("System", "Is the system disk"),
                ("BitLocker", "BitLocker"), ("BitLockerPct", "Encrypted %"),
            ]
            for key, label in pretty:
                val = str(d.get(key, "")).strip()
                if not val:
                    continue
                if key in ("DiskSize", "PartSize", "PartOffset"):
                    try:
                        val = f"{_fmt_size(int(val))}   ({int(val):,} bytes)"
                    except Exception:
                        pass
                if key == "Spindle" and val in ("0", "4294967295"):
                    val = "—  (no spinning platter)"
                warn = (key in ("Boot", "System") and val.lower() == "true")
                lines.append(("warn" if warn else "",
                              f"  {label:20} {val}"))
        self._body = lines
        self._fill(lines)

    def _copy_all(self):
        try:
            txt = self._txt.get("1.0", "end-1c")
            head = (f"{self._letter}:  {_volume_info(self._vol)['label']}\n"
                    f"File system: {_volume_info(self._vol)['fs']}\n\n")
            _to_clipboard(head + txt)
        except Exception as exc:
            _log(f"Disk info could not be copied: {exc}")

    def _on_format(self):
        why = _format_is_forbidden(self._letter)
        if why:
            return
        _FormatStep1Dlg(self._parent, self._letter)


# ══════════════════════════════════════════════════════════════════════════
#  🧨 Format  —  first WHAT IS THERE, then WHAT IT BECOMES  (revision BP)
# ══════════════════════════════════════════════════════════════════════════
#
# The first cut had the two warnings the other way round and moved the buttons
# about to stop a double-click landing on both.  His redesign is better and it
# is what is built here:
#
#   Window 1  —  WHAT YOU ARE ABOUT TO ERASE.  The drive, and the first ten
#                folders on it, right there in the first window.  A letter says
#                nothing; ten folder names say instantly which disk this is.
#   Window 2  —  WHAT IT SHOULD BECOME.  NOTHING IS PRESELECTED.  No default
#                file system, so the button cannot be reached without a
#                deliberate choice — which is a better guard than moving the
#                buttons ever was, and it lets Continue / Abort sit where
#                buttons normally sit.
#
# Each choice explains itself: what it is for, and the limit that actually
# bites (FAT32 refusing a 4 GB file is the one that catches people out).

# (name, one-line purpose, [facts], warning or "")
_FMT_CHOICES = [
    ("NTFS", "Windows' own — the right answer for anything only Windows touches",
     ["No practical file-size limit (16 TB per file)",
      "Permissions, journalling, compression, hard links",
      "macOS reads it but will not write it without extra software",
      "Use for: internal disks, backup disks, big transfers"],
     ""),
    ("exFAT", "For flash, and for sharing a disk between machines",
     ["No practical file-size limit either (far past 4 GB)",
      "Read AND written by Windows, macOS, Linux, most TVs and cameras",
      "No permissions and NO JOURNAL — a bad unplug can lose the directory",
      "Use for: USB sticks and external disks that visit other machines"],
     "Always eject it properly.  There is no journal to repair it with."),
    ("FAT32", "Only when something old insists on it",
     ["⚠  A single file may not exceed 4 GB — that is most films and most "
      "disk images",
      "Windows' own tool will not make one bigger than 32 GB",
      "No permissions, no journal",
      "Use for: old car stereos, cameras, BIOS/UEFI boot sticks"],
     "The 4 GB limit is per FILE, not per disk, and it fails mid-copy."),
    ("ReFS", "Specialist — checksums and block cloning",
     ["Detects and repairs silent corruption on mirrored storage",
      "Windows only, and nothing boots from it",
      "No compression, no EFS encryption, no removable media",
      "Use for: large data volumes where bit rot is the worry"],
     "Not every Windows edition will format ReFS; it will say so if it cannot."),
]


class _FormatStep1Dlg(tk.Toplevel):
    """Window one — WHAT IS ON IT.  Identify the disk before anything else."""

    def __init__(self, parent, letter: str):
        super().__init__(parent)
        self._parent = parent
        self._letter = letter.upper()[:1]
        self._vol    = self._letter + ":\\"
        _setup_toplevel(self, f"Format {self._letter}:  —  what is on it",
                        parent, modal=True)
        self.configure(bg=C_BG)
        self.minsize(540, 460)

        v    = _volume_info(self._vol)
        k    = _drive_kind_info(self._vol)
        boot = _looks_bootable(self._vol)
        names, nfold, nfile = _top_level_entries(self._vol, 10)
        try:
            du  = shutil.disk_usage(self._vol)
            cap = (f"{_fmt_size(du.total)}   "
                   f"({_fmt_size(du.total - du.free)} in use)")
        except Exception:
            cap = "unknown"

        # Buttons FIRST, from the bottom — a row packed after an expanding
        # widget is given one pixel and disappears.
        bot = ttk.Frame(self)
        bot.pack(side="bottom", fill="x", padx=14, pady=14)
        ttk.Button(bot, text="Continue  ▶", width=16,
                   command=self._go).pack(side="right", padx=(6, 0))
        cancel = ttk.Button(bot, text="Cancel", width=12, command=self.destroy)
        cancel.pack(side="right")
        cancel.focus_set()              # the safe answer owns the keyboard
        self.bind("<Escape>", lambda e: self.destroy())

        box = tk.Frame(self, bg="#3a1a1a", padx=16, pady=12)
        box.pack(fill="x", padx=14, pady=(14, 8))
        tk.Label(box, text="🧨  FORMAT — this erases everything on the disk",
                 bg="#3a1a1a", fg="#ff8888", font=("Segoe UI", 12, "bold"),
                 anchor="w").pack(fill="x")
        tk.Label(box, text="There is no undo.  Nothing goes to the trash.",
                 bg="#3a1a1a", fg="#ffb0b0", font=("Segoe UI", 9),
                 anchor="w").pack(fill="x", pady=(2, 0))
        if boot:
            tk.Label(box, text=f"⚠  This disk carries {boot}.  Formatting it "
                               f"will stop that booting.",
                     bg="#3a1a1a", fg="#ffe066", font=("Segoe UI", 9, "bold"),
                     anchor="w", justify="left", wraplength=500
                     ).pack(fill="x", pady=(6, 0))

        grid = tk.Frame(self, bg=C_BG)
        grid.pack(fill="x", padx=20, pady=(4, 6))
        for r, (lbl, val) in enumerate((
                ("Drive", f"{self._letter}:"),
                ("Label", v["label"] or "(no label)"),
                ("File system now", v["fs"] or "unreadable"),
                ("Type", k["kind"]),
                ("Capacity", cap))):
            tk.Label(grid, text=lbl, bg=C_BG, fg=C_FG_DIM, font=("Segoe UI", 9),
                     anchor="e", width=16).grid(row=r, column=0, sticky="e",
                                                pady=1)
            tk.Label(grid, text=val, bg=C_BG, fg=C_FG,
                     font=("Segoe UI", 9, "bold"), anchor="w"
                     ).grid(row=r, column=1, sticky="w", padx=8, pady=1)

        # ── What is on it.  THE POINT OF THIS WINDOW ─────────────────────
        if nfold < 0:
            head_txt = "The top level of this drive could not be read."
        elif nfold == 0 and nfile == 0:
            head_txt = "This drive is EMPTY — nothing at the top level at all."
        else:
            head_txt = (f"{nfold} folders and {nfile} loose files at the top "
                        f"level.  The first {min(10, nfold)}:"
                        if nfold else
                        f"No folders, but {nfile} loose files at the top level.")
        tk.Label(self, text=head_txt, bg=C_BG, fg=C_FG,
                 font=("Segoe UI", 9, "bold"), anchor="w", justify="left",
                 wraplength=500).pack(fill="x", padx=20, pady=(6, 2))

        lst = tk.Frame(self, bg=C_BG3, padx=14, pady=8)
        lst.pack(fill="both", expand=True, padx=20, pady=(0, 6))
        if names:
            for n in names:
                tk.Label(lst, text=f"   📁  {n}", bg=C_BG3, fg=C_FG,
                         font=("Consolas", 10), anchor="w").pack(fill="x")
            if nfold > len(names):
                tk.Label(lst, text=f"   … and {nfold - len(names)} more folders",
                         bg=C_BG3, fg=C_FG_DIM, font=("Segoe UI", 9),
                         anchor="w").pack(fill="x", pady=(4, 0))
        else:
            # An empty disk is a perfectly ordinary thing to be formatting and
            # must not look like a failure — it used to print nothing at all.
            tk.Label(lst, text=("   (nothing here — this drive is empty)"
                                if nfold == 0 else
                                "   (the folder list could not be read)"),
                     bg=C_BG3, fg=C_FG_DIM, font=("Segoe UI", 9),
                     anchor="w").pack(fill="x")

        tk.Label(self, text="Next you choose what it should be formatted TO.  "
                            "Nothing happens until then.",
                 bg=C_BG, fg=C_FG_DIM, font=("Segoe UI", 8), anchor="w",
                 justify="left", wraplength=500).pack(fill="x", padx=20)

    def _go(self):
        parent, letter = self._parent, self._letter
        self.destroy()                  # let go of the grab before the next one
        parent.after(60, lambda: _FormatStep2Dlg(parent, letter))


class _FormatStep2Dlg(tk.Toplevel):
    """Window two — WHAT IT BECOMES.  Nothing is preselected, on purpose."""

    def __init__(self, parent, letter: str):
        super().__init__(parent)
        self._parent = parent
        self._letter = letter.upper()[:1]
        self._vol    = self._letter + ":\\"
        _setup_toplevel(self, f"Format {self._letter}:  —  format it as what?",
                        parent, modal=True)
        self.configure(bg=C_BG)
        self.minsize(640, 620)

        # NOTHING PRESELECTED.  This is the guard now: Continue stays dead
        # until a file system is actually chosen, so no amount of clicking
        # through can format a disk as something nobody picked.
        self._fs = tk.StringVar(value="")

        # Buttons where buttons normally go — bottom right, Cancel on the safe
        # side of Continue.  They can sit there because the choice above is the
        # thing standing in the way, not their position.
        bot = ttk.Frame(self)
        bot.pack(side="bottom", fill="x", padx=14, pady=12)
        self._btn_go = ttk.Button(bot, text="Format now", width=16,
                                  command=self._do_format, state="disabled")
        self._btn_go.pack(side="right", padx=(6, 0))
        abort = ttk.Button(bot, text="Abort", width=12, command=self.destroy)
        abort.pack(side="right")
        abort.focus_set()
        self.bind("<Escape>", lambda e: self.destroy())
        self._hint = tk.Label(bot, text="Choose a file system first ↑",
                              bg=self["bg"], fg="#ffe066",
                              font=("Segoe UI", 9, "bold"), anchor="w")
        self._hint.pack(side="left", padx=(4, 0))

        self._status = tk.Label(self, text="", bg=C_BG, fg=C_FG_DIM,
                                font=("Segoe UI", 9), anchor="w",
                                justify="left", wraplength=600)
        self._status.pack(side="bottom", fill="x", padx=20, pady=(0, 8))

        v = _volume_info(self._vol)
        tk.Label(self, text=f"🧨  {self._letter}:   "
                            f"{v['label'] or '(no label)'}   ·   currently "
                            f"{v['fs'] or 'unreadable'}",
                 bg=C_BG, fg="#ff8888", font=("Segoe UI", 11, "bold"),
                 anchor="w").pack(fill="x", padx=20, pady=(14, 2))
        tk.Label(self, text="What should it become?  Pick one — there is no "
                            "default, deliberately.",
                 bg=C_BG, fg=C_FG_DIM, font=("Segoe UI", 9), anchor="w"
                 ).pack(fill="x", padx=20, pady=(0, 8))

        # ── The choices, each explaining itself ──────────────────────────
        for name, purpose, facts, warn in _FMT_CHOICES:
            card = tk.Frame(self, bg=C_BG3, padx=12, pady=8)
            card.pack(fill="x", padx=20, pady=3)
            rb = tk.Radiobutton(
                card, text=name, value=name, variable=self._fs,
                bg=C_BG3, fg=C_FG, selectcolor=C_BG2, activebackground=C_BG3,
                activeforeground=C_FG, font=("Segoe UI", 10, "bold"),
                anchor="w", command=self._chosen)
            rb.pack(anchor="w")
            tk.Label(card, text=purpose, bg=C_BG3, fg=C_ACCENT,
                     font=("Segoe UI", 8), anchor="w", justify="left",
                     wraplength=560).pack(fill="x", padx=(24, 0))
            for f in facts:
                tk.Label(card, text=f"·  {f}", bg=C_BG3,
                         fg=("#ffe066" if f.startswith("⚠") else C_FG_DIM),
                         font=("Segoe UI", 8), anchor="w", justify="left",
                         wraplength=560).pack(fill="x", padx=(30, 0))
            if warn:
                tk.Label(card, text=f"⚠  {warn}", bg=C_BG3, fg="#ffb86c",
                         font=("Segoe UI", 8, "bold"), anchor="w",
                         justify="left", wraplength=560
                         ).pack(fill="x", padx=(24, 0), pady=(3, 0))

        # ── Label and quick/full ─────────────────────────────────────────
        opt = tk.Frame(self, bg=C_BG)
        opt.pack(fill="x", padx=20, pady=(10, 4))
        tk.Label(opt, text="New label:", bg=C_BG, fg=C_FG_DIM,
                 font=("Segoe UI", 9)).pack(side="left")
        self._label = tk.Entry(opt, width=22, insertofftime=0,
                               insertontime=9999999)
        self._label.pack(side="left", padx=(6, 14))
        self._label.insert(0, v["label"] or "")
        self._quick = tk.BooleanVar(value=True)
        tk.Checkbutton(opt, text="Quick format  (full also overwrites every "
                                 "sector — hours on a big disk)",
                       variable=self._quick, bg=C_BG, fg=C_FG,
                       selectcolor=C_BG3, activebackground=C_BG,
                       activeforeground=C_FG, font=("Segoe UI", 8)
                       ).pack(side="left")

    def _chosen(self):
        """A file system has been picked — only now is the button reachable."""
        if self._fs.get():
            self._btn_go.configure(state="normal")
            self._hint.configure(
                text=f"{self._letter}: will be erased and made {self._fs.get()}",
                fg="#ff8888")

    def _do_format(self):
        fs = self._fs.get()
        if not fs:                      # cannot happen; cheap to be sure
            return
        # Checked AGAIN at the moment of doing it, not only when the menu was
        # built: a drive can be unplugged, or become the system drive, between
        # the right-click and this click.
        why = _format_is_forbidden(self._letter)
        if why:
            self._status.configure(text=f"⛔  Refused: {why}", fg="#ff8888")
            self._btn_go.configure(state="disabled")
            return
        label = self._label.get().strip()[:32]
        quick = bool(self._quick.get())
        self._btn_go.configure(state="disabled")
        self._status.configure(
            text=f"Formatting {self._letter}: as {fs}…  this window will say "
                 f"when it is done.", fg="#ffe066")
        _log(f"FORMAT requested: {self._letter}: as {fs}, quick={quick}, "
             f"label={label!r}")
        threading.Thread(target=self._run_format,
                         args=(fs, label, quick), daemon=True).start()

    def _run_format(self, fs: str, label: str, quick: bool):
        cmd = (f"Format-Volume -DriveLetter {self._letter} "
               f"-FileSystem {fs} -Confirm:$false -Force")
        if label:
            cmd += f" -NewFileSystemLabel '{label.replace(chr(39), chr(39) * 2)}'"
        cmd += " -Full:$false" if quick else " -Full"
        script = ("$ErrorActionPreference='Stop'; try{" + cmd +
                  " | Out-Null; 'OK' } catch { 'ERR ' + $_.Exception.Message }")
        out = ""
        try:
            res = subprocess.run(
                [_ps_exe(), "-NoProfile", "-NonInteractive", "-Command", script],
                capture_output=True, text=True, timeout=7200,
                creationflags=getattr(subprocess, "CREATE_NO_WINDOW", 0))
            out = ((res.stdout or "") + (res.stderr or "")).strip()
        except subprocess.TimeoutExpired:
            out = "ERR the format did not finish within two hours"
        except Exception as exc:
            out = f"ERR {exc}"
        _log(f"FORMAT {self._letter}: result -> {out[:300]}")
        _ui_call(self._parent, lambda: self._done(out))

    def _done(self, out: str):
        if not self.winfo_exists():
            return
        _FREE_SPACE_CACHE.clear()
        _PHYS_CACHE.pop(self._letter, None)
        # A format is the one thing that DOES change a drive's file system, so
        # this is where the status bar's cached answer has to go.
        _FS_NAME_CACHE.pop(os.path.normcase(self._vol), None)
        if out.startswith("OK"):
            v = _volume_info(self._vol)
            self._status.configure(
                text=f"✅  {self._letter}: is now {v['fs'] or '?'}"
                     f"  ·  label {v['label'] or '(none)'}", fg="#77dd77")
            self._hint.configure(text="Done", fg="#77dd77")
        else:
            self._status.configure(
                text=f"⛔  It did not happen: {out[3:].strip() or out}",
                fg="#ff8888")
            try:
                self._btn_go.configure(state="normal")
            except Exception:
                pass
        try:
            self._parent.refresh_panels()
        except Exception:
            pass


# ══════════════════════════════════════════════════════════════════════════
#  🗃 Queues  —  park a queue under a name, pick it up later  (revision BN)
# ══════════════════════════════════════════════════════════════════════════
#
# The automatic file (task_queue.json) already carries whatever is unfinished
# across a close, and empties itself only when the work is really done.  This
# is the deliberate version of the same thing: "pausa och spara en queue … och
# ladda in och resume senare".  One JSON file per saved queue, the SAME record
# format, so a saved queue and a carried-over one come back through the same
# code and behave identically.

class _QueueStoreDlg(tk.Toplevel):
    """Save the queue under a name; load one back, paused, as a resume."""

    def __init__(self, parent: "QueueWindow", mgr: "TaskQueueManager"):
        super().__init__(parent)
        self._mgr    = mgr
        self._parent = parent
        _setup_toplevel(self, "Queues", parent, modal=True)
        self.configure(bg=C_BG)
        self.resizable(True, True)
        self.minsize(560, 380)
        try:
            self.geometry("640x460")
        except Exception:
            pass

        picked = parent._get_selected_tids()
        n_all  = len(mgr.unfinished())
        self._picked = list(picked)

        # ── Save ──────────────────────────────────────────────────────────
        top = tk.Frame(self, bg=C_BG3, padx=10, pady=8)
        top.pack(fill="x", padx=8, pady=(8, 4))
        tk.Label(top, text="💾  Save this queue as:", bg=C_BG3, fg=C_ACCENT,
                 font=("Segoe UI", 9, "bold")).pack(anchor="w")
        row = tk.Frame(top, bg=C_BG3)
        row.pack(fill="x", pady=(4, 0))
        # insertofftime/insertontime: the caret must not BLINK — see _ask_text.
        self._qname = tk.Entry(row, insertofftime=0, insertontime=9999999)
        self._qname.pack(side="left", fill="x", expand=True)
        self._qname.insert(0, datetime.now().strftime("Queue %Y-%m-%d %H%M"))
        self._qname.select_range(0, "end")
        self._qname.bind("<Return>", lambda e: (self._on_save(), "break")[1])
        ttk.Button(row, text="💾 Save", width=10,
                   command=self._on_save).pack(side="left", padx=(6, 0))
        what = (f"the {len(picked)} picked job(s)" if picked
                else f"all {n_all} unfinished job(s)")
        tk.Label(top, text=f"Saves {what}.  They stay in the queue — saving is "
                           f"not removing.",
                 bg=C_BG3, fg=C_FG_DIM, font=("Segoe UI", 8),
                 anchor="w", justify="left").pack(fill="x", pady=(4, 0))

        # ── Buttons FIRST, from the bottom ────────────────────────────────
        # A row packed after an expanding list gets one pixel and vanishes —
        # which is how the Task Queue's own button row once disappeared.
        bot = ttk.Frame(self)
        bot.pack(side="bottom", fill="x", padx=8, pady=8)
        ttk.Button(bot, text="📂 Load (paused)", width=17,
                   command=self._on_load).pack(side="left", padx=2)
        ttk.Button(bot, text="🗑 Delete", width=11,
                   command=self._on_delete).pack(side="left", padx=2)
        ttk.Button(bot, text="Close", width=10,
                   command=self.destroy).pack(side="right", padx=2)
        self._resume_var = tk.BooleanVar(value=True)
        tk.Checkbutton(
            bot, text="Resume: skip files already copied",
            variable=self._resume_var, bg=self["bg"], fg=C_FG,
            selectcolor=C_BG3, activebackground=self["bg"],
            activeforeground=C_FG, font=("Segoe UI", 8), takefocus=0,
        ).pack(side="left", padx=(12, 0))

        self._lbl = tk.Label(self, text="", bg=C_BG, fg=C_FG_DIM,
                             font=("Segoe UI", 8), anchor="w")
        self._lbl.pack(side="bottom", fill="x", padx=12)

        # ── The saved queues ──────────────────────────────────────────────
        tk.Label(self, text="📂  Saved queues", bg=C_BG, fg=C_ACCENT,
                 font=("Segoe UI", 9, "bold"), anchor="w").pack(
                     fill="x", padx=12, pady=(6, 2))
        frm = ttk.Frame(self)
        frm.pack(fill="both", expand=True, padx=8, pady=(0, 4))
        cols = ("name", "jobs", "size", "when")
        # Scrollbar BEFORE the tree: packed the other way round it comes out
        # one pixel wide (the packer gives the expanding widget everything).
        self._tree = ttk.Treeview(frm, columns=cols, show="headings",
                                  selectmode="browse", height=10)
        vsb = ttk.Scrollbar(frm, orient="vertical", command=self._tree.yview)
        self._tree.configure(yscrollcommand=vsb.set)
        vsb.pack(side="right", fill="y")
        self._tree.pack(fill="both", expand=True)
        for c, txt, w, anc in (("name", "Name", 260, "w"),
                               ("jobs", "Jobs", 60, "center"),
                               ("size", "Size", 90, "e"),
                               ("when", "Saved", 130, "center")):
            self._tree.heading(c, text=txt, anchor=anc)
            self._tree.column(c, width=w, anchor=anc,
                              stretch=(c == "name"))
        self._tree.bind("<Double-1>", lambda e: self._on_load())

        self._reload()

    # ── Internals ────────────────────────────────────────────────────────

    def _reload(self):
        self._tree.delete(*self._tree.get_children())
        self._rows = self._mgr.list_saved_queues()
        for name, jobs, total, mtime in self._rows:
            try:
                when = datetime.fromtimestamp(mtime).strftime("%Y-%m-%d %H:%M")
            except Exception:
                when = ""
            self._tree.insert("", "end",
                              values=(name, jobs, _fmt_size(total), when))
        if not self._rows:
            self._lbl.configure(text="No saved queues yet.")

    def _selected_name(self) -> str:
        sel = self._tree.selection()
        if not sel:
            return ""
        return str(self._tree.item(sel[0], "values")[0])

    def _on_save(self):
        name = self._qname.get().strip()
        if not name:
            # Complain INSIDE the dialog.  A messagebox raised from a window
            # that holds the grab is the reliable way to wedge this program.
            self._lbl.configure(text="⚠  Give it a name first.")
            return
        try:
            n, path = self._mgr.save_queue_as(
                name, self._picked if self._picked else None)
        except Exception as exc:
            self._lbl.configure(text=f"⚠  Could not save: {exc}")
            _log(f"Queue save failed: {exc}")
            return
        if not n:
            self._lbl.configure(text="⚠  Nothing to save — the queue is empty.")
            return
        self._lbl.configure(text=f"💾  {n} job(s) saved as ‘{name}’.")
        self._reload()

    def _on_load(self):
        name = self._selected_name()
        if not name:
            self._lbl.configure(text="Pick a saved queue first.")
            return
        try:
            n, dropped = self._mgr.load_saved_queue(
                name, resume=bool(self._resume_var.get()))
        except Exception as exc:
            self._lbl.configure(text=f"⚠  Could not load: {exc}")
            _log(f"Queue load failed: {exc}")
            return
        if not n:
            self._lbl.configure(
                text=f"⚠  Nothing came back from ‘{name}’ — none of its "
                     f"sources are still on disk.")
            return
        msg = f"📂  {n} job(s) loaded, PAUSED.  Press ▶ Start in the queue."
        if dropped:
            msg += f"   ({dropped} dropped: their sources are gone.)"
        self._lbl.configure(text=msg)
        try:
            self._parent.refresh()
        except Exception:
            pass

    def _on_delete(self):
        name = self._selected_name()
        if not name:
            self._lbl.configure(text="Pick a saved queue first.")
            return
        if self._mgr.delete_saved_queue(name):
            self._lbl.configure(text=f"🗑  ‘{name}’ deleted.")
        else:
            self._lbl.configure(text=f"⚠  ‘{name}’ could not be deleted.")
        self._reload()


# ══════════════════════════════════════════════════════════════════════════
#  Queue Window  —  single unified popup for all pending operations
# ══════════════════════════════════════════════════════════════════════════

# ── The ⚡ button's four states (revBS) ────────────────────────────────────
# ONE control for the whole "is the Task Queue in the way, or buried?" question,
# and it lives in the FILE MANAGER's toolbar with every other button.
# LEFT-click cycles 1 → 2 → 3 → closed; RIGHT-click closes from any state.
QUEUE_MODE_CLOSED   = 0     # hidden — the button keeps its original colour
QUEUE_MODE_FREE     = 1     # open, ordinary window: anything may cover it
QUEUE_MODE_OVER_FM  = 2     # open, OWNED by the file manager: above it only
QUEUE_MODE_OVER_ALL = 3     # open, WS_EX_TOPMOST: above everything, for ever

# ttk ignores bg= on the Windows themes, so the state is carried by the BOLT
# itself.  Closed has no entry — it gets the plain theme colour back.
_QUEUE_MODE_COLOUR = {
    QUEUE_MODE_FREE:     "#1f9d3a",     # green
    QUEUE_MODE_OVER_FM:  "#c8761a",     # orange / light brown
    QUEUE_MODE_OVER_ALL: "#d21c1c",     # red — the aggressive one
}
# Kept SHORT on purpose: this sits in the queue's toolbar, which packs left to
# right, and whatever is packed last (the status line, on the right) is what
# loses its space when the row runs out of width.  The full wording is in the
# tooltip.
_QUEUE_MODE_LABEL = {
    QUEUE_MODE_CLOSED:   "",
    QUEUE_MODE_FREE:     "🟢 free",
    QUEUE_MODE_OVER_FM:  "🟠 over FM",
    QUEUE_MODE_OVER_ALL: "🔴 over all",
}
_QUEUE_MODE_FLASH = {
    QUEUE_MODE_CLOSED:   "⚡  Task Queue closed  (left-click the bolt to open it)",
    QUEUE_MODE_FREE:     "🟢  Task Queue open — no priority; other windows may "
                         "cover it  (click ⚡ again for the next state)",
    QUEUE_MODE_OVER_FM:  "🟠  Task Queue above the FILE MANAGER — other programs "
                         "still cover it  (click ⚡ again for the next state)",
    QUEUE_MODE_OVER_ALL: "🔴  Task Queue above EVERYTHING  (click ⚡ again to "
                         "close it, or right-click the bolt)",
}
_QUEUE_MODE_TIP = (
    "Where this window sits is set on the ⚡ button in the FILE MANAGER's\n"
    "toolbar — this line only says which state it is in.\n"
    "\n"
    "LEFT-click ⚡ to step through them:\n"
    "   1  🟢 green    open — no priority; anything may cover it\n"
    "   2  🟠 orange   open — always above the FILE MANAGER, nothing else\n"
    "   3  🔴 red      open — above EVERYTHING (the aggressive one)\n"
    "   4  ⚡ plain    closed\n"
    "RIGHT-click ⚡ closes it from any state.")


class QueueWindow(tk.Toplevel):
    """Shows all queued tasks with live status, smart-sort, and manual reorder."""

    def _escape(self, _e=None):
        """Skip a waiting name clash, or close the window when none is."""
        try:
            if self._mgr.first_conflict_task() is not None:
                ed = getattr(self._mgr, "_editor", None)
                if ed is not None:
                    ed._cbar_resolve("skip_all") if getattr(ed, "_cbar_shown", False) \
                        else self._mgr.resolve_pending_conflicts("skip_all")
                    return "break"
        except Exception as exc:
            _log(f"Esc in the Task Queue: {exc}")
        self._hide()
        return "break"

    def __init__(self, parent, mgr: TaskQueueManager):
        super().__init__(parent)
        self.title("Task Queue")
        # Open in the bottom-right corner of the screen so it stays visible
        # without covering the file panels.  (Never grabbed / never modal.)
        # 400 px tall was not enough for its own contents: toolbar + auto-rule
        # bar + progress strip + a clash banner + the list left the button row
        # with nothing, and the buttons were simply not there.  The row is now
        # packed from the bottom (see _build_ui) AND the window has a floor it
        # cannot be dragged below.
        w, h = 820, 560
        try:
            sw = self.winfo_screenwidth()
            sh = self.winfo_screenheight()
            h = min(h, max(420, sh - 120))
            x = max(0, sw - w - 30)
            y = max(0, sh - h - 70)
            self.geometry(f"{w}x{h}+{x}+{y}")
        except Exception:
            self.geometry(f"{w}x{h}")
        self.resizable(True, True)
        # 800, not 660.  Measured, not guessed: the bottom button row needs
        # 750 px to show every button and the toolbar 797 for every control.
        # That row is what the window is FOR when something has gone wrong and
        # it was squeezed out of existence once already (revBF), so the window
        # is not allowed to be narrow enough for it to happen again (revBT).
        self.minsize(800, 420)
        self.configure(bg=C_BG)
        # NOTE: deliberately NOT transient — a transient window always stays
        # on top of its parent and would cover the corner permanently.  As an
        # independent window it floats, can be sent behind by clicking the file
        # manager, and never blocks it.
        # Start hidden so the very first show can be a no-activate one (the OS
        # otherwise focuses a freshly created window, stealing the keyboard).
        self.withdraw()
        # Apply the no-activate + TOOL-WINDOW style NOW, while still withdrawn,
        # so the window is never registered in the taskbar in the first place
        # (no phantom second entry under the file-manager icon).  Reached via the
        # ⚡ toolbar button instead.
        self.after_idle(lambda: _make_window_no_activate(self))
        # Closing just hides; tasks keep running (reopen with the ⚡ button)
        self.protocol("WM_DELETE_WINDOW", self._hide)
        # Esc: answer a waiting name clash with Skip first — the same meaning
        # it has everywhere else — and only close the window when nothing is
        # waiting.  Pressing it here used to shut the queue and leave the
        # "⚠1 ANSWER" exactly where it was.
        self.bind("<Escape>", self._escape)
        # Loop guards for the focus/raise plumbing (see _bounce_focus_to_fm)
        self._bouncing      = False
        self._last_bounce_t = 0.0
        self._last_raise_t  = 0.0
        self._raise_burst   = 0
        # What is ON SCREEN right now: 0 closed · 1 free · 2 above the file
        # manager · 3 above everything.  The ⚡ button is coloured from THIS,
        # never from the saved setting, so it can never claim the queue is
        # pinned while nothing is showing.
        self._mode_now = QUEUE_MODE_CLOSED
        self._mgr = mgr
        self._build_ui()
        self._no_keyboard_focus_anywhere()   # queue widgets never Tab-grab the caret
        self.refresh()
        self._tick()   # start 1-second countdown updater
        # Make the whole window "no-activate": clicking it (its Resolve buttons)
        # can never steal the keyboard from the main file manager, so the arrow
        # keys always drive the file list, never the queue.  Applied once the
        # HWND exists; kept off the critical path if it ever fails.
        self.after(0, lambda: _make_window_no_activate(self))
        # Belt-and-suspenders: if the queue window EVER receives keyboard focus
        # (some window managers focus a freshly shown window before the no-
        # activate style takes hold), immediately hand the keyboard back to the
        # file manager.  The Task Queue must NEVER own the keyboard.
        self.bind("<FocusIn>", self._bounce_focus_to_fm)
        # Because the window is "no-activate", the OS will NOT raise it when you
        # click it — so raise it ourselves.  Clicking anywhere on the queue (its
        # title area, list or buttons) brings it to the FRONT above every other
        # program, yet still never takes the keyboard.  add="+" so it runs
        # alongside the buttons' own commands.  (The toplevel is in each child's
        # bind tags, so this fires for clicks on the child widgets too.)
        self.bind("<Button-1>", self._raise_on_click, add="+")
        # Ultimate guarantee: a short-timer watchdog. The no-activate style and
        # the FocusIn bounce are both event-driven and can be beaten by a badly
        # timed OS focus grab; this polling guard closes the gap and can NEVER be
        # out-raced. It only ever acts when focus is genuinely INSIDE the queue -
        # switching to another app (focus leaves this program entirely) is left
        # completely alone.
        self.after(200, self._focus_guard)
        # One-second heartbeat so the strips can say "nothing has moved for
        # four minutes".  Until now the only thing that repainted them was a
        # byte arriving — so a stall froze the display looking healthy.
        self._heartbeat_id = None
        self._progress_heartbeat()

    def _focus_guard(self):
        """Runs every 200 ms for the life of the window. If the keyboard focus
        has landed on ANY widget inside the Task Queue, bounce it back to the
        file manager at once. The queue must never own the keyboard.

        It deliberately does NOTHING while a modal dialog holds a grab: yanking
        focus away from a modal dialog starts a focus tug-of-war between the two
        windows, which is exactly the kind of loop that made everything flash."""
        try:
            if self.winfo_exists() and self.winfo_ismapped():
                if self.grab_current() is None:      # no modal dialog open
                    foc = self.focus_get()      # focus widget in THIS app, or None
                    if foc is not None:
                        fp, mine = str(foc), str(self)
                        if fp == mine or fp.startswith(mine + "."):
                            self._bounce_focus_to_fm()
        except Exception:
            pass
        finally:
            try:
                self.after(200, self._focus_guard)
            except Exception:
                pass

    def _no_keyboard_focus_anywhere(self):
        """Set takefocus=0 on the queue window and every widget inside it, so Tab
        traversal can never move the caret into the Task Queue. (Mouse clicks are
        handled by the no-activate style plus the focus watchdog; this closes the
        keyboard-traversal door as well.)"""
        def walk(w):
            try:
                w.configure(takefocus=0)
            except Exception:
                pass
            for child in w.winfo_children():
                walk(child)
        walk(self)

    # ── The four states, carried out (revBS) ──────────────────────────────
    # This window does not DECIDE any of this any more; the ⚡ button in the
    # file manager does.  Everything here just does what the mode says.

    def _top_mode(self) -> int:
        """The state the ⚡ button is set to (0-3)."""
        try:
            return self._mgr._editor._queue_top_mode()
        except Exception:
            return QUEUE_MODE_OVER_FM

    def _want_on_top(self) -> bool:
        """True only for state 3 — "above everything".  State 2 is owner-based
        and needs none of the WS_EX_TOPMOST machinery (that is the point of
        it: WS_EX_TOPMOST was never "above the file manager")."""
        return self._mode_now >= QUEUE_MODE_OVER_ALL

    def apply_top_mode(self, mode: int):
        """Show the window in state 1, 2 or 3.  (State 4 / 0 is _hide().)

        Never activates: the arrow keys stay in the file manager in every one
        of the states, which is the rule that does not bend."""
        mode = max(QUEUE_MODE_FREE, min(QUEUE_MODE_OVER_ALL, int(mode)))
        _make_window_no_activate(self)
        self._ensure_on_screen()
        if mode >= QUEUE_MODE_OVER_ALL:
            # Above everything.  No owner — an owned window can never be
            # topmost above its own owner's stack in a useful way, and the
            # two mechanisms must not be mixed.
            _win_set_owner(self, 0)
            _register_topmost_window(self)
            if _MODAL_DEPTH["n"]:
                # A modal dialog must stay in front of us; it re-pins this
                # window itself when it closes.
                _show_toplevel_no_activate(self)
            else:
                _raise_toplevel_no_activate(self, keep_on_top=True)
        else:
            _unregister_topmost_window(self)
            _drop_toplevel_no_activate(self)
            if not _show_toplevel_no_activate(self):
                try:
                    self.deiconify()       # non-Windows fallback
                except Exception:
                    pass
            # State 2: owned by the file manager, so Windows keeps it above
            # that one window and no other.  State 1: no owner at all.
            owner = 0
            if mode == QUEUE_MODE_OVER_FM:
                try:
                    owner = _win_hwnd(self._mgr._editor.winfo_toplevel())
                except Exception:
                    owner = 0
            _win_set_owner(self, owner)
            if platform.system() == "Windows":
                # HWND_TOP, never HWND_TOPMOST: the usual "raise then demote"
                # trick would make this window topmost for an instant, and a
                # topmost window drags its OWNER up with it — which is exactly
                # what state 2 must not do.
                _win_set_zorder(self, 0)
            else:
                try:
                    self.lift()
                except Exception:
                    pass
        self._mode_now = mode
        self._show_mode_label()

    def _show_mode_label(self):
        """Say in the queue's own toolbar which state the ⚡ button has it in."""
        try:
            self._lbl_mode.configure(
                text=_QUEUE_MODE_LABEL.get(self._mode_now, ""),
                fg=_QUEUE_MODE_COLOUR.get(self._mode_now, C_FG_DIM))
        except Exception:
            pass

    def _on_toggle_full_speed(self):
        """Live override from the queue's own toolbar.

        Ticked → the ⚡ Full speed preset.  Unticked → back to whatever was in
        force before (so a hand-tuned Transfers tab is not quietly thrown away
        by one panic tick of the box), or 🙂 Polite the first time."""
        try:
            ed = self._mgr._editor
            if self._full_speed_var.get():
                prev = _throttle_preset_name(ed.settings)
                if prev != "full":
                    ed.settings["transfer_preset_before_full"] = prev
                    if prev == "custom":
                        ed.settings["transfer_custom_backup"] = {
                            k: ed.settings.get(k)
                            for k in THROTTLE_PRESETS["polite"]}
                ed.settings.update(THROTTLE_PRESETS["full"])
            else:
                prev = ed.settings.get("transfer_preset_before_full", "polite")
                if prev == "custom" and ed.settings.get("transfer_custom_backup"):
                    ed.settings.update(ed.settings["transfer_custom_backup"])
                else:
                    ed.settings.update(
                        THROTTLE_PRESETS.get(prev, THROTTLE_PRESETS["polite"]))
            ed.save_settings()
        except Exception:
            pass

    def _sync_full_speed_box(self):
        """Keep the toolbar box honest when Settings ▸ Transfers is used."""
        try:
            want = (_throttle_preset_name(self._mgr._editor.settings) == "full")
            if bool(self._full_speed_var.get()) != want:
                self._full_speed_var.set(want)
        except Exception:
            pass
        try:
            if bool(self._bus_solo_var.get()) != bool(self._mgr._bus_solo):
                self._bus_solo_var.set(bool(self._mgr._bus_solo))
        except Exception:
            pass

    def _on_toggle_bus_pause(self):
        """🚌 paused — hold the bus lane; the main lane carries on."""
        on = bool(self._bus_pause_var.get())
        self._mgr.set_bus_paused(on)
        n = len(self._mgr.bus_queue())
        try:
            if on:
                self._lbl_status.configure(
                    text=(f"🚌 lane HELD — {n} job(s) standing still; the main "
                          f"lane carries on"
                          if n else
                          "🚌 lane HELD — nothing in it at the moment"))
            else:
                self._lbl_status.configure(
                    text=(f"🚌 lane released — {n} job(s) moving again"
                          if n else "🚌 lane released"))
        except Exception:
            pass
        self.refresh()

    def _on_toggle_bus_solo(self):
        """🚌 only — hold the main lane while there is bus work to do."""
        on = bool(self._bus_solo_var.get())
        self._mgr.set_bus_solo(on)
        n = len(self._mgr.bus_queue())
        if on:
            self._lbl_status.configure(
                text=(f"🚌 only — the main lane stands down for {n} bus job(s)"
                      if n else
                      "🚌 only — armed; the main lane runs until something "
                      "takes the bus lane"))
        else:
            self._lbl_status.configure(
                text="🚌 back to sharing the disk with the main lane")

    def _raise_on_click(self, event=None):
        """Bring the queue to the front on a click, without activating it.

        State 3 is topmost and by definition not covered, so the click does no
        window work at all.  State 2 raises with HWND_TOP only — going topmost
        even for an instant would drag its OWNER (the file manager) up with it,
        which is the one thing state 2 must not do.  State 1 raises the old
        way, above other programs as well."""
        if self._mode_now >= QUEUE_MODE_OVER_ALL:
            return
        if self._mode_now == QUEUE_MODE_OVER_FM:
            _win_set_zorder(self, 0)
            return
        _raise_toplevel_no_activate(self, keep_on_top=False)

    def present(self, activate: bool = False):
        """Show the window in whatever state the ⚡ button is set to.

        The z-order is the MODE's business now, so *activate* no longer means
        "jump in front" — it is kept for the old callers and only means "if the
        button says closed, open it".  Either way the keyboard stays exactly
        where it was: the Task Queue never takes it, in any state.
        """
        mode = self._top_mode()
        if mode <= QUEUE_MODE_CLOSED:
            mode = QUEUE_MODE_FREE
        self.apply_top_mode(mode)

    def _hide(self):
        """Close button / Escape — that IS state 4, so tell the ⚡ button too,
        or it would sit there coloured while nothing is on screen."""
        _unregister_topmost_window(self)
        try:
            _drop_toplevel_no_activate(self)
            _win_set_owner(self, 0)
        except Exception:
            pass
        self.withdraw()
        self._had_tasks = False
        self._mode_now = QUEUE_MODE_CLOSED
        self._show_mode_label()
        try:
            self._mgr._editor._set_queue_top_mode(
                QUEUE_MODE_CLOSED, from_window=True)
        except Exception:
            pass

    def _ensure_on_screen(self):
        """Drag the window back onto the desktop if a monitor change (or an old
        saved position) left it partly or fully outside — an invisible queue is
        just as unreachable as a buried one."""
        try:
            self.update_idletasks()
            sw, sh = self.winfo_screenwidth(), self.winfo_screenheight()
            w = max(320, self.winfo_width())
            h = max(200, self.winfo_height())
            x, y = self.winfo_x(), self.winfo_y()
            nx = min(max(0, x), max(0, sw - w))
            ny = min(max(0, y), max(0, sh - h))
            if (nx, ny) != (x, y):
                self.geometry(f"+{nx}+{ny}")
        except Exception:
            pass

    def alert_front(self):
        """Pop the window IN FRONT of everything and keep it there (always-on-
        top) so a problem that needs resolving cannot be missed or buried behind
        other programs.  Still never steals the keyboard — the arrow keys stay
        in the file manager.  The window is demoted again by _drop_to_background
        once the conflict is resolved (or the queue empties)."""
        _make_window_no_activate(self)
        _register_topmost_window(self)
        if _MODAL_DEPTH["n"]:
            _show_toplevel_no_activate(self)   # a modal dialog stays in front
            return
        _raise_toplevel_no_activate(self, keep_on_top=True)

    def _bounce_focus_to_fm(self, event=None):
        """The Task Queue must NEVER own the keyboard.  If it somehow gains focus
        (the OS focused it the instant it was shown, or a click slipped past the
        no-activate style), hand the keyboard straight back to the file manager.

        Just calling panel.tree.focus_set() is NOT enough: on Windows the Tk
        keyboard focus follows the ACTIVE OS window, and while this queue window
        is the active one, requesting focus for a widget in ANOTHER toplevel does
        nothing.  So we (1) re-assert the no-activate style so this can't recur,
        (2) pull the MAIN window back to the foreground at the OS level, and only
        then (3) put the caret in the active file panel.

        Loop protection (this is the dangerous one): focus_force() generates
        focus events of its own, so an unguarded bounce can re-trigger itself
        for ever — everything flashes and the process eventually dies.  Hence
        a re-entrancy flag, a 400 ms cooldown, and a hard rule that it never
        touches focus while a MODAL DIALOG is open (fighting a modal dialog
        for focus is a guaranteed tug-of-war).  It also never re-raises this
        window: WS_EX_TOPMOST already keeps it above the main one."""
        if getattr(self, "_bouncing", False):
            return
        now = _time.monotonic()
        if now - getattr(self, "_last_bounce_t", 0.0) < 0.4:
            return
        try:
            if self.grab_current() is not None:
                return                      # a modal dialog owns the keyboard
        except Exception:
            pass
        self._bouncing     = True
        self._last_bounce_t = now
        try:
            ed  = self._mgr._editor
            top = ed.winfo_toplevel()
            # (1) make sure this window is (still) no-activate
            _make_window_no_activate(self)
            # (2) main window back to the OS foreground — but only if some
            #     other window of OURS is not already holding it, and only if
            #     this program is the foreground application at all (switching
            #     to Explorer must never yank the user back here).
            if _win_app_is_foreground(top) is not True:
                pass                        # another app has it — leave it alone
            else:
                try:
                    top.focus_force()
                except Exception:
                    pass
            # (3) caret into the active panel's file list
            panel = ed.get_active_panel()
            if panel is not None and hasattr(panel, "tree"):
                panel.tree.focus_set()
        except Exception:
            pass
        finally:
            self._bouncing = False

    def _drop_to_background(self):
        """Hand the keyboard back to the active file panel right after a conflict
        is resolved, so the arrow keys drive the file list again with no extra
        click.

        Whether the queue also drops BEHIND the file manager depends on which
        of the ⚡ button's four states it is in: state 3 (above everything) and
        state 2 (owned by the file manager) both keep it visible, because that
        is what they are for; state 1 goes back to the old behaviour, where
        ordinary windows may cover it."""
        try:
            ed  = self._mgr._editor
            top = ed.winfo_toplevel()
            if not self._want_on_top():
                _drop_toplevel_no_activate(self)
                top.lift()
            panel = ed.get_active_panel()
            if panel is not None and hasattr(panel, "tree"):
                panel.tree.focus_set()
            # No re-raise here: state 3 already keeps this window above the
            # main one through WS_EX_TOPMOST and state 2 through its owner,
            # and raising from a focus path is the loop that had to be removed.
        except Exception:
            pass

    # ── UI construction ───────────────────────────────────────────────────

    def _build_ui(self):
        # ── Top toolbar ───────────────────────────────────────────────────
        tb = tk.Frame(self, bg=C_BG2, padx=6, pady=5)
        tb.pack(fill="x")

        self._btn_start = ttk.Button(tb, text="▶  Start",      width=11, command=self._on_start)
        self._btn_pause = ttk.Button(tb, text="⏸  Pause",      width=11, command=self._on_pause)
        btn_sort        = ttk.Button(tb, text="✨  Smart Sort", width=13, command=self._on_smart_sort)
        btn_clear       = ttk.Button(tb, text="🧹  Clear Done", width=13, command=self._on_clear_done)
        btn_rules       = ttk.Button(tb, text="⚖  Rules…",     width=11, command=self._open_rules)

        self._btn_start.pack(side="left", padx=2)
        self._btn_pause.pack(side="left", padx=2)
        btn_sort.pack(       side="left", padx=(10, 2))
        btn_clear.pack(      side="left", padx=2)
        btn_rules.pack(      side="left", padx=(10, 2))

        # ── Which state is the ⚡ button in?  (revBS) ──────────────────────
        # The 📌 "On top" tick and the ⏱ "Top" button that used to sit here are
        # gone.  Three controls in two windows for one question was the whole
        # complaint; there is now exactly one, the ⚡ button in the file
        # manager's toolbar, and this label only REPORTS what it is set to so
        # the window says it as well as the button does.
        self._lbl_mode = tk.Label(tb, text="", bg=C_BG2, fg=C_FG_DIM,
                                  font=("Segoe UI", 8))
        self._lbl_mode.pack(side="left", padx=(12, 2))
        try:
            self._mgr._editor._create_tooltip(self._lbl_mode, _QUEUE_MODE_TIP)
        except Exception:
            pass

        # ── "⚡ Full speed" — the override, where you can actually reach it ──
        # Buried in Settings ▸ Transfers is no use while a 10 GB copy has the
        # machine on its knees and you want it to stop being clever RIGHT NOW.
        # This is live: it reaches the file that is already being written, not
        # just the next job.  Ticked = no priority drop, no cache flushing, no
        # cap — the disk decides.  See the revAZ header note.
        self._full_speed_var = tk.BooleanVar(
            value=(_throttle_preset_name(self._mgr._editor.settings) == "full"))
        chk_fast = tk.Checkbutton(
            tb, text="⚡ Full speed", variable=self._full_speed_var,
            bg=C_BG2, fg=C_FG, selectcolor=C_BG3, activebackground=C_BG2,
            activeforeground=C_FG, font=("Segoe UI", 8), takefocus=0,
            command=self._on_toggle_full_speed)
        chk_fast.pack(side="left", padx=2)

        # ── "🚌 only" — the bus lane with the road to itself (revBN) ──────
        # Asked for: "den får även ha funktionen att den kan pausa huvudgrejen
        # = kör bara bus-lane".  Ticked, the big transfer stands down at the
        # next block boundary and STAYS down until the bus queue is empty.
        self._bus_solo_var = tk.BooleanVar(value=bool(self._mgr._bus_solo))
        chk_solo = tk.Checkbutton(
            tb, text="🚌 only", variable=self._bus_solo_var,
            bg=C_BG2, fg=C_FG, selectcolor=C_BG3, activebackground=C_BG2,
            activeforeground=C_FG, font=("Segoe UI", 8), takefocus=0,
            command=self._on_toggle_bus_solo)
        chk_solo.pack(side="left", padx=2)

        # ── "🚌 paused" — the other direction (revBT) ─────────────────────
        # "jag ser inte något sätt att pausa eller ta bort från bus lane".
        # 🚌 only holds the MAIN lane for the bus lane; this holds the BUS
        # lane and lets the main one carry on.
        self._bus_pause_var = tk.BooleanVar(value=bool(self._mgr._bus_paused))
        chk_bpause = tk.Checkbutton(
            tb, text="🚌 paused", variable=self._bus_pause_var,
            bg=C_BG2, fg=C_FG, selectcolor=C_BG3, activebackground=C_BG2,
            activeforeground=C_FG, font=("Segoe UI", 8), takefocus=0,
            command=self._on_toggle_bus_pause)
        chk_bpause.pack(side="left", padx=2)

        # ── "Close when empty" (default ON) ───────────────────────────────
        # Asked for: the Task Queue closes itself once everything is done AND
        # the list has been emptied (🧹 Clear Done / removing the last row).
        # It never closes while a job is running, waiting, or still on the
        # list, and never a window you opened yourself on an empty queue.
        self._autoclose_var = tk.BooleanVar(
            value=bool(self._mgr._editor.settings.get("queue_autoclose", True)))
        self._had_tasks = False
        chk_autoclose = tk.Checkbutton(
            tb, text="Close when empty", variable=self._autoclose_var,
            bg=C_BG2, fg=C_FG, selectcolor=C_BG3, activebackground=C_BG2,
            activeforeground=C_FG, font=("Segoe UI", 8), takefocus=0,
            command=self._on_toggle_autoclose)
        chk_autoclose.pack(side="left", padx=2)
        try:
            self._mgr._editor._create_tooltip(
                chk_autoclose,
                "Close this window by itself when every job is done and the\n"
                "list has become empty.  Never closes while something is\n"
                "running or waiting.")
        except Exception:
            pass
        try:
            self._mgr._editor._create_tooltip(
                chk_bpause,
                "🚌 paused — hold the BUS LANE still.  The main lane carries on.\n"
                "\n"
                "A job already running in the lane stops at the next block\n"
                "boundary — nothing half-written, nothing thrown away — and\n"
                "picks itself up exactly where it stopped when you let it go.\n"
                "\n"
                "This is the one for “I pressed 🚌 on the 35 GB transfer by\n"
                "mistake and now it is in front of my three small ones”: hold\n"
                "the lane instead of cancelling it, and nothing is lost.\n"
                "RIGHT-click the 🚌 button at the bottom to empty the lane\n"
                "altogether.\n"
                "\n"
                "An ORDINARY small job (the ⚡ fast lane) is not held — only the\n"
                "ones you put in the lane by hand.  It is not remembered between\n"
                "sessions: a hold you have forgotten about must never be able to\n"
                "stop work at the next start.")
        except Exception:
            pass
        try:
            self._mgr._editor._create_tooltip(
                chk_solo,
                "🚌 only — the bus lane gets the disk to ITSELF.\n"
                "\n"
                "Normally a bus job runs BESIDE the big transfer and the two\n"
                "share the drive.  Ticked, the big one stands down at the next\n"
                "block boundary (nothing half-written, nothing thrown away) and\n"
                "stays down until every job in the bus queue is finished — then\n"
                "it picks itself up exactly where it stopped.\n"
                "\n"
                "Two streams onto one USB disk is the worst case there is; this\n"
                "is the switch for it.\n"
                "\n"
                "It can never deadlock: a bus job that CANNOT run — parked on a\n"
                "name clash, waiting for room, or held back because an earlier\n"
                "job has the same file — holds nothing, and the main lane runs.")
        except Exception:
            pass
        try:
            self._mgr._editor._create_tooltip(
                chk_fast,
                "OFF (normal): the copy runs at Windows BACKGROUND I/O priority and\n"
                "flushes its write cache every 64 MB.  On an idle machine that is\n"
                "full speed — nothing is competing, so nothing overtakes it — and\n"
                "the moment you do something else, YOUR disk requests jump ahead of\n"
                "the copy's.  This is what keeps the machine usable.\n"
                "\n"
                "ON: none of that.  The copy is an ordinary, equal-priority program\n"
                "and its writes pile up in the Windows cache.  Fastest on paper;\n"
                "it is also what made a 10 GB C→C copy take 30 seconds to open\n"
                "Ctrl+Alt+Del.  Takes effect on the RUNNING file, not just the\n"
                "next one.")
        except Exception:
            pass

        # Explain what the less-obvious buttons do (hover tooltips)
        ed = self._mgr._editor
        try:
            ed._create_tooltip(
                btn_sort,
                "Smart Sort — reorder the PENDING jobs so quick ones run first\n"
                "(same-drive moves are instant, small copies before big ones),\n"
                "and any job that would not FIT on its destination drive is moved\n"
                "to the end to wait for space.  Jobs you dragged by hand stay put.")
            ed._create_tooltip(
                btn_rules,
                "Conflict rules — set 'from folder X to folder Y (in Workspace W)\n"
                "always Overwrite older / Rename old / …' so clashes resolve\n"
                "automatically and never stop to ask.")
        except Exception:
            pass

        # Status label (right side)
        # ── The status line gets a row of its OWN (revBT) ─────────────────
        # It used to be packed side="right" in the toolbar above — and pack
        # gives its space out in the order things are packed, so the LAST one
        # in is the one that loses when the row runs out of width.  Measured:
        # that button row wants about 785 px and this label wants up to 325,
        # in a window whose default is 820 — so the sentence telling you what
        # just happened was the thing being thrown away.  On its own row it
        # can never fight the buttons, and it has the whole width to say it in.
        tb2 = tk.Frame(self, bg=C_BG2, padx=8, pady=0)
        tb2.pack(fill="x")
        self._lbl_status = tk.Label(tb2, text="", bg=C_BG2, fg=C_FG_DIM,
                                    font=("Segoe UI", 8), anchor="w",
                                    justify="left")
        self._lbl_status.pack(side="left", fill="x", expand=True, pady=(0, 3))

        # ── One-tick auto-rule bar ────────────────────────────────────────
        # After a copy/move, tick "Always auto-resolve this" to save a Smart-
        # queue rule for THIS Workspace and THIS from→to folder pair, so future
        # transfers between them never stop to ask.  Manage them via ⚖ Rules….
        ar = tk.Frame(self, bg=C_BG3, padx=8, pady=4)
        ar.pack(fill="x", padx=6, pady=(2, 0))
        tk.Label(ar, text="⚖  Auto-rule:", bg=C_BG3, fg=C_ACCENT,
                 font=("Segoe UI", 8, "bold")).pack(side="left")
        self._ar_lbl = tk.Label(ar, text="", bg=C_BG3, fg=C_FG_DIM,
                                font=("Segoe UI", 8), anchor="w")
        self._ar_lbl.pack(side="left", padx=(6, 8))

        self._ar_check_var = tk.BooleanVar(value=False)
        self._ar_check = tk.Checkbutton(
            ar, text="Always auto-resolve this", variable=self._ar_check_var,
            bg=C_BG3, fg=C_FG, selectcolor=C_BG2, activebackground=C_BG3,
            activeforeground=C_FG, font=("Segoe UI", 8),
            command=self._on_autorule_toggle)
        self._ar_check.pack(side="right", padx=(4, 0))

        self._ar_policy = tk.StringVar(value="Backup-rename old")
        self._ar_combo = ttk.Combobox(
            ar, textvariable=self._ar_policy,
            values=[lbl for lbl, _m in _CONFLICT_CHOICES],
            width=18, state="readonly")
        self._ar_combo.pack(side="right", padx=4)
        self._ar_combo.bind("<<ComboboxSelected>>",
                            lambda e: self._on_autorule_policy())
        tk.Label(ar, text="On clash:", bg=C_BG3, fg=C_FG_DIM,
                 font=("Segoe UI", 8)).pack(side="right")

        # ── How wide the rule should be ───────────────────────────────────
        # Saving the rule one or two folders UP is what stops a dated
        # sub-folder ("…\Claude_working\2026-08-29") needing its own rule
        # every single day.  Source and destination are set separately —
        # often only the destination needs widening.
        #
        # ON ITS OWN ROW, packed left.  Squeezed onto the row above with
        # side="right" they were simply never drawn: the window's minimum
        # width is 660 px and the tick, the policy combo and the path label
        # had already taken it — the same one-pixel trap the button row at the
        # bottom of this window was fixed for.
        ar2 = tk.Frame(self, bg=C_BG3, padx=8, pady=(0))
        ar2.pack(fill="x", padx=6)
        _ar_defaults = self._mgr._editor.settings
        tk.Label(ar2, text="       covers — from:", bg=C_BG3, fg=C_FG_DIM,
                 font=("Segoe UI", 8)).pack(side="left")

        self._ar_src_scope = tk.StringVar(
            value=_RULE_SCOPE_LABEL.get(
                int(_ar_defaults.get("rule_scope_src", 0) or 0), "This folder"))
        self._ar_src_combo = ttk.Combobox(
            ar2, textvariable=self._ar_src_scope,
            values=[lbl for lbl, _n in _RULE_SCOPES],
            width=12, state="readonly")
        self._ar_src_combo.pack(side="left", padx=4)
        self._ar_src_combo.bind("<<ComboboxSelected>>",
                                lambda e: self._on_autorule_scope())

        tk.Label(ar2, text="to:", bg=C_BG3, fg=C_FG_DIM,
                 font=("Segoe UI", 8)).pack(side="left", padx=(8, 0))
        self._ar_dst_scope = tk.StringVar(
            value=_RULE_SCOPE_LABEL.get(
                int(_ar_defaults.get("rule_scope_dst", 0) or 0), "This folder"))
        self._ar_dst_combo = ttk.Combobox(
            ar2, textvariable=self._ar_dst_scope,
            values=[lbl for lbl, _n in _RULE_SCOPES],
            width=12, state="readonly")
        self._ar_dst_combo.pack(side="left", padx=4)
        self._ar_dst_combo.bind("<<ComboboxSelected>>",
                                lambda e: self._on_autorule_scope())
        tk.Label(ar2,
                 text="(a rule always covers sub-folders — “1 level up” makes one "
                      "rule cover every dated folder made under it)",
                 bg=C_BG3, fg=C_FG_DIM,
                 font=("Segoe UI", 8)).pack(side="left", padx=(10, 0))

        # ── Inline progress (shown while a task runs) ─────────────────────
        self._prog_frame = tk.Frame(self, bg=C_BG3, padx=8, pady=5)
        self._prog_frame.pack(fill="x", padx=6, pady=(2, 0))

        prog_top = tk.Frame(self._prog_frame, bg=C_BG3)
        prog_top.pack(fill="x")

        self._prog_lbl_file = tk.Label(
            prog_top, text="", bg=C_BG3, fg=C_FG,
            font=("Segoe UI", 9), anchor="w",
        )
        self._prog_lbl_file.pack(side="left", fill="x", expand=True)

        self._btn_cancel_curr = ttk.Button(
            prog_top, text="✖ Cancel", width=10, command=self._on_cancel_current
        )
        self._btn_cancel_curr.pack(side="right", padx=(4, 0))

        self._prog_var = tk.DoubleVar(value=0.0)
        self._prog_bar = ttk.Progressbar(
            self._prog_frame, variable=self._prog_var,
            maximum=100.0, length=600, mode="determinate",
        )
        self._prog_bar.pack(fill="x", pady=(3, 2))

        prog_bot = tk.Frame(self._prog_frame, bg=C_BG3)
        prog_bot.pack(fill="x")
        self._prog_lbl_count = tk.Label(prog_bot, text="", bg=C_BG3, fg=C_FG_DIM,
                                        font=("Segoe UI", 8), anchor="w")
        self._prog_lbl_count.pack(side="left")
        self._prog_lbl_eta = tk.Label(prog_bot, text="", bg=C_BG3, fg=C_FG_DIM,
                                      font=("Segoe UI", 8), anchor="e")
        self._prog_lbl_eta.pack(side="right")

        # Hide until a task is running
        self._prog_frame.pack_forget()

        # ── Bus / fast lane progress ───────────────────────────────
        # The SECOND job — the one running beside the big transfer — has its
        # own strip, because it has its own file, its own speed and its own ✖.
        self._bus_frame = tk.Frame(self, bg="#2a2200", padx=8, pady=4)
        bus_top = tk.Frame(self._bus_frame, bg="#2a2200")
        bus_top.pack(fill="x")
        self._bus_lbl_file = tk.Label(
            bus_top, text="", bg="#2a2200", fg="#ffd479",
            font=("Segoe UI", 9), anchor="w")
        self._bus_lbl_file.pack(side="left", fill="x", expand=True)
        self._btn_cancel_bus = ttk.Button(
            bus_top, text="✖ Cancel", width=10,
            command=self._on_cancel_bus)
        self._btn_cancel_bus.pack(side="right", padx=(4, 0))
        self._bus_var = tk.DoubleVar(value=0.0)
        self._bus_bar = ttk.Progressbar(
            self._bus_frame, variable=self._bus_var,
            maximum=100.0, length=600, mode="determinate")
        self._bus_bar.pack(fill="x", pady=(3, 2))
        self._bus_lbl_count = tk.Label(self._bus_frame, text="", bg="#2a2200",
                                       fg="#c9b071", font=("Segoe UI", 8),
                                       anchor="w")
        self._bus_lbl_count.pack(fill="x")
        self._bus_frame.pack_forget()

        # ── Carried over from the last session ──────────────────────
        self._restore_frame = tk.Frame(self, bg="#12331f", padx=8, pady=6)
        rs_top = tk.Frame(self._restore_frame, bg="#12331f")
        rs_top.pack(fill="x")
        self._restore_lbl = tk.Label(
            rs_top, text="", bg="#12331f", fg="#8fe0a8",
            font=("Segoe UI", 9), anchor="w", justify="left")
        self._restore_lbl.pack(side="left", fill="x", expand=True)
        ttk.Button(rs_top, text="🗑 Drop them", width=13,
                   command=self._on_restore_drop).pack(side="right", padx=(6, 0))
        ttk.Button(rs_top, text="▶ Start now", width=13,
                   command=self._on_restore_start).pack(side="right", padx=(6, 0))
        self._restore_frame.pack_forget()

        # ── Space-warning banner (shown when a task is space-blocked) ─────────
        self._space_frame = tk.Frame(self, bg="#4a3a00", padx=8, pady=6)
        # (packed dynamically in _do_refresh)

        sw_top = tk.Frame(self._space_frame, bg="#4a3a00")
        sw_top.pack(fill="x")

        self._space_lbl = tk.Label(
            sw_top, text="", bg="#4a3a00", fg="#ffe066",
            font=("Segoe UI", 9), anchor="w", justify="left",
        )
        self._space_lbl.pack(side="left", fill="x", expand=True)

        self._btn_refresh_space = ttk.Button(
            sw_top, text="🔄 Refresh", width=12,
            command=self._on_refresh_space,
        )
        self._btn_refresh_space.pack(side="right", padx=(6, 0))

        self._space_countdown_lbl = tk.Label(
            self._space_frame, text="", bg="#4a3a00", fg="#aaa060",
            font=("Segoe UI", 8), anchor="w",
        )
        self._space_countdown_lbl.pack(fill="x")

        # ── Conflict-resolution banner (shown when a task has unresolved conflicts) ──
        self._conflict_frame = tk.Frame(self, bg="#3a1a2a", padx=8, pady=6)
        # (packed dynamically in _do_refresh)

        cf_hdr = tk.Frame(self._conflict_frame, bg="#3a1a2a")
        cf_hdr.pack(fill="x")

        self._conflict_lbl = tk.Label(
            cf_hdr, text="", bg="#3a1a2a", fg="#ff99cc",
            font=("Segoe UI", 9), anchor="w", justify="left", wraplength=620,
        )
        self._conflict_lbl.pack(side="left", fill="x", expand=True)

        cf_btns = tk.Frame(self._conflict_frame, bg="#3a1a2a")
        cf_btns.pack(fill="x", pady=(6, 0))

        tk.Label(cf_btns, text="Resolve:", bg="#3a1a2a", fg="#ff99cc",
                 font=("Segoe UI", 8)).pack(side="left", padx=(0, 6))

        # ONE NAME PER MODE (2026-09-12).  This banner called overwrite_older
        # "Overwrite newer" while the combobox three inches above it called the
        # very same mode "Overwrite older" — two opposite-sounding names for one
        # thing, in one window, which is exactly how it came to be read as "it
        # overwrites when the source is OLDER".  It does not: it writes only
        # when the file coming in is the NEWER one.  Labels now come from
        # _CONFLICT_LABEL, so there is one place to change and no second name.
        for mode in ("overwrite_all", "backup_old", "auto_rename",
                     "skip_all", "overwrite_older"):
            ttk.Button(
                cf_btns, text=_CONFLICT_LABEL.get(mode, mode), width=18,
                command=lambda m=mode: self._on_resolve_conflicts(m),
            ).pack(side="left", padx=3)

        # ── Bottom button row ─────────────────────────────────────────────
        # PACKED BEFORE THE TREE, side="bottom".  It used to be created last
        # and packed last, and the tree above it takes everything with
        # expand=True — so as soon as a job was running (progress strip) with a
        # clash parked (conflict strip), this whole row was allocated ONE PIXEL
        # and vanished.  That is why "I cannot remove anything, I cannot
        # reorder anything": the buttons for it were never on screen.
        # A minsize (set in __init__) stops the same thing happening by resize.
        bot = ttk.Frame(self)
        bot.pack(side="bottom", fill="x", padx=6, pady=5)

        ttk.Button(bot, text="↑  Up",   width=9,
                   command=self._on_up).pack(side="left", padx=2)
        ttk.Button(bot, text="↓  Down", width=9,
                   command=self._on_down).pack(side="left", padx=2)
        ttk.Button(bot, text="🔒 Lock", width=9,
                   command=self._on_lock).pack(side="left", padx=2)
        self._btn_bus = ttk.Button(bot, text="🚌 Do it now", width=15,
                                   command=self._on_bus)
        self._btn_bus.pack(side="left", padx=(10, 2))
        # RIGHT-click empties the whole lane — the undo for "I meant to press
        # it on the small ones and hit the 35 GB one" (revBT).
        self._btn_bus.bind("<Button-3>", self._on_bus_clear)
        ttk.Button(bot, text="✖ Cancel", width=10,
                   command=self._on_cancel_task).pack(side="left", padx=(10, 2))
        # "Remove i botten, är det remove from bus lane eller remove från task
        # queue?"  The list.  It never had anything to do with the lane — and
        # now it says so (revBT).
        btn_rm = ttk.Button(bot, text="🗑 Out of queue", width=15,
                            command=self._on_remove)
        btn_rm.pack(side="left", padx=2)
        # ↺ Resume — the answer to "the ones I cancel, do I start over?" (revBN)
        btn_res = ttk.Button(bot, text="↺ Resume", width=11,
                             command=self._on_resume)
        btn_res.pack(side="left", padx=(10, 2))

        # Close goes in BEFORE the hint text: pack gives each widget its space
        # in the order it is packed, so a long left-side label takes the lot
        # and a right-side button packed after it comes out one pixel wide.
        # (Which is exactly what happened to this one.)
        ttk.Button(bot, text="Close", width=9,
                   command=self.withdraw).pack(side="right", padx=2)
        btn_q = ttk.Button(bot, text="🗃 Queues…", width=11,
                           command=self._open_queue_store)
        btn_q.pack(side="right", padx=2)

        lbl_hint = tk.Label(
            bot,
            text="pick rows  ·  ↑↓ = order  ·  🚌 = in / out of the bus lane "
                 "(right-click = empty it)  ·  ✖ = stop it  ·  🗑 = out of the "
                 "QUEUE (Del)  ·  ↺ = carry on where it stopped",
            bg=self["bg"], fg=C_FG_DIM, font=("Segoe UI", 8), anchor="w",
        )
        lbl_hint.pack(side="left", padx=12, fill="x", expand=True)
        try:
            self._mgr._editor._create_tooltip(
                btn_res,
                "↺  Resume — put a finished, cancelled or failed job back to\n"
                "work WITHOUT starting it over.\n"
                "\n"
                "The job is queued again exactly as it was, marked as a resume:\n"
                "every file it already wrote is skipped in silence (same size,\n"
                "same date = the same file), so it carries straight on from\n"
                "where it stopped instead of asking about four thousand files\n"
                "it has already copied.\n"
                "\n"
                "Only the file that was mid-copy when it stopped is done again.\n"
                "A cancel deletes that one on purpose, so there is never a\n"
                "half-written file sitting there wearing the right name.")
            self._mgr._editor._create_tooltip(
                btn_q,
                "🗃  Queues — park a queue under a name and pick it up later.\n"
                "\n"
                "Saving does not remove anything: the jobs stay where they are.\n"
                "Loading puts them back PAUSED, as a resume, so nothing moves\n"
                "until you press ▶ Start and nothing already copied is asked\n"
                "about twice.\n"
                "\n"
                "Separate from the automatic one — whatever is unfinished is\n"
                "ALWAYS written to Helpfiles/redigerare/task_queue.json as it\n"
                "changes and comes back at the next start, whether you save it\n"
                "by hand or not.  That file empties itself only when the work\n"
                "is actually done.")
        except Exception:
            pass
        try:
            self._mgr._editor._create_tooltip(
                self._btn_bus,
                "🚌  BUS LANE — start the picked jobs NOW.\n"
                "\n"
                "It is a lane of its own: filled ONLY by hand, with its own\n"
                "worker, beside the automatic ⚡ lane — so a big job in here\n"
                "never holds up the tiny files the ⚡ lane takes by itself.\n"
                "\n"
                "They do not wait for the job that is running: they run BESIDE\n"
                "it in a second lane, so nothing already half-copied is thrown\n"
                "away.  A small file makes the big transfer stand aside for the\n"
                "second or two it needs; a big one runs alongside and the two\n"
                "share the disk.\n"
                "\n"
                "Press it again to put them back in the normal queue — the\n"
                "button says “🚌 Out of lane” when that is what it will do.\n"
                "This works on the automatic ⚡ jobs too: they move to the\n"
                "normal queue (marked 🛣) and stay there whatever their size;\n"
                "right-click the row > “Let the program choose…” undoes it.\n"
                "RIGHT-CLICK the button to empty the WHOLE lane in one press.\n"
                "\n"
                "Inside the lane the SHORTEST job runs first, so dropping a big\n"
                "one in does not put it in front of the small ones already\n"
                "there.  To stop the lane without losing anything, tick\n"
                "“🚌 paused” on the toolbar above.\n"
                "\n"
                "The one thing it will not do is let a job overtake an EARLIER\n"
                "job holding the SAME file — that row keeps saying ‘⏳ after #n’\n"
                "and takes the lane the moment that one is done.")
        except Exception:
            pass
        try:
            self._mgr._editor._create_tooltip(
                btn_rm,
                "Take the selected jobs out of the QUEUE — off the list\n"
                "altogether, gone, not going to happen.\n"
                "\n"
                "This is NOT the bus lane.  To take a job out of the lane and\n"
                "leave it in the queue, use the 🚌 button (or right-click 🚌 to\n"
                "empty the lane in one press).\n"
                "\n"
                "A job that has not started is cancelled first; the one that is\n"
                "running is left alone (stop that with ✖ on the progress bar).")
        except Exception:
            pass

        # ── Treeview ──────────────────────────────────────────────────────
        frm = ttk.Frame(self)
        frm.pack(fill="both", expand=True, padx=6, pady=(4, 0))
        self._tree_frame = frm  # kept for pack-order reference in refresh

        cols = ("lock", "time", "type", "description", "size", "status")
        # extended: several jobs can be picked at once — removing six duplicates
        # one at a time is not a thing anybody should have to do.
        self._tree = ttk.Treeview(frm, columns=cols, show="headings",
                                   selectmode="extended", height=13)

        self._tree.heading("lock",        text="🔒", anchor="center")
        self._tree.heading("time",        text="Time",        anchor="center")
        self._tree.heading("type",        text="Type",        anchor="center")
        self._tree.heading("description", text="Description")
        self._tree.heading("size",        text="Size",        anchor="e")
        self._tree.heading("status",      text="Status",      anchor="center")

        self._tree.column("lock",        width=32,  stretch=False, anchor="center")
        self._tree.column("time",        width=54,  stretch=False, anchor="center")
        self._tree.column("type",        width=90,  stretch=False, anchor="center")
        self._tree.column("description", width=330, stretch=True)
        self._tree.column("size",        width=80,  stretch=False, anchor="e")
        self._tree.column("status",      width=110, stretch=False, anchor="center")

        vsb = ttk.Scrollbar(frm, orient="vertical", command=self._tree.yview)
        self._tree.configure(yscrollcommand=vsb.set)
        vsb.pack(side="right", fill="y")
        self._tree.pack(fill="both", expand=True)

        # Row colour tags
        self._tree.tag_configure("running",   background="#1b3a5a", foreground=C_ACCENT)
        self._tree.tag_configure("done",      foreground="#55aa55")
        self._tree.tag_configure("cancelled", foreground="#888888")
        self._tree.tag_configure("error",     foreground="#cc4444")
        self._tree.tag_configure("locked",    foreground="#e8c84a")
        self._tree.tag_configure("pending",     foreground=C_FG)
        self._tree.tag_configure("space_blocked",    foreground="#ffe066", background="#2e2500")
        self._tree.tag_configure("conflict_pending", foreground="#ff99cc", background="#2a0d1a")
        # Day-section header rows
        self._tree.tag_configure("dayhdr", background="#20304a", foreground="#9fc3ff",
                                 font=("Segoe UI", 9, "bold"))
        # A job held back because an earlier one has the same file open.
        self._tree.tag_configure("held", foreground="#9fc3ff")
        # 🚌 Bus lane — picked by hand to run now.
        self._tree.tag_configure("bus", foreground="#ffd479", background="#2a2200")
        # Del removes the picked rows — the same as the 🗑 button.  (The queue
        # never owns the keyboard, so this only fires while the mouse has put
        # the focus here; the button is the reliable way.)
        self._tree.bind("<Delete>", lambda e: self._on_remove())
        # add="+" is not optional — a plain bind() REPLACES whatever is on the
        # event already.  Keeps the 🚌 button's label honest as the selection
        # moves (revBT).
        self._tree.bind("<<TreeviewSelect>>", self._update_bus_btn, add="+")
        # revCJ: right-click a row for the things that have no room left on the
        # (already full) button row - at the moment "Unpack anyway".
        self._tree.bind("<Button-3>", self._on_tree_menu)

    # ── Refresh ───────────────────────────────────────────────────────────

    # A running copy reports progress many times a second, and every report
    # used to rebuild the whole window.  Coalesce them: repaint at most every
    # REFRESH_MS, with a trailing update so the final state is never missed.
    REFRESH_MS = 250

    def refresh(self):
        """Ask for a repaint.  Rate-limited — see REFRESH_MS."""
        now = _time.monotonic()
        due = now - getattr(self, "_last_refresh_t", 0.0)
        if due * 1000.0 >= self.REFRESH_MS:
            self._last_refresh_t = now
            self._refresh_now()
            return
        if getattr(self, "_refresh_pending", None) is None:
            wait = int(self.REFRESH_MS - due * 1000.0) + 1
            try:
                self._refresh_pending = self.after(wait, self._refresh_due)
            except Exception:
                self._refresh_pending = None
                self._refresh_now()

    def _refresh_due(self):
        self._refresh_pending  = None
        self._last_refresh_t   = _time.monotonic()
        self._refresh_now()

    def _banner(self, attr: str, show: bool):
        """Show / hide one of the three banner strips WITHOUT re-packing it
        every refresh.

        The old test was `winfo_ismapped()`, which reports 0 whenever the
        window itself is not viewable — so while the queue was hidden (or being
        shown) the banner was packed again on every single refresh, and each
        pack is a full relayout.  With a running copy reporting progress many
        times a second that is a window that visibly flashes.  Remembering the
        state ourselves means pack / pack_forget happen only on a real change.
        """
        state = getattr(self, "_banner_state", None)
        if state is None:
            state = self._banner_state = {}
        if state.get(attr) == show:
            return
        state[attr] = show
        frame = getattr(self, attr, None)
        if frame is None:
            return
        try:
            if show:
                frame.pack(fill="x", padx=6, pady=(2, 0),
                           before=self._tree_frame)
            else:
                frame.pack_forget()
        except Exception:
            state.pop(attr, None)          # retry next time

    # ══════════════════════════════════════════════════════════════════
    #  The progress strips  —  and the stall you can SEE  (revision BN)
    # ══════════════════════════════════════════════════════════════════
    #
    # REPORTED: "task queue … det verkar stå helt still".  It was not "verkar":
    # it WAS still, and had been for 25 minutes — zero bytes read, zero written,
    # zero I/O operations.  The window meanwhile said "▶ Running… · 1 MB/s ·
    # ~4.6 h left", because the speed was total bytes divided by total wall
    # time since the job started.  That average cannot reach zero; it only
    # sags.  So a dead transfer looked like a slow one, which is the single
    # most expensive thing this window has ever done.
    #
    # Three changes, and they only work together:
    #   · the speed is measured over the last few seconds, so it FALLS TO ZERO;
    #   · the time of the last byte is kept, so "nothing since 14:02" can be
    #     said in words;
    #   · a one-second heartbeat repaints the strips, because the old code only
    #     repainted when bytes arrived — and when nothing arrives, nothing
    #     repaints, which is why the frozen numbers stayed convincingly frozen.

    _STALL_WARN  = 15.0      # seconds with no bytes before the strip says so
    _STALL_ALARM = 60.0      # ...and before it says so in red

    @staticmethod
    def _fmt_dur(s: float) -> str:
        s = int(max(0, s))
        if s < 60:
            return f"{s} s"
        if s < 3600:
            return f"{s // 60} min {s % 60} s"
        return f"{s // 3600} h {(s % 3600) // 60} min"

    @staticmethod
    def _fmt_eta(remaining: float) -> str:
        if remaining < 4:
            return ""
        if remaining < 90:
            return f"~{remaining:.0f} s left"
        if remaining < 5400:
            return f"~{remaining / 60:.0f} min left"
        return f"~{remaining / 3600:.1f} h left"

    def _render_progress(self):
        """Repaint both lane strips.  Called by refresh() AND by the heartbeat.

        Kept apart from refresh() on purpose: the heartbeat must be able to
        update the numbers every second without rebuilding the job list, which
        would be a full Treeview relayout once a second — exactly the kind of
        flicker this window is not allowed to have.
        """
        mgr = self._mgr

        # ── Main lane ─────────────────────────────────────────────────────
        if mgr._prog_total > 0 and mgr._current_task is not None:
            cur     = mgr._prog_cur
            total_p = mgr._prog_total
            fname   = mgr._prog_file
            by      = (getattr(mgr, "_prog_unit", "files") == "bytes")
            self._prog_var.set(min(100.0, cur / total_p * 100.0))

            name = os.path.basename(fname) if fname else "…"
            if len(name) > 70:
                name = "…" + name[-67:]
            self._prog_lbl_file.configure(text=name)

            # WHY it is not moving comes before HOW FAST it is not moving.
            held = ""
            if mgr._paused:
                held = "⏸ PAUSED"
            elif mgr.bus_holds_main():
                held = "🚌 standing down for the bus lane"
            elif mgr._big_should_yield():
                held = "⏳ standing aside for the fast lane"

            if by:
                count_txt = f"{_fmt_size(cur)} / {_fmt_size(total_p)}"
            elif total_p > 50_000:
                count_txt = f"{_fmt_size(cur)} / {_fmt_size(total_p)}"
            else:
                count_txt = f"{cur} / {total_p} files"

            stalled = mgr.lane_stalled_for(False) if by else 0.0
            fg      = C_FG_DIM
            eta_txt = ""
            if held:
                count_txt += f"     ·     {held}"
            elif by and stalled >= self._STALL_WARN:
                # THE LINE THAT WOULD HAVE SAVED THE AFTERNOON.
                count_txt += (f"     ·     ⚠  NOT MOVING — no bytes for "
                              f"{self._fmt_dur(stalled)}")
                fg = "#ffe066" if stalled < self._STALL_ALARM else "#ff8888"
                eta_txt = "stalled"
            elif by:
                count_txt += f"     ·     {_fmt_size(int(mgr._prog_rate))}/s"
                if mgr._prog_rate > 0 and cur < total_p:
                    eta_txt = self._fmt_eta((total_p - cur) / mgr._prog_rate)
            elif mgr._prog_start and 0 < cur < total_p:
                el = _time.monotonic() - mgr._prog_start
                if el > 0.5:
                    eta_txt = self._fmt_eta(el / cur * (total_p - cur))

            self._prog_lbl_count.configure(text=count_txt, fg=fg)
            self._prog_lbl_eta.configure(
                text=eta_txt, fg=("#ff8888" if eta_txt == "stalled" else C_FG_DIM))
            self._banner("_prog_frame", True)
        else:
            self._prog_var.set(0)
            self._prog_lbl_file.configure(text="")
            self._prog_lbl_count.configure(text="", fg=C_FG_DIM)
            self._prog_lbl_eta.configure(text="", fg=C_FG_DIM)
            self._banner("_prog_frame", False)

        # ── Bus / fast lane strip ─────────────────────────────────────────
        # It is a QUEUE now, not a single slot: several jobs can be sent down
        # it, they run one after another, and the strip says how many are
        # still to come instead of pretending there is only ever one.
        try:
            waiting = [t for t in mgr.bus_queue()
                       if t.status == TaskStatus.PENDING]
        except Exception:
            waiting = []
        # Two small lanes (revision CL): the strip shows the 🚌 job when there
        # is one (it is the slow one, worth watching) and mentions the ⚡ one
        # that is running beside it.
        bus_cur  = mgr._current_bus
        fast_cur = mgr._current_fast
        fast_task = bus_cur if bus_cur is not None else fast_cur
        if fast_task is not None:
            pre     = "_bprog_" if bus_cur is not None else "_fprog_"
            f_total = getattr(mgr, pre + "total", 0)
            f_cur   = getattr(mgr, pre + "cur", 0)
            f_by    = (getattr(mgr, pre + "unit", "files") == "bytes")
            self._bus_var.set(
                max(0.0, min(100.0, (f_cur / f_total * 100.0) if f_total else 0.0)))
            lane = ("🚌 Bus lane" if bus_cur is not None else "⚡ Fast lane")
            name = getattr(mgr, pre + "file", "") or fast_task.description
            if len(name) > 70:
                name = "…" + name[-69:]
            self._bus_lbl_file.configure(text=f"{lane}:  {name}")

            cnt = (f"{_fmt_size(f_cur)} / {_fmt_size(f_total)}" if f_by
                   else f"{f_cur} / {f_total} files")
            f_stall = (mgr.lane_stalled_for("bus" if bus_cur is not None
                                            else True) if f_by else 0.0)
            fg2 = C_FG_DIM
            if f_by and f_stall >= self._STALL_WARN:
                cnt += (f"     ·     ⚠  NOT MOVING — no bytes for "
                        f"{self._fmt_dur(f_stall)}")
                fg2 = "#ffe066" if f_stall < self._STALL_ALARM else "#ff8888"
            elif f_by:
                cnt += f"   ·   {_fmt_size(int(getattr(mgr, pre + 'rate', 0.0)))}/s"
            if bus_cur is not None and fast_cur is not None:
                fn = os.path.basename(getattr(mgr, "_fprog_file", "") or "")
                cnt += f"     ·     ⚡ also: {fn[:30] or fast_cur.description[:30]}"
            if mgr._bus_paused and (bus_cur is not None or fast_cur is None):
                cnt += "     ·     ⏸  THE LANE IS HELD — not moving"
                fg2 = "#ffe066"
            else:
                cnt += ("     ·     the main lane is standing down for this"
                        if mgr.bus_holds_main() else
                        "     ·     runs beside the job above")
            if waiting:
                cnt += f"     ·     🚌 {len(waiting)} more in the bus queue"
            self._bus_lbl_count.configure(text=cnt, fg=fg2)
            self._banner("_bus_frame", True)
        elif waiting:
            # Nothing running in the lane yet, but the lane is not empty —
            # say so rather than showing nothing at all.
            self._bus_var.set(0)
            self._bus_lbl_file.configure(
                text=f"🚌 Bus queue:  {waiting[0].description}")
            more = (f"     ·     and {len(waiting) - 1} more"
                    if len(waiting) > 1 else "")
            self._bus_lbl_count.configure(
                text=(f"{len(waiting)} job(s) waiting in the bus lane, smallest "
                      f"first{more}"
                      + ("     ·     ⏸  THE LANE IS HELD" if mgr._bus_paused
                         else "     ·     the main lane stands down for them"
                         if mgr._bus_solo else "")),
                fg=("#ffe066" if mgr._bus_paused else C_FG_DIM))
            self._banner("_bus_frame", True)
        else:
            self._bus_var.set(0)
            self._bus_lbl_file.configure(text="")
            self._bus_lbl_count.configure(text="", fg=C_FG_DIM)
            self._banner("_bus_frame", False)

    def _progress_heartbeat(self):
        """Repaint the strips once a second, whether or not bytes are moving.

        Without this there is no way for the window to say "nothing has
        happened for four minutes": the only thing that used to repaint it was
        a byte arriving, so a stall froze the display at its last happy reading
        and left it there looking healthy.
        """
        try:
            if (self._mgr._current_task is not None or self._mgr._current_fast
                    or self._mgr._current_bus):
                self._render_progress()
        except Exception:
            pass
        try:
            self._heartbeat_id = self.after(1000, self._progress_heartbeat)
        except Exception:
            self._heartbeat_id = None

    def _on_toggle_autoclose(self):
        try:
            ed = self._mgr._editor
            ed.settings["queue_autoclose"] = bool(self._autoclose_var.get())
            ed.save_settings()
        except Exception:
            pass

    def _maybe_autoclose(self):
        """Hide the window when the list went from "has jobs" to "empty"."""
        try:
            tasks = self._mgr.get_tasks()
        except Exception:
            return
        if tasks:
            self._had_tasks = True
            return
        if not getattr(self, "_had_tasks", False):
            return
        if self._mode_now == QUEUE_MODE_CLOSED:
            self._had_tasks = False
            return
        if not self._autoclose_var.get():
            return
        # An empty list means nothing is running or waiting (Clear Done keeps
        # every PENDING / RUNNING job), so there is nothing more to check.
        self._had_tasks = False
        ed = self._mgr._editor
        prev = ed.settings.get("queue_top_mode", QUEUE_MODE_OVER_FM)
        self._hide()
        try:
            # Closing by itself must not forget which state you like it in.
            ed.settings["queue_top_mode"] = prev
            ed.save_settings()
        except Exception:
            pass

    def _refresh_now(self):
        try:
            self._do_refresh()
        except Exception:
            pass
        try:
            self._maybe_autoclose()
        except Exception:
            pass
        try:
            self._refresh_autorule_bar()
        except Exception:
            pass

    def _do_refresh(self):
        # Remember which task_id is selected
        sel_tid = self._get_selected_tid()

        self._tree.delete(*self._tree.get_children())
        tasks = self._mgr.get_tasks()

        # Two things the list never used to say out loud, and both of them are
        # exactly what you need to know when the order looks wrong:
        #   held  — this job is waiting for an EARLIER job with the same file
        #   dupe  — this job is the same job as one already in the list
        held, dupes, seen_sig = {}, {}, {}
        try:
            held = _held_map(tasks)
            for t in tasks:
                if t.status not in (TaskStatus.PENDING, TaskStatus.RUNNING):
                    continue
                sig = (t.task_type,
                       tuple(sorted(os.path.normcase(s)
                                    for s in (t.sources or []))),
                       os.path.normcase(t.dest_dir or ""))
                if sig in seen_sig:
                    dupes[t.task_id] = seen_sig[sig]
                else:
                    seen_sig[sig] = t.task_id
        except Exception as exc:
            _log(f"Queue: could not work out what is waiting for what: {exc}")

        # Where each bus job stands in the BUS QUEUE, and whether the main lane
        # is being held shut for it (revBN).  Worked out once, not per row.
        bus_pos, bus_held = {}, False
        try:
            bus_held = self._mgr.bus_holds_main()
            for i, bt in enumerate(
                    [x for x in self._mgr.bus_queue()
                     if x.status == TaskStatus.PENDING], start=1):
                bus_pos[bt.task_id] = i
        except Exception as exc:
            _log(f"Queue: bus lane order could not be worked out: {exc}")

        new_iid_for_tid: dict = {}
        cur_day = None   # track the day so we can emit a header when it changes
        for t in tasks:
            # "When" = finish time for completed tasks, else the queued time.
            when = t.finished_at if t.finished_at else t.added_at
            try:
                dt = datetime.fromtimestamp(when)
            except (OverflowError, OSError, ValueError):
                dt = datetime.now()
            day_key = dt.strftime("%Y-%m-%d")

            # Emit a day-section header row whenever the day changes
            if day_key != cur_day:
                cur_day = day_key
                today = datetime.now().strftime("%Y-%m-%d")
                yday  = (datetime.now() - timedelta(days=1)).strftime("%Y-%m-%d")
                if   day_key == today: day_label = f"Today  ·  {dt.strftime('%A %Y-%m-%d')}"
                elif day_key == yday:  day_label = f"Yesterday  ·  {dt.strftime('%A %Y-%m-%d')}"
                else:                  day_label = dt.strftime("%A  ·  %Y-%m-%d")
                self._tree.insert("", "end",
                                  values=("", "", "", f"— {day_label} —", "", ""),
                                  tags=("dayhdr",))

            time_col  = dt.strftime("%H:%M")
            lock_col  = "🔒" if t.locked else ""
            type_col  = _TASK_ICONS.get(t.task_type, str(t.task_type.value))
            sz_col    = _fmt_size(t.size_bytes) if t.size_bytes > 0 else "—"

            # ⚡ marks a job in the FAST LANE — it is small (or a same-drive
            # rename) and runs alongside the big transfer instead of behind it.
            if getattr(t, "bus", False):
                type_col = "🚌 " + type_col
            elif t.fast:
                type_col = "⚡ " + type_col
            elif getattr(t, "main_only", False) and t.status == TaskStatus.PENDING:
                type_col = "🛣 " + type_col      # kept in the main queue by hand

            if t.status == TaskStatus.PENDING and getattr(t, "preflight", "done") == "scanning":
                st_col = "🔎 Checking…"
            elif t.status == TaskStatus.PENDING and getattr(t, "preflight", "done") == "twins":
                st_col = "❓ Waiting for you"
            elif (t.status == TaskStatus.PENDING
                  and getattr(t, "wait_until", 0.0) > _time.time()):
                left = int(t.wait_until - _time.time())
                st_col = f"⏳ {t.wait_reason} ({left}s)"
            elif t.status == TaskStatus.PENDING and t.task_id in dupes:
                st_col = f"⧉ same as #{dupes[t.task_id]}"
            elif t.status == TaskStatus.PENDING and t.task_id in held:
                st_col = f"⏳ after #{held[t.task_id]}"
            elif t.status == TaskStatus.PENDING and getattr(t, "bus", False):
                # The bus lane is a QUEUE — say which place in it (revBN), and
                # whether the lane is allowed to move at all (revBT).
                pos = bus_pos.get(t.task_id, 0)
                if self._mgr._bus_paused:
                    st_col = "⏸ 🚌 lane held"
                else:
                    st_col = ("🚌 Bus lane — next" if pos <= 1
                              else f"🚌 Bus lane #{pos}")
            elif (t.status == TaskStatus.PENDING and bus_held
                  and not getattr(t, "fast", False)):
                st_col = "⏸ held for 🚌"
            elif (t.status == TaskStatus.PENDING
                  and getattr(t, "was_interrupted", False)):
                st_col = "⚠ Was interrupted"
            elif t.status == TaskStatus.PENDING and getattr(t, "resume_skip", False):
                st_col = "↺ Resuming"
            elif t.status == TaskStatus.PENDING and getattr(t, "restored", False):
                st_col = "↺ From last session"
            elif t.status == TaskStatus.RUNNING:
                if getattr(t, "bus", False):
                    st_col = ("⏸ 🚌 lane held" if self._mgr._bus_paused
                              else "🚌 Running now…")
                elif t.fast:
                    st_col = "⚡ Running…"
                elif bus_held:
                    # It IS running — it is just not being allowed to move.
                    # Saying "Running…" while the bytes are stopped is the
                    # whole problem this revision is about.
                    st_col = "⏸ stood down for 🚌"
                else:
                    st_col = "▶ Running…"
            elif t.status == TaskStatus.ERROR:
                short = (t.error_msg[:22] + "…") if len(t.error_msg) > 22 else t.error_msg
                st_col = f"⚠ {short}"
            else:
                st_col = _STATUS_ICONS.get(t.status, t.status.value)

            # Choose row tag for colour
            if t.status == TaskStatus.RUNNING:
                row_tag = "running"
            elif t.status == TaskStatus.PENDING and t.conflict_mode == "pending_conflicts":
                row_tag = "conflict_pending"
            elif t.status == TaskStatus.PENDING and t.space_warning:
                row_tag = "space_blocked"
            elif t.status == TaskStatus.PENDING and getattr(t, "bus", False):
                row_tag = "bus"
            elif t.locked and t.status == TaskStatus.PENDING:
                row_tag = "locked"
            else:
                row_tag = t.status.value   # "pending", "done", "cancelled", "error"

            iid = self._tree.insert(
                "", "end",
                values=(lock_col, time_col, type_col, t.description, sz_col, st_col),
                tags=(f"tid_{t.task_id}", row_tag),
            )
            new_iid_for_tid[t.task_id] = iid

        # Restore selection
        if sel_tid is not None and sel_tid in new_iid_for_tid:
            iid = new_iid_for_tid[sel_tid]
            self._tree.selection_set(iid)
            self._tree.see(iid)

        # Update toolbar buttons
        running = self._mgr._running
        paused  = self._mgr._paused
        pending = self._mgr.pending_count()

        if running and not paused:
            self._btn_start.configure(state="disabled")
            self._btn_pause.configure(text="⏸  Pause")
        elif paused:
            self._btn_start.configure(state="normal")
            self._btn_pause.configure(text="▶  Resume")
        else:
            self._btn_start.configure(state="normal" if pending else "disabled")
            self._btn_pause.configure(text="⏸  Pause")

        total_tasks = len(tasks)
        done_tasks  = sum(1 for t in tasks if t.status == TaskStatus.DONE)
        self._lbl_status.configure(
            text=f"{pending} pending  •  {done_tasks}/{total_tasks} done"
        )
        self.title(f"Task Queue  ({pending} pending)" if pending else "Task Queue")

        # ── Inline progress section ────────────────────────────────────────
        mgr = self._mgr
        self._render_progress()

        # ── Carried over from the last session ──────────────────────
        note = getattr(mgr, "_restored_note", "")
        if note:
            self._restore_lbl.configure(text=note)
            self._banner("_restore_frame", True)
        else:
            self._banner("_restore_frame", False)

        # ── Space-warning banner ─────────────────────────────────────────
        blocked_task = next(
            (t for t in tasks
             if t.status == TaskStatus.PENDING and t.space_warning),
            None,
        )
        if blocked_task:
            self._space_lbl.configure(text="⚠  " + blocked_task.space_warning)

            # Countdown to next auto-recheck
            rid = mgr._space_recheck_id
            if rid is not None:
                try:
                    # Tk doesn\'t expose remaining time directly; we approximate
                    # by storing the schedule time on the manager
                    sched = getattr(mgr, "_space_recheck_at", None)
                    if sched:
                        remaining_s = max(0, sched - _time.monotonic())
                        cd_txt = f"Auto-recheck in {remaining_s:.0f} s"
                    else:
                        cd_txt = "Auto-recheck scheduled"
                except Exception:
                    cd_txt = ""
            else:
                cd_txt = ""
            self._space_countdown_lbl.configure(text=cd_txt)

            self._banner("_space_frame", True)
        else:
            self._banner("_space_frame", False)

        # ── Conflict-banner update ───────────────────────────────────────────
        conflict_task = next(
            (t for t in tasks
             if t.status == TaskStatus.PENDING
             and t.conflict_mode == "pending_conflicts"
             and t.pending_conflicts),
            None,
        )
        if conflict_task:
            n     = len(conflict_task.pending_conflicts)
            names = [os.path.basename(c["src"]) for c in conflict_task.pending_conflicts[:3]]
            sample = ",  ".join(names)
            if n > 3:
                sample += f"  … +{n - 3} more"
            self._conflict_lbl.configure(
                text=(f"❗  {n} conflict(s) in: {conflict_task.description}\n"
                      f"   Files already exist at destination: {sample}")
            )
            self._banner("_conflict_frame", True)
        else:
            self._banner("_conflict_frame", False)

    # ── Button handlers ───────────────────────────────────────────────────

    def _get_selected_tid(self) -> "int | None":
        tids = self._get_selected_tids()
        return tids[0] if tids else None

    def _get_selected_tids(self) -> list:
        """Every picked job, in the order the list shows them.

        Day-header rows carry no tid_ tag, so they simply drop out — clicking
        one selects nothing rather than acting on the wrong job."""
        out = []
        for iid in self._tree.selection():
            for tag in self._tree.item(iid, "tags"):
                if tag.startswith("tid_"):
                    out.append(int(tag[4:]))
                    break
        return out

    def _on_start(self):
        self._mgr.start()

    def _on_pause(self):
        self._mgr.pause_resume()

    def _on_cancel_current(self):
        """Cancel the currently running task via the proxy's cancelled flag.

        This is the BIG job's ✖ — the progress bar it sits on belongs to that
        job.  A fast-lane file slipping past is left alone (it is measured in
        milliseconds anyway); cancel one of those from its right-click menu."""
        self._mgr._cancel_current = True

    def _on_refresh_space(self):
        """Manually trigger a disk-space recheck right now."""
        self._mgr.space_recheck_now()
        self.refresh()

    def _on_resolve_conflicts(self, mode: str):
        """Apply *mode* to all tasks that are waiting on conflict resolution."""
        self._mgr.resolve_pending_conflicts(mode)
        # Action chosen — drop the queue to the background and return the
        # keyboard to the main file manager.
        self._drop_to_background()

    def _tick(self):
        """Update the space-warning countdown label every second."""
        try:
            if not self.winfo_exists():
                return
            if self._mgr._space_blocked and self._space_frame.winfo_ismapped():
                sched = getattr(self._mgr, "_space_recheck_at", 0)
                remaining_s = max(0, sched - _time.monotonic())
                cd_txt = f"Auto-recheck in {remaining_s:.0f} s  —  or click Refresh to check now"
                self._space_countdown_lbl.configure(text=cd_txt)
        except Exception:
            pass
        self._sync_full_speed_box()
        self.after(1000, self._tick)

    def _on_smart_sort(self):
        self._mgr.smart_sort()
        self.refresh()

    def _open_rules(self):
        """Open the Smart-queue conflict-rules manager from the Task Queue."""
        try:
            self._mgr._editor.open_conflict_rules()
        except Exception:
            pass

    # ── One-tick auto-rule for the last transfer ──────────────────────────
    def _refresh_autorule_bar(self):
        """Show the last copy/move's Workspace + folder pair, and reflect whether
        a matching rule already exists.  Called on every queue refresh."""
        lt = getattr(self._mgr._editor, "_last_transfer", None)
        if not lt or not lt.get("src") or not lt.get("dst"):
            self._ar_lbl.config(text="(do a copy/move first, then tick to remember it)")
            self._ar_check.config(state="disabled")
            self._ar_combo.config(state="disabled")
            self._ar_src_combo.config(state="disabled")
            self._ar_dst_combo.config(state="disabled")
            self._ar_check_var.set(False)
            return
        self._ar_check.config(state="normal")
        self._ar_combo.config(state="readonly")
        self._ar_src_combo.config(state="readonly")
        self._ar_dst_combo.config(state="readonly")
        ws_raw = lt.get("workspace") or ""
        # A rule may already exist for a WIDER scope than "this folder" — the
        # combos are put back where that rule sits, so the tick tells the
        # truth instead of offering to save a duplicate.
        rules = _load_conflict_rules()
        found = self._find_scoped_rule(rules, lt)
        if found is not None:
            idx, s_lv, d_lv = found
            self._ar_src_scope.set(_RULE_SCOPE_LABEL.get(s_lv, "This folder"))
            self._ar_dst_scope.set(_RULE_SCOPE_LABEL.get(d_lv, "This folder"))
            self._ar_check_var.set(True)
            self._ar_policy.set(_CONFLICT_LABEL.get(
                rules[idx].get("conflict", ""), "Backup-rename old"))
        else:
            self._ar_check_var.set(False)

        eff_src, eff_dst = self._autorule_scoped_paths(lt)
        src_n = (os.path.basename(eff_src.rstrip("\\/")) or eff_src) if eff_src \
                else "ANY folder"
        dst_n = (os.path.basename(eff_dst.rstrip("\\/")) or eff_dst) if eff_dst \
                else "ANY folder"
        # Make the scope obvious: which Workspace, and warn if it would be global
        if ws_raw:
            ws_txt = f"Workspace [{ws_raw}]"
            self._ar_lbl.config(fg=C_FG_DIM)
        else:
            ws_txt = "⚠ ANY workspace"
            self._ar_lbl.config(fg=TC_WARN)
        self._ar_lbl.config(text=f"{ws_txt}:   {src_n}  →  {dst_n}   (+ subfolders)")

    def _autorule_scoped_paths(self, lt: dict) -> tuple:
        """The from→to pair the tick would actually save, after the two
        "covers" pickers have widened it."""
        s_lv = _RULE_SCOPE_NUM.get(self._ar_src_scope.get(), 0)
        d_lv = _RULE_SCOPE_NUM.get(self._ar_dst_scope.get(), 0)
        return (_rule_scope_path(lt.get("src", ""), s_lv),
                _rule_scope_path(lt.get("dst", ""), d_lv))

    def _find_scoped_rule(self, rules: list, lt: dict):
        """Find a saved rule for this transfer at ANY scope.

        Returns (index, source levels, destination levels) or None.  Without
        this, widening a rule to "1 level up" and re-opening the queue would
        show an empty tick box and quietly save a second, narrower rule beside
        the first."""
        ws = lt.get("workspace", "")
        for s_lv in (0, 1, 2, 3, -1):
            for d_lv in (0, 1, 2, 3, -1):
                idx = _find_exact_rule(
                    rules,
                    _rule_scope_path(lt.get("src", ""), s_lv),
                    _rule_scope_path(lt.get("dst", ""), d_lv), ws)
                if idx >= 0:
                    return (idx, s_lv, d_lv)
        return None

    def _on_autorule_toggle(self):
        """Tick = save (or update) a rule for this Workspace + folder pair;
        untick = remove it.  The two "covers" pickers decide whether the rule
        is written down for these exact folders or for a parent of them."""
        lt = getattr(self._mgr._editor, "_last_transfer", None)
        if not lt or not lt.get("src") or not lt.get("dst"):
            return
        rules = _load_conflict_rules()
        eff_src, eff_dst = self._autorule_scoped_paths(lt)
        # Any rule this transfer already has, at whatever scope — so changing
        # the scope MOVES the rule instead of leaving a stale one behind.
        found = self._find_scoped_rule(rules, lt)
        idx = found[0] if found else -1
        if self._ar_check_var.get():
            conflict = next((m for lbl, m in _CONFLICT_CHOICES
                             if lbl == self._ar_policy.get()), "backup_old")
            rule = {"src": eff_src, "dst": eff_dst,
                    "workspace": lt.get("workspace", ""),
                    "conflict": conflict, "enabled": True}
            if idx >= 0:
                rules[idx] = rule
            else:
                rules.append(rule)
            _save_conflict_rules(rules)
            where = " · ".join(
                p for p in (
                    f"from {self._ar_src_scope.get().lower()}"
                    if _RULE_SCOPE_NUM.get(self._ar_src_scope.get(), 0) else "",
                    f"to {self._ar_dst_scope.get().lower()}"
                    if _RULE_SCOPE_NUM.get(self._ar_dst_scope.get(), 0) else "",
                ) if p)
            self._lbl_status.config(
                text=f"Saved: always {self._ar_policy.get()}"
                     + (f"  ({where})" if where else " here"))
            self._refresh_autorule_bar()
        elif idx >= 0:
            del rules[idx]
            _save_conflict_rules(rules)
            self._lbl_status.config(text="Auto-rule removed")

    def _on_autorule_policy(self):
        """Changing the policy while the box is ticked re-saves the rule."""
        if self._ar_check_var.get():
            self._on_autorule_toggle()

    def _on_autorule_scope(self):
        """Widening/narrowing the scope: re-save the rule at the new scope if
        the box is ticked, and always redraw the "covers" label so you can see
        which folder the rule would land on before you tick it."""
        if self._ar_check_var.get():
            self._on_autorule_toggle()
        else:
            lt = getattr(self._mgr._editor, "_last_transfer", None)
            if not lt:
                return
            eff_src, eff_dst = self._autorule_scoped_paths(lt)
            self._ar_lbl.config(
                text=f"would cover:   {eff_src or 'ANY folder'}"
                     f"   →   {eff_dst or 'ANY folder'}   (+ subfolders)")

    def _on_clear_done(self):
        self._mgr.remove_finished()
        self.refresh()

    def _on_up(self):
        # Topmost first, or two rows moving up would swap past each other.
        tids = self._get_selected_tids()
        for tid in tids:
            self._mgr.move_up(tid)
        if tids:
            self.refresh()
            self._reselect(tids)

    def _on_down(self):
        tids = self._get_selected_tids()
        for tid in reversed(tids):
            self._mgr.move_down(tid)
        if tids:
            self.refresh()
            self._reselect(tids)

    def _on_lock(self):
        tids = self._get_selected_tids()
        for tid in tids:
            self._mgr.toggle_lock(tid)
        if tids:
            self.refresh()
            self._reselect(tids)

    def _on_restore_start(self):
        """▶ on the carried-over banner — lift the pause and get going."""
        self._mgr.start()
        self.refresh()

    def _on_restore_drop(self):
        """🗑 on the carried-over banner — throw the last session’s jobs
        away.  Nothing of them has run this time round, so there is nothing to
        undo; only the LIST goes."""
        tids = [t.task_id for t in self._mgr.get_tasks()
                if getattr(t, "restored", False)
                and t.status == TaskStatus.PENDING]
        if tids:
            self._mgr.remove_tasks(tids)
        self._mgr._restored_note = ""
        self._mgr.discard_state()
        self.refresh()

    def _on_cancel_bus(self):
        """✖ on the bus-lane strip — stops the job in the SECOND lane only.

        Cancel is per task (see _QueueProgressProxy.cancelled), so the big
        transfer this one is running beside carries straight on."""
        # The strip shows the 🚌 job when there is one, else the ⚡ one.
        t = self._mgr._current_bus or self._mgr._current_fast
        if t is not None:
            t.cancel_requested = True

    def _on_bus(self):
        """🚌 — send the picked jobs down the bus lane (a toggle)."""
        tids = self._get_selected_tids()
        if not tids:
            self._lbl_status.configure(text="Pick a row first")
            return
        in_lane = self._mgr.bus_ids()
        # Mixed selection counts as "put them ALL in" — pressing it again with
        # the same rows picked then takes them all back out.
        on = not all(t in in_lane for t in tids)
        n  = self._mgr.set_bus(tids, on)
        self.refresh()
        self._reselect(tids)
        self._update_bus_btn()
        if not n:
            self._lbl_status.configure(
                text="Only a job that has not started yet can change lane "
                     "(and a job already in the main queue has nothing to leave)")
            return
        if not on:
            self._lbl_status.configure(
                text=f"🛣 {n} job(s) moved to the normal queue — they stay "
                     f"there whatever their size (right-click the row to undo)")
        elif self._mgr._paused:
            self._lbl_status.configure(
                text=f"🚌 {n} job(s) in the bus lane — the queue is PAUSED, "
                     f"press ▶ Start")
        elif self._mgr._bus_solo:
            self._lbl_status.configure(
                text=f"🚌 {n} job(s) in the bus lane — the main lane is "
                     f"standing down for them")
        elif self._mgr._bus_paused:
            self._lbl_status.configure(
                text=f"🚌 {n} job(s) in the bus lane — but the lane is HELD "
                     f"(untick 🚌 paused to let it go)")
        else:
            self._lbl_status.configure(
                text=f"🚌 {n} job(s) in the lane — smallest first, beside the "
                     f"running one")

    def _on_auto_lane(self):
        """Right-click row > the size rule picks the lane again (revision CL)."""
        tids = self._get_selected_tids()
        n = self._mgr.set_auto_lane(tids) if tids else 0
        self.refresh()
        self._reselect(tids)
        self._update_bus_btn()
        self._lbl_status.configure(
            text=(f"{n} job(s) back under automatic lane choice" if n else
                  "None of the picked jobs was kept in the main queue by hand"))

    def _on_bus_clear(self, _event=None):
        """RIGHT-click 🚌 — empty the bus lane in one press."""
        n = self._mgr.clear_bus_lane()
        self.refresh()
        self._update_bus_btn()
        if n:
            self._lbl_status.configure(
                text=f"🚌 lane emptied — {n} job(s) back in the normal queue")
        elif any(t.status == TaskStatus.RUNNING for t in self._mgr.bus_queue()):
            self._lbl_status.configure(
                text="The only job left in the lane is already RUNNING — tick "
                     "🚌 paused to hold it, or ✖ Cancel and ↺ Resume it later")
        else:
            self._lbl_status.configure(text="The bus lane is empty")
        return "break"

    def _update_bus_btn(self, _event=None):
        """The 🚌 button is a TOGGLE — say which way it is about to go.

        "jag ser inte något sätt att … 'ta bort från' bus lane": the way was
        always this button, it simply never admitted it (revBT)."""
        try:
            tids    = self._get_selected_tids()
            in_lane = self._mgr.bus_ids()
            out     = bool(tids) and all(t in in_lane for t in tids)
            self._btn_bus.configure(
                text="🚌 Out of lane" if out else "🚌 Do it now")
        except Exception:
            pass

    def _on_tree_menu(self, event):
        """Right-click on a job row."""
        iid = self._tree.identify_row(event.y)
        if iid and iid not in self._tree.selection():
            self._tree.selection_set(iid)
        tids = self._get_selected_tids()
        if not tids:
            return "break"
        menu = tk.Menu(self, tearoff=0)
        menu.add_command(
            label="📋  Show what is missing  (according to the .sfv) …",
            command=self._on_show_missing)
        menu.add_command(
            label="⏩  Unpack anyway  (ignore the .sfv / missing parts)",
            command=self._on_force_unpack)
        menu.add_command(
            label="🛣  Let the program choose the lane again  (after “Out of lane”)",
            command=self._on_auto_lane)
        try:
            menu.tk_popup(event.x_root, event.y_root)
        finally:
            try:
                menu.grab_release()
            except Exception:
                pass
        return "break"

    def _on_show_missing(self):
        """📋 The full list of files the .sfv promises that are not in the
        folder - the status column only has room for the first three."""
        tids = self._get_selected_tids()
        task = next((t for t in self._mgr.get_tasks()
                     if t.task_id in tids and t.task_type == TaskType.UNPACK),
                    None)
        if task is None or not task.sources:
            self._lbl_status.configure(text="Pick an UNPACK job first")
            return
        archive = task.sources[0]
        lines = [f"Archive:  {archive}", ""]
        rep = _sfv_check(archive)
        if rep:
            for r in rep:
                lines.append(f"{r['sfv']} lists {r['total']} files - "
                             f"{len(r['missing'])} of them are NOT in the folder:")
                lines.extend(f"      {m}" for m in r["missing"])
                lines.append("")
            lines.append("(The .sfv itself is there - it is the list the files "
                         "are checked against.)")
        else:
            lines.append("No .sfv file says anything is missing right now.")
            if task.wait_reason:
                lines.append("")
                lines.append(f"The job is waiting because:  {task.wait_reason}")
        win = tk.Toplevel(self)
        win.configure(bg=C_BG)
        win.geometry("720x420")
        _setup_toplevel(win, "Missing according to the .sfv",
                        self.winfo_toplevel())
        txt = tk.Text(win, bg=C_BG2, fg=C_FG, font=("Consolas", 10),
                      wrap="none", insertofftime=0, insertontime=9999999,
                      relief="flat", padx=10, pady=8)
        sb = ttk.Scrollbar(win, orient="vertical", command=txt.yview)
        txt.configure(yscrollcommand=sb.set)
        btn = ttk.Button(win, text="Close  (Esc)", command=win.destroy)
        btn.pack(side="bottom", anchor="e", padx=10, pady=8)
        sb.pack(side="right", fill="y")
        txt.pack(side="left", fill="both", expand=True)
        txt.insert("1.0", "\n".join(lines))
        txt.configure(state="disabled")
        btn.focus_set()

    def _on_force_unpack(self):
        """⏩ Unpack anyway — do not wait for the .sfv / the rest of the parts."""
        tids = self._get_selected_tids()
        n = self._mgr.force_unpack_tasks(tids) if tids else 0
        self.refresh()
        self._reselect(tids)
        self._lbl_status.configure(
            text=(f"⏩ {n} unpack job(s) released - no more waiting for the .sfv"
                  if n else
                  "Only an UNPACK job that is waiting (or gave up) can be forced"))

    def _on_resume(self):
        """↺ Resume — carry on with jobs that stopped part-way."""
        tids = self._get_selected_tids()
        if not tids:
            self._lbl_status.configure(
                text="Pick a finished or cancelled row first")
            return
        n = self._mgr.resume_tasks(tids)
        self.refresh()
        if not n:
            self._lbl_status.configure(
                text="Only a job that has STOPPED can be resumed — a running "
                     "one is already carrying on")
            return
        self._lbl_status.configure(
            text=f"↺ {n} job(s) resumed — everything already copied is skipped, "
                 f"it carries on from where it stopped")

    def _open_queue_store(self):
        """🗃 Queues… — park this queue under a name, or bring one back."""
        try:
            _QueueStoreDlg(self, self._mgr)
        except Exception as exc:
            _log(f"Queue store could not be opened: {exc}")
            self._lbl_status.configure(text=f"Queues: {exc}")
        self.refresh()

    def _on_cancel_task(self):
        for tid in self._get_selected_tids():
            self._mgr.cancel_task(tid)

    def _on_remove(self):
        """🗑 — take the picked jobs out of the list altogether.

        Cancel leaves the row sitting there marked ✖, which is right for "I
        changed my mind about that one" but no help at all when the list has
        two jobs you queued by mistake and you want them GONE."""
        tids = self._get_selected_tids()
        if not tids:
            self._lbl_status.configure(text="Pick a row first")
            return
        removed, running = self._mgr.remove_tasks(tids)
        self.refresh()
        self._update_bus_btn()
        if running:
            self._lbl_status.configure(
                text=f"{removed} taken out of the queue  ·  {running} still "
                     f"running (stop it with ✖ on the progress bar)")
        else:
            self._lbl_status.configure(
                text=f"{removed} job(s) taken out of the QUEUE altogether "
                     f"(the 🚌 button is the one for the bus lane)")

    def _reselect(self, tids):
        if isinstance(tids, int):
            tids = [tids]
        want = {f"tid_{t}" for t in tids}
        found = [iid for iid in self._tree.get_children()
                 if want & set(self._tree.item(iid, "tags"))]
        if found:
            self._tree.selection_set(found)
            self._tree.see(found[0])

def _do_single_copy_move(src: str, dst_dir: str, move: bool,
                         conflict_mode: str, parent_win) -> tuple:
    """Copy or move one file/folder *src* into *dst_dir*.

    Returns (new_conflict_mode, cancelled).
    conflict_mode may be upgraded to overwrite_all/skip_all by the user.

    NOT CALLED BY ANYTHING (checked 2026-09-27) — every copy and move goes
    through the task queue's _run_copy_move these days.  Before wiring this
    back up, note that it only knows four of the dialog's answers: "Backup-
    rename old" and the *_ALL answers it does not recognise fall through to
    the overwrite branch, which would destroy the very file the user asked to
    keep.  The queue path handles all of them.
    """
    name = os.path.basename(src)
    dest = os.path.join(dst_dir, name)
    is_dir = os.path.isdir(src)

    # ── Conflict handling ─────────────────────────────────────────────────
    if os.path.exists(dest):
        mode = conflict_mode

        if mode == "ask":
            dlg = _ConflictDlg(parent_win, src, dest)
            parent_win.wait_window(dlg)
            action = dlg.action
            if action == _ConflictDlg.OVERWRITE_ALL:
                conflict_mode = "overwrite_all"
                action        = _ConflictDlg.OVERWRITE
            elif action == _ConflictDlg.SKIP_ALL:
                conflict_mode = "skip_all"
                action        = _ConflictDlg.SKIP
            if action in (_ConflictDlg.SKIP, "skip_all"):
                return conflict_mode, False
            if action == _ConflictDlg.CANCEL:
                return conflict_mode, True
            if action == _ConflictDlg.AUTO_RENAME:
                dest = _auto_rename_path(dest)
            # OVERWRITE falls through

        elif mode == "overwrite_all":
            pass   # fall through to actual copy/move

        elif mode == "overwrite_older":
            try:
                src_mtime = os.path.getmtime(src)
                dst_mtime = os.path.getmtime(dest)
                if src_mtime <= dst_mtime:
                    return conflict_mode, False   # dest is same age or newer → skip
            except Exception:
                pass  # can't stat → overwrite

        elif mode == "skip_all":
            return conflict_mode, False

        elif mode == "auto_rename":
            dest = _auto_rename_path(dest)

        # Remove existing dest so shutil doesn't complain (for dirs)
        if os.path.exists(dest) and mode not in ("auto_rename", "ask"):
            try:
                if os.path.isdir(dest):
                    shutil.rmtree(dest)
                else:
                    os.remove(dest)
            except Exception:
                pass

    # ── Perform the operation ─────────────────────────────────────────────
    if is_dir:
        if move:
            shutil.move(src, dest)
        else:
            shutil.copytree(src, dest)
    else:
        if move:
            shutil.move(src, dest)
        else:
            shutil.copy2(src, dest)

    return conflict_mode, False   # (updated mode, cancelled=False)



class EditorFrame(tk.Frame):

    def __init__(self, master):
        super().__init__(master)
        self.master = master

        self.settings = {
            "show_hidden": False,
            "show_system": False,
            "show_icons": True,     # Total-Commander-style shell icons per file type
            "show_build_in_title": False,   # revCC: build stamp after "File Manager" in the title bar
            "queue_in_statusbar": False,    # revCI: live job line in the main status bar (OFF - the Task Queue window shows it)
            # revBR — the icon in front of a file is the icon of the PROGRAM
            # that opens it.  DefaultHub already says who owns a .pdf or a
            # .jpg, and Icons\<Program>.ico already exists for every program
            # in the tree, so nothing new has to be invented and nothing has
            # to be started: a .pdf wears PDFull's icon, a .jpg SeeView's.
            # Off, the panels show Windows' own shell icons as before.
            "suite_icons": True,
            # …except text & code.  DefaultHub's "text" kind is ONE kind for
            # .py .json .txt .md .log .csv .xml, so with this off every one of
            # them wears the same editor icon and the types stop telling
            # themselves apart at a glance.  Turn this ON to leave that one
            # kind to Windows and keep the program icons for all the rest.
            "suite_icons_skip_text": False,
            "size_group_digits": True,   # Size column: 9133144 → "9 133 144 KB"
            # Folders normally have an EMPTY Size cell until Alt+Shift+Enter
            # measures them.  Turn this on and every folder listing measures
            # itself the moment it is shown — the "folders show a size too"
            # MODE rather than a per-press action.  Off by default on purpose:
            # a folder of 200 000 files costs a full disk walk every time you
            # step into its parent.  It runs in the background and the Size
            # cells simply fill in, so it never blocks the list.
            "auto_folder_sizes": False,
            # Extensions that open in the BUILT-IN reader on Enter / double-click
            # (comma-separated).  Everything else opens in its external program.
            # F3 always uses the reader; F4 always the external program.
            "reader_extensions": "nfo, txt",
            # ── Copy/move throttle — keep the machine usable during big jobs ──
            # TWO SEPARATE MECHANISMS, and only the first one is on by default:
            #
            #   io_background   drop the copy's threads to Windows background
            #                   I/O priority, so anything you do overtakes it
            #                   on the disk queue.  Free on an idle machine —
            #                   with nothing competing, nothing overtakes and
            #                   the copy runs flat out.  This is what "give the
            #                   big file less power" was always supposed to be.
            #   copy_flush_mb   flush the write-behind cache every N MB so the
            #                   dirty page backlog cannot grow into gigabytes
            #                   and take the whole machine down with it.
            #   throttle_*      an outright percentage cap.  OFF by default: it
            #                   makes a copy take longer without giving the
            #                   disk queue back to anybody, so it is the wrong
            #                   answer to "the machine is unusable" and only
            #                   worth it when you want a copy to crawl.
            #
            # The percentage numbers used to be 5 s → 60 %, 15 s → 30 %,
            # 30 s → 50 %: a 6 GB file is past all three before it has really
            # started, so a 12 GB copy ran its whole length at 30 % of the
            # speed the disk could do.  They arrive LATE and stay GENTLE now.
            "io_background":          True,
            "copy_flush_mb":          64,   # 0 = never flush (old behaviour)
            "throttle_enabled":       False,
            "throttle_soft_after_s":  60,   # after this long ON ONE FILE …
            "throttle_soft_pct":      80,   # … cap it to this % of full speed
            "throttle_hard_after_s":  300,  # after this long ON ONE FILE …
            "throttle_hard_pct":      60,   # … cap it further
            "throttle_batch_after_s": 600,  # after the whole job has run this long
            "throttle_batch_pct":     70,   # … cap the whole job to this %
            "copy_chunk_kb":          4096, # block size for chunked copy
            # ── FAST LANE — small files never wait behind a huge transfer ──
            # A copy/move whose total size is under fastlane_max_mb (or a
            # same-drive MOVE, which is only a rename and therefore instant)
            # runs in its OWN worker, in parallel with the big job.  While it
            # runs, the big job pauses (fastlane_pause_big) so the small one
            # gets the whole disk and is over in a blink.
            "fastlane_enabled":  True,
            "fastlane_max_mb":   50,
            "fastlane_pause_big": True,
            "default_editor": "hub_editor",
            "remember_last": True,
            "unpack_method": "background",
            "unpack_order":  "smallest_first",
            "favorites": [
                ("Home",      os.path.expanduser("~")),
                ("Desktop",   os.path.join(os.path.expanduser("~"), "Desktop")),
                ("Documents", os.path.join(os.path.expanduser("~"), "Documents")),
            ],
            "view_mode": "long",
            "force_helpdir_saves": False,
            # Permanent start directories – changed via Alt-F1/F2 menu
            "start_dir_left":  DEFAULT_START_DIR,
            "start_dir_right": DEFAULT_START_DIR,
            # Default column widths for file panels (pixels)
            "column_widths": {
                "name":       320,
                "type":       100,
                "flag":        26,
                "size":        90,
                "modified":   140,
                "attributes":  70,
            },
            # Per-extension custom openers (overrides Windows default).
            # Key = lower-case extension with dot, e.g. ".pdf"
            # Value = full path to executable, e.g. "C:\\Program Files\\SumatraPDF\\SumatraPDF.exe"
            "custom_openers": {},
            # Optional command-line arguments per extension ("%1" = the file).
            "custom_opener_args": {},
            # ---- F4: the external program, decided HERE and not by Windows ----
            # Empty = use whatever Windows associates with the file. Set it to
            # your own editor and F4 uses that instead. "%1" in f4_args is
            # replaced by the file name; with no %1 the name is appended.
            # f4_extensions empty = the program is used for EVERY file; a list
            # like "txt, nfo, log, md" limits it to those.
            "f4_program":    "",
            "f4_args":       "",
            "f4_extensions": "",
            # ---- Shift+F4: a SECOND external program (e.g. a different editor) --
            # Same rules as the F4 program above.  Leave the program empty and
            # Shift+F4 falls back to the Windows association (its old behaviour).
            "f4b_program":    "",
            "f4b_args":       "",
            "f4b_extensions": "",
            # F3 built-in reader: allow editing + saving (Ctrl+S), not just read
            "reader_editable": True,
            # ---- F3 = F4 when you have picked your own program ----------------
            # ON: F3 hands the file to the SAME external program F4 would use
            # (per-extension opener first, then the F4 program), so one editor
            # serves both keys and the built-in reader stays out of the way.
            # It only kicks in when such a program actually covers that file
            # type — otherwise the built-in reader still opens it, so F3 never
            # becomes a dead key.  Shift+Enter always forces the built-in one.
            "f3_use_external": True,
            # ⚖ Side comparison (the scales button between ⚡ and 🗑): colour the
            # file names that exist in BOTH panels — green newest, red oldest.
            # Remembered between sessions; it is meant to be left switched on.
            "compare_sides_on": False,
            # ⚖ second stage: also flag the files that are on one side only.
            "compare_sides_singles": False,
            # Task Queue window: which of the ⚡ button's four states it opens
            # in — 0 closed · 1 open, no priority · 2 above the FILE MANAGER ·
            # 3 above everything.  LEFT-click the ⚡ button to cycle them,
            # RIGHT-click to close.  It still never takes the keyboard in any
            # of them — the arrow keys always stay in the file list.
            "queue_top_mode": QUEUE_MODE_OVER_FM,
            # A job parked on a name clash used to pop the Task Queue window
            # IN FRONT of the file manager, every single time — which is most
            # copies, when you keep copying the same programs to the same
            # folders.  Off: the ⚡ button turns into ⚠ and the status line
            # says so, and nothing jumps.  (Only read in "queue" alert mode.)
            "queue_alert_front":  False,
            # ── When a copy hits a name clash ─────────────────────────────
            #   "bar"    — a red strip in the MAIN window above the status bar.
            #              Loud, never covers the panels, never takes the arrow
            #              keys; Ctrl+Alt+1…5 answer it.  Default.
            #   "dialog" — stop and ask at once, one file at a time, the way it
            #              used to work.  Nothing is ever missed; it interrupts.
            #   "queue"  — say nothing but the ⚠ button and the status line, and
            #              wait in the Task Queue until you go and look.
            # revAP — the cursor trace log.  On by default: the fault it
            # exists to catch is rare and unpredictable, and a log you have to
            # remember to switch on first is a log that is always off when the
            # thing you were waiting for finally happens.  It prunes itself, so
            # leaving it on costs nothing but a text file that never grows past
            # trace_hours of history.
            # revAR — build watch.  Which folders hold the sources, which
            # hold the built one-folder programs, and which programs you
            # actually care about (1---Blandat has 130 .py files in it; only a
            # handful are programs you run).  Nothing is watched until you
            # tick it in Settings ▸ My programs.
            # Both derived from APP_ROOT, never a hard-coded drive letter: Py,
            # Folder-exe, Helpfiles and Icons are siblings under one home, and
            # that home is free to move without this file being edited. In the
            # old flat layout neither subfolder exists, so the fallback is the
            # root itself, exactly as before.
            "watch_src_dirs":   [str(APP_ROOT / "Py")
                                 if (APP_ROOT / "Py").is_dir() else str(APP_ROOT)],
            "watch_build_dirs": [str(APP_ROOT / "Folder-exe")
                                 if (APP_ROOT / "Folder-exe").is_dir()
                                 else r"B:\0---Burn\0---Util\0---Mina_program"],
            "watch_chosen":     [],
            "watch_at_startup": True,
            "trace_cursor": True,
            "trace_hours":  48,
            "conflict_alert_mode": "bar",
            # revAO — with the bar up, arm its first choice ("1 Overwrite old")
            # so plain Enter answers and ←/→ walk to another choice.  Off = the
            # original behaviour: the bar never takes the keyboard at all and
            # only Ctrl+Alt+1…5 or the mouse answer it.
            "conflict_bar_keys": True,
            # Same size AND same modified time = the same file.  On: those are
            # skipped silently, so re-copying a folder you already copied asks
            # nothing.  Off (default) they are treated like any other clash.
            "conflict_skip_identical": False,
            # How wide the Task Queue's one-tick auto-rule is saved by default.
            # 0 = these exact folders, 1-3 = that many folders up, -1 = any.
            # 1 up on the destination is what makes one rule cover every dated
            # sub-folder that will be created under a working folder.
            "rule_scope_src": 0,
            "rule_scope_dst": 0,
            # Network locations opened recently (the drive menu offers them back)
            "net_recent": [],
            # The places the "Go to:" box on the Workspace bar has actually
            # landed on (DEL 51), newest first — the ▾ list next to the box.
            "goto_history": [],
            # ── Drive memory (per panel, per volume) ──────────────────────
            # Picking a drive from the drive menu used to always land in its
            # ROOT, so hopping D: → C: → D: meant walking the whole way back
            # down every time.  On (default): each panel remembers the last
            # folder you stood in on each volume and goes straight back there.
            # The ↖ toolbar button still jumps to the root whenever you do
            # want the root.
            "drive_memory": True,
            # {"left": {"d:": "D:\\Foo\\Bar", ...}, "right": {...}} — written
            # when you actually switch drive, not on every step.
            "drive_last": {},
            # Colour completely-empty folders (no files AND no sub-folders)
            # differently from normal (blue) folders, so they stand out.
            "mark_empty_dirs": True,
            # A Workspace to load automatically on start ("" = none).  Set it by
            # right-clicking a Workspace button ▸ "Start with this workspace".
            "startup_workspace": "",
            # Window size / position, remembered between sessions
            "window_geometry":  "",
            "window_maximized": False,
            # Quick View panel (Ctrl+Q)
            "quickview_open":  False,
            "quickview_width": 380,
            "quickview_mode":  "auto",      # auto | text | hex | image
            # Command bar (shown under the panels)
            "cmdbar_open":  False,
            "cmdbar_shell": "cmd",          # cmd | powershell
            # Watch the current folders and refresh automatically on change
            "auto_refresh":    True,
            "auto_refresh_ms": 1500,
            # Relocator (DEL 50): right-click ⤴ runs every rule at once — ask
            # first (one yes/no with the count) unless this is turned off.
            "relocator_confirm": True,
            # ... and close the "running" window by itself after a clean run.
            "relocator_autoclose": True,
            # Unpacking (DEL 20b).  The waiting is on by default because it
            # costs nothing when the archive is whole; the three tidy-ups are
            # off, because each of them moves or renames something.
            "unpack_wait_enabled":      True,
            "unpack_wait_seconds":      20,
            "unpack_wait_max_minutes":  60,
            "unpack_subfolder":         False,
            "unpack_delete_after":      False,
            "unpack_mark_source_folder": False,
            # Show the Task Queue when an unpack is queued.  Nothing visible
            # happens in the panels while an archive is being extracted, so
            # "it went in the queue" on its own leaves you wondering whether
            # anything took.  (Background, never focus-stealing.)
            "unpack_show_queue":        True,
            # Unpack into the OTHER panel's folder — including archives found
            # by picking whole FOLDERS, which used to always extract where they
            # lie.  A second drive unpacks far faster than the one being read
            # from, and "the same folder" is still one click away: point the
            # other panel at it.
            "unpack_dest_other":        True,
            # Keep folders grouped above files when sorting. Off = one
            # mixed list, so a date sort interleaves folders and files.
            # Enter / double-click use my own openers (per-type → F4 program →
            # DefaultHub) instead of going straight to Windows.  Off by
            # default: a plain double-click firing an external program you had
            # forgotten about is exactly how three MP3 players once piled up.
            "activate_uses_openers":    False,
            # DefaultHub's table on a plain Enter / double-click.  ON, unlike
            # the line above, and the two are not the same kind of setting:
            # that one is a program you may have forgotten you set, this is
            # the one file where he writes down which program owns a file
            # type for the whole tree.  Off, a .jpg or a .pdf goes to a
            # Windows association that does not exist here — nothing happens.
            "activate_uses_hub":        True,
            # Enter / double-click on a .py, .bat, .exe … STARTS it.  On, and
            # it has to be: DefaultHub's "text" kind lists .py, .bat and .ps1
            # (rightly — they are text to every other program in the tree),
            # and without this a double-click on any of his 140-odd programs
            # opened the editor instead of running it.  F4 still edits.
            "activate_runs_programs":   True,
            "sort_folders_first": True,
            # Folders follow the FILE sort instead of keeping their own order
            # (Workspace bar, "Folders sort like files").  Off = the classic
            # two-orders behaviour with the hollow ▵ arrow.
            "folders_follow_file_sort": False,
            # Dates: keep what the source/archive says, or stamp today
            "keep_dates_unpack": True,
            "keep_dates_copy":   True,
            # Deletion → tiered in-place trash.  Delete RENAMES the file to a
            # ~deleted~<date>~ name (freeing the original name immediately) and
            # hides it; a startup sweep physically removes old trash.
            "delete_use_trash":        True,   # off = straight to Recycle Bin
            "trash_small_max_mb":      5,      # < this = "small" tier
            "trash_small_weeks":       2,      # small trash purged after N weeks
            "trash_large_hours":       24,     # large trash purged after N hours (cap 30)
            "trash_startup_delay_min": 5,      # wait this long after start, then sweep
            # (legacy, still read so old settings files don't error)
            "auto_purge_enabled": False,
            "auto_purge_days":    8,
            # Default sort order for a fresh tab.  Each is [column, reverse].
            # Columns: "#0" (Name), "type", "size", "modified", "attributes".
            # Factory default: files newest-first, folders alphabetically.
            "default_sort_files": ["modified", True],
            "default_sort_dirs":  ["#0",       False],
            # Task Queue: show the queue window automatically when a task is
            # added.  It is a NON-modal, non-covering window (opens in a screen
            # corner and never steals focus), so the file manager stays fully
            # usable — "in the background" without hiding.  Turn this off to keep
            # it fully hidden and only open it with the ⚡ toolbar button.
            # Backup-rename: where "Yes + move" sends the renamed copies.
            "backup_move_dir":    "",
        }
        self.last_positions = {}
        self.rename_item = None
        self.rename_data = None
        self._trash: list = []   # soft-deleted paths (hidden but not yet removed from disk)
        self.load_settings()

        # Side data files (all under Helpfiles/redigerare/)
        self.hotlist     = _load_json_list(HOTLIST_PATH)    # favourite local folders
        self.folder_sorts = _load_json_dict(FOLDER_SORTS_PATH, portable=True)  # per-folder sort override
        self.command_lib = _load_json_list(COMMANDS_PATH)   # saved shell commands
        self.keymap      = load_keymap()                    # user keyboard shortcuts
        self.oplog       = OperationLog(self)               # undo history
        self.tools       = load_tools()                     # "Send to" hooks
        self.tagstore    = TagStore()                       # colour labels
        # Extension → colour, for the file lists (Settings ▸ Customization)
        self.ext_colours: dict = {}
        self.reload_ext_colours()
        self.apply_date_policy()                            # dates: keep or stamp
        self._load_pending_delete()                         # crash-safe delete marks
        # Whatever the queue still had to do when the program last closed.
        # Deferred: the panels and the toolbar have to exist before the Task
        # Queue can be put in front of them.
        self.after(700, self._restore_task_queue)

        # Background unpack queue (legacy; kept for compatibility)
        self.archive_queue = queue.Queue()
        self._unpack_thread = threading.Thread(
            target=self._process_archive_queue, daemon=True
        )
        self._unpack_thread.start()

        # Unified task queue (copy / move / pack / unpack)
        self.task_queue_mgr = TaskQueueManager(self)

        # DEL 49: originals of locked files that were copied across and must be
        # removed once their program lets go.  Loaded now, retried for the life
        # of the session (and on every future start until they succeed).
        self._load_unlock_deletes()
        self.after(5_000, self._retry_unlock_deletes)

        # ⚖ Side comparison (DEL 48): remembered between sessions, because it is
        # meant to be a toggle you can just leave switched on.  Set BEFORE the
        # toolbar is built so the button draws in the right state.
        self.compare_sides_on = bool(self.settings.get("compare_sides_on", False))
        self.compare_sides_singles = bool(
            self.settings.get("compare_sides_singles", False))
        self._compare_btn     = None
        self._cmp_pending     = False

        self._create_toolbar()
        self._update_trash_btn()   # reflect any trash loaded from settings
        self._create_context_menu()
        self._bind_keys()

        # Workspace bar (between toolbar and panels)
        self._ws_apply_left  = tk.BooleanVar(value=True)
        self._ws_apply_right = tk.BooleanVar(value=True)
        self._ws_bar = tk.Frame(self, bg=C_BG3, height=26)
        self._ws_bar.pack(fill="x")

        # Dual panel
        self.active_panel = "left"
        self.panes = ttk.Panedwindow(self, orient=tk.HORIZONTAL)
        self.panes.pack(fill="both", expand=True)

        self.left_holder  = ttk.Frame(self.panes)
        self.right_holder = ttk.Frame(self.panes)
        self.panes.add(self.left_holder,  weight=1)
        self.panes.add(self.right_holder, weight=1)

        # Tab-bar frames – packed first so they appear above the file panels.
        # Each sits inside a horizontally-scrollable canvas so a long row of
        # tabs can be scrolled (mouse wheel over the strip, or the thin
        # scrollbar that appears only when the tabs overflow).
        self._tabbar_left_frame  = self._make_tab_scroller(self.left_holder,  "left")
        self._tabbar_right_frame = self._make_tab_scroller(self.right_holder, "right")

        # ⚖ (DEL 48) — the button carries its own state in its colour, because
        # it can stay switched on for hours and "is it in or out?" should not
        # need a squint at one small character.
        try:
            _st = ttk.Style()
            _st.configure("CmpOff.TButton",     foreground=C_CMP_BTN_OFF)
            _st.configure("CmpSingles.TButton", foreground=C_CMP_BTN_SINGLES)
        except Exception:
            pass

        self.left_panel  = FilePanel(self.left_holder,  "left",  self)
        self.right_panel = FilePanel(self.right_holder, "right", self)
        self.left_panel.pack(fill="both",  expand=True)
        self.right_panel.pack(fill="both", expand=True)
        # _bind_keys() ran before the panels existed, so give each tree its own
        # cursor-jump bindings now (see bind_panel_jumps for why they are
        # needed on the widget and not only via bind_all).
        self.bind_panel_jumps(self.left_panel)
        self.bind_panel_jumps(self.right_panel)
        # Fill the drive-menu caches (mapped network drives + portable devices)
        # in the background, so the first Alt+F1 is instant instead of waiting
        # for a `net use` call and a shell-namespace walk.
        _mtp_warm_caches()

        # ── Tab state ─────────────────────────────────────────────────────
        self.left_tabs     = [self.left_panel.current_path]
        self.left_tab_idx  = 0
        self.right_tabs    = [self.right_panel.current_path]
        self.right_tab_idx = 0
        # Per-tab metadata, kept parallel to left_tabs / right_tabs.
        #   saved  : True  = part of the loaded Workspace
        #            False = temporary / unsaved (amber "○")
        #   locked : True  = YOU protected this tab (🔒).  It refuses to close
        #            until you unlock it.  This — and nothing else — is what
        #            protects a tab; "saved" only decides the amber tint.
        #   sort   : [f_col, f_rev, d_col, d_rev]  or None (use the default)
        # The first tab is treated as "saved" so it looks normal until you
        # actually start using Workspaces.
        self.left_tab_meta  = [{"saved": True, "locked": False,
                                "sort": self.left_panel.get_sort_state()}]
        self.right_tab_meta = [{"saved": True, "locked": False,
                                "sort": self.right_panel.get_sort_state()}]
        # "Ignore tab locks" on the Workspace bar: while it is ticked a 🔒 tab
        # closes anyway (the lock is kept, just not enforced) — for clearing a
        # whole side out in one go.
        self._ws_unlock = tk.BooleanVar(value=False)
        # A side is "in Workspace mode" only after a Workspace is loaded or saved
        # on it.  Until then tabs are neutral (closable, not amber) — the classic
        # behaviour for people who do not use Workspaces at all.
        self._ws_active = {"left": False, "right": False}
        # Name of the Workspace currently loaded on each side (or None).  While a
        # side is in a Workspace, any EXTRA tabs you open are auto-remembered
        # (half-saved) into that Workspace's *_extra list — see _ws_autosave_extras.
        self._ws_name = {"left": None, "right": None}
        # Where each Workspace was standing when you left it: (name, side) ->
        # (tab index, that tab's folder).  Switching to another Workspace and
        # back used to put you on tab 1 of each panel, whatever you had been
        # working in.  Session only, on purpose — at program start nothing is
        # remembered, so the ★ start-up Workspace opens on its first tabs.
        self._ws_spot: dict = {}
        # ── Tab pairs (F8 cycles them) ─────────────────────────────────────
        # A "pair" links one LEFT tab with one RIGHT tab.  Pressing F8 jumps the
        # left panel to the pair's left tab AND the right panel to its right tab
        # in one keypress — so you can bounce between two whole L+R layouts while
        # copying files back and forth, without two separate tab clicks.  Pair 1
        # is implicit = the leftmost tab on each side (index 0,0); user pairs
        # (2,3,…) live in self._tab_pairs as {"left": idx, "right": idx}.  They
        # are remembered per Workspace.
        self._tab_pairs: list = []
        self._pair1_in_cycle: bool = True
        self._pair_pos: int = 0
        # Closed-tab history: list of path strings (most recent last)
        self.closed_tabs: list = []
        # DnD: tracks which panel side is the current drag source (or None)
        self._dnd_source_side: str | None = None
        # Register a Treeview style variant used for drop-hover highlight
        style = ttk.Style()
        try:
            style.configure("DnDHover.Treeview", background="#1e3a5f",
                            fieldbackground="#1e3a5f")
            # Give rows enough height for the 16-px shell icons to sit centred
            # without being clipped (the default can be as low as 16).
            try:
                cur_rh = int(style.lookup("Treeview", "rowheight") or 0)
            except Exception:
                cur_rh = 0
            if cur_rh < 18:
                style.configure("Treeview", rowheight=18)
        except Exception:
            pass

        self._render_tab_bar("left")
        self._render_tab_bar("right")

        # ── Workspace state ────────────────────────────────────────────────
        self.workspaces: dict = self._load_workspaces()   # {name: {left:[..], right:[..]}}
        self._render_workspace_bar()

        # ── Command bar (packed above the status bar) ──────────────────────
        self.cmdbar = CommandBar(self, self)
        if self.settings.get("cmdbar_open"):
            self.cmdbar.show()

        # ── Inline conflict bar (packed just above the status bar) ─────────
        self._create_conflict_bar()

        self._create_statusbar()
        # Auto-load the chosen start-up Workspace (right-click a Workspace ▸
        # "Start with this workspace"), before the first refresh so there is no
        # flash of the default folders.
        self._apply_startup_workspace()
        self.refresh_panels()

        # ── Quick View panel (Ctrl+Q) ──────────────────────────────────────
        self.quickview = QuickViewPanel(self.panes, self)
        if self.settings.get("quickview_open"):
            self.quickview.show()

        # ── Automatic refresh when folders change on disk ──────────────────
        self.folder_watcher = FolderWatcher(self)
        # Build watch — off the UI thread, and only ever a status line.
        try:
            if self.settings.get("watch_at_startup", True):
                self.after(4000, self._build_watch_startup)
        except Exception:
            pass

        # Cursor trace log — configure, prune the old lines, then keep
        # pruning every half hour so a long session cannot outgrow the window.
        try:
            _trace.configure(self.settings.get("trace_cursor", True),
                             self.settings.get("trace_hours", 48))
            _trace.prune()
            _trace.write("SESSION", note=f"File Manager started  "
                                         f"(build {_build_stamp()}, "
                                         f"keeping {_trace.hours}h)")
            self._schedule_trace_prune()
        except Exception as exc:
            _log(f"Cursor trace could not start: {exc}")

        if self.settings.get("auto_refresh", True):
            self.folder_watcher.start()

        # Give the left panel keyboard focus with a row selected from the start
        self.master.after(0, self._set_initial_focus)
        # Carry out any deletions that have been waiting longer than the limit
        self.master.after(400, self.auto_purge_pending)

    def capture_column_widths(self):
        """Remember the column widths as they are on screen.

        Dragging a column edge used to be forgotten at the next start — the
        widths were only ever read from settings, never written back. This
        stores what you actually set, so a wider Modified column stays wide.
        """
        panel = getattr(self, "left_panel", None)
        if panel is None or getattr(panel, "is_remote", False):
            panel = getattr(self, "right_panel", None)
        if panel is None or getattr(panel, "is_remote", False):
            return
        try:
            widths = dict(self.settings.get("column_widths", {}))
            for key, col in (("name", "#0"), ("type", "type"),
                             ("flag", "flag"), ("size", "size"),
                             ("modified", "modified"),
                             ("attributes", "attributes")):
                w = int(panel.tree.column(col, "width"))
                if w > 0:
                    widths[key] = w
            # The Tags column collapses to 0 when nothing is tagged, so take
            # the remembered width rather than whatever it happens to show.
            tags_now = int(panel.tree.column("tags", "width"))
            widths["tags"] = (tags_now if tags_now > 0
                              else getattr(panel, "_tags_col_width", 110))
            self.settings["column_widths"] = widths
        except Exception as exc:
            _log(f"Could not capture column widths: {exc}")

    def shutdown(self):
        """Stop background helpers cleanly before the window is destroyed."""
        self.capture_column_widths()
        # Last word on the queue.  _on_close already writes it before asking,
        # but this is the path every OTHER way out takes — and an unfinished
        # transfer must never be lost without a trace.
        mgr = getattr(self, "task_queue_mgr", None)
        if mgr is not None:
            try:
                mgr.save_state_now()
            except Exception as exc:
                _log(f"Could not save the task queue on shutdown: {exc}")
        # Flush any pending debounced Workspace tab-reorder save so a reorder
        # made in the last minute before closing is not lost.
        pending = getattr(self, "_ws_reorder_after", None)
        if pending:
            for side, aid in list(pending.items()):
                if aid is not None:
                    try:
                        self.after_cancel(aid)
                    except Exception:
                        pass
                    try:
                        self._ws_save_order(side)
                    except Exception:
                        pass
        try:
            _trace.write("SESSION", note="File Manager closing")
            _trace.close()
        except Exception:
            pass
        for attr in ("folder_watcher", "quickview"):
            obj = getattr(self, attr, None)
            if obj is not None:
                try:
                    obj.stop()
                except Exception:
                    pass

    # ── UI construction ──────────────────────────────────────────────────

    def _create_toolbar(self):
        self.toolbar = ttk.Frame(self)
        self.toolbar.pack(fill="x", pady=2)
        self.toolbar_layout = load_toolbar()
        self.build_toolbar()

    def build_toolbar(self):
        """(Re)build the button row from self.toolbar_layout.

        Called at startup and again whenever the user edits the toolbar, so
        changes appear immediately without a restart.
        """
        # Buttons that other code updates by reference — cleared on rebuild so
        # a removed button never leaves a stale widget behind.
        self._queue_btn = None
        self._trash_btn = None
        self._tools_menu = None

        # The right-hand group is rebuilt too, so carry its state across
        keep_filter = ""
        try:
            keep_filter = self._filter_var.get()
        except Exception:
            pass

        for child in self.toolbar.winfo_children():
            child.destroy()

        # The right-hand group is built FIRST so it always keeps its space:
        # with pack(), whatever is packed earlier wins when the toolbar runs
        # out of width, and the left button row is the part that may be
        # clipped on a narrow window — not the filter and checkboxes.
        self._create_toolbar_right()
        if keep_filter:
            self._filter_var.set(keep_filter)

        for item in self.toolbar_layout:
            try:
                self._add_toolbar_item(item)
            except Exception as exc:
                _log(f"Toolbar item {item!r} could not be created: {exc}")

        # Reflect current state on the freshly created buttons
        self._update_trash_btn()
        self._update_queue_btn()

    def _add_toolbar_item(self, item: dict):
        """Create one toolbar entry from its layout description."""
        kind = item.get("type", "action")

        if kind == "sep":
            ttk.Separator(self.toolbar, orient="vertical").pack(
                side="left", fill="y", padx=4, pady=2)
            return

        if kind == "menu":
            self._add_toolbar_menu(item.get("id", ""))
            return

        text = item.get("text", "")
        tip  = item.get("tip", "")

        if kind == "command":
            command = item.get("command", "")
            shell   = item.get("shell", "cmd")
            tip = tip or f"{SHELLS.get(shell, shell)}:  {command}"
            action = lambda c=command, s=shell: self._toolbar_run_command(c, s)

        elif kind == "folder":
            path = item.get("path", "")
            tip = tip or f"Go to  {path}"
            action = lambda p=path: self._toolbar_goto(p)

        else:   # "action"
            action_id = item.get("id", "")
            entry = TOOLBAR_ACTIONS.get(action_id)
            if not entry:
                _log(f"Toolbar refers to an unknown action: {action_id!r}")
                return
            label, method_name, default_text = entry
            method = getattr(self, method_name, None)
            if method is None:
                _log(f"Toolbar action {action_id!r}: no method {method_name!r}")
                return
            text = text or default_text
            key = self.keymap.get(action_id, "")
            tip = tip or (f"{label}   ({key_to_label(key)})" if key else label)
            # Make the Shift / Ctrl variants of the function keys discoverable
            # right from the button (e.g. Copy button also mentions Shift+F5).
            hint = TOOLBAR_SECONDARY_TIPS.get(action_id)
            if hint:
                tip = f"{tip}\n{hint}"
            action = method

        btn = ttk.Button(self.toolbar, text=text, command=action,
                         width=max(3, min(10, len(text) + 2)))
        btn.pack(side="left", padx=1)
        self._create_tooltip(btn, tip)

        # A few buttons do something else on a right-click (the Relocator runs
        # every rule at once).  Bound here so any button can gain the trick.
        if kind == "action":
            rc = TOOLBAR_RIGHTCLICK.get(item.get("id", ""))
            if rc:
                meth = getattr(self, rc, None)
                if meth is not None:
                    btn.bind("<Button-3>", lambda e, f=meth: (f(), "break")[1])

        # Keep references to the two buttons that display live state
        if kind == "action":
            if item.get("id") == "queue":
                self._queue_btn = btn
            elif item.get("id") == "trash":
                self._trash_btn = btn
            elif item.get("id") == "compare_sides":
                self._compare_btn = btn
                self._update_compare_btn()
            elif item.get("id") == "relocator":
                self._relocator_btn = btn

    def _add_toolbar_menu(self, menu_id: str):
        """The three drop-down menus that can sit in the toolbar."""
        if menu_id == "tools":
            self._create_tools_menu()
            return

        if menu_id == "net":
            mb = ttk.Menubutton(self.toolbar, text="NET ▾", width=5)
            menu = tk.Menu(mb, tearoff=0)
            mb["menu"] = menu
            menu.add_command(label="🔍  Find network locations …",
                             command=self.open_network_locations)
            menu.add_command(label="🔌  Connect to a PC (connection file) …",
                             command=self.open_connect_pc)
            menu.add_command(label="📤  Share this PC's drives …",
                             command=self.open_share_this_pc)
            menu.add_command(label="🌐  Server for connection files …",
                             command=self.open_pc_relay)
            menu.add_command(label="📱  Phones / portable devices …",
                             command=self.open_portable_devices)
            menu.add_separator()
            menu.add_command(label="Scan …", command=self.open_network_window)
            menu.add_command(label="🖧  Browse shares …", command=self.open_shares)
            menu.add_separator()
            menu.add_command(label="Favorites …",
                             command=lambda: NetworkWindow(self, tab="fav"))
            menu.add_command(label="Activate All Favorites",
                             command=self._net_activate_all_favorites)
            menu.add_separator()
            menu.add_command(label="ARP Quick-Scan …",
                             command=self._net_arp_quickscan)
            mb.pack(side="left", padx=1)
            self._create_tooltip(mb, "Network tools")
            return

        if menu_id == "sel":
            mb = ttk.Menubutton(self.toolbar, text="SEL ▾", width=5)
            menu = tk.Menu(mb, tearoff=0)
            mb["menu"] = menu
            menu.add_command(label="💾  Save selection to file…",
                             command=self.save_selection_to_file)
            menu.add_command(label="📋  Copy paths to clipboard",
                             command=self.copy_paths_to_clipboard)
            menu.add_command(label="📋  Copy names to clipboard",
                             command=self.copy_names_to_clipboard)
            mb.pack(side="left", padx=1)
            self._create_tooltip(mb, "Selection tools")
            return

        _log(f"Unknown toolbar menu id: {menu_id!r}")

    def _toolbar_run_command(self, command: str, shell: str):
        """Run a user-defined toolbar command in the active panel's folder."""
        cwd = self.get_active_panel().current_path
        if not os.path.isdir(cwd):
            cwd = str(APP_ROOT)
        expanded = expand_command(command, self)
        # Show it in the command bar so the output is visible, not swallowed
        self.cmdbar.show()
        self.cmdbar._show_output()
        self.cmdbar._append(f"\n{cwd}> {expanded}\n", "cmd")
        run_command_async(shell, expanded, cwd,
                          on_output=lambda line: _ui_call(
                              self, lambda l=line: self.cmdbar._append(l)),
                          on_done=lambda code: _ui_call(
                              self, lambda c=code: self.cmdbar._on_done(c)))

    def _toolbar_goto(self, path: str):
        """Jump the active panel to a folder pinned on the toolbar."""
        if not os.path.isdir(path):
            messagebox.showerror("Toolbar", f"This folder does not exist:\n{path}")
            return
        panel = self.get_active_panel()
        if getattr(panel, "is_remote", False):
            messagebox.showinfo("Toolbar",
                                "That panel is mounted on FTP — unmount it first.")
            return
        panel.change_directory(path)

    def open_toolbar_config(self):
        ToolbarConfigWindow(self)

    def _create_toolbar_right(self):
        """Filter field, Hidden / System toggles and About — right-aligned."""
        right_frame = ttk.Frame(self.toolbar)
        right_frame.pack(side="right", padx=5)

        # ── Filter field ──────────────────────────────────────────────────
        ttk.Label(right_frame, text="Filter:").pack(side="left", padx=(0, 2))
        self._filter_var      = tk.StringVar()
        self._filter_after_id = None   # debounce handle

        filter_entry = tk.Entry(
            right_frame, textvariable=self._filter_var,
            width=14,
            insertofftime=0, insertontime=9999999,
        )
        filter_entry.pack(side="left")
        self._create_tooltip(filter_entry,
            "Filter: show only matching names/extensions\n"
            "  .py   → only .py files\n"
            "  rep   → anything containing 'rep'\n"
            "  *      → only ★-flagged items\n"
            "  -*     → only items WITHOUT a ★\n"
            "  tag:Work → only that colour label\n"
            "(Folders are always shown — except for * / -* / tag:)")

        def _on_filter_change(*_):
            if self._filter_after_id:
                self.after_cancel(self._filter_after_id)
            self._filter_after_id = self.after(200, self._apply_filter)

        self._filter_var.trace_add("write", _on_filter_change)

        clr_btn = tk.Button(
            right_frame, text="×",
            command=self._clear_filter,
            relief="flat", padx=2, pady=0,
            font=("", 9, "bold"),
            cursor="hand2",
        )
        clr_btn.pack(side="left", padx=(1, 6))
        self._create_tooltip(clr_btn, "Clear filter")

        # ── Hidden / System ───────────────────────────────────────────────
        self._var_show_hidden = tk.BooleanVar(value=self.settings["show_hidden"])
        self._var_show_system = tk.BooleanVar(value=self.settings["show_system"])
        ttk.Checkbutton(
            right_frame, text="Hidden",
            command=self._toggle_hidden, variable=self._var_show_hidden
        ).pack(side="left")
        ttk.Checkbutton(
            right_frame, text="System",
            command=self._toggle_system, variable=self._var_show_system
        ).pack(side="left")

        # Total-Commander-style file-type icons
        self._var_show_icons = tk.BooleanVar(value=self.settings.get("show_icons", True))
        ttk.Checkbutton(
            right_frame, text="Icons",
            command=self._toggle_icons, variable=self._var_show_icons
        ).pack(side="left")

        # About button
        ab = ttk.Button(right_frame, text="ℹ", command=self._show_about, width=3)
        ab.pack(side="left", padx=(6, 0))
        self._create_tooltip(ab, "About")

    def _create_tools_menu(self):
        """The TOOLS ▾ drop-down. Labels show the current shortcut."""
        # width was 9 for a 7-character label — the slack is given to the ★
        # button that now sits further along the row.
        tools_mb = ttk.Menubutton(self.toolbar, text="TOOLS ▾", width=7)
        menu = tk.Menu(tools_mb, tearoff=0)
        tools_mb["menu"] = menu
        self._tools_menu = menu
        tools_mb.pack(side="left", padx=(4, 1))
        self._create_tooltip(tools_mb,
                             "Multi-rename, compare, sync, duplicates,\n"
                             "checksums, split, listings and more")
        self._rebuild_tools_menu()

    def _rebuild_tools_menu(self):
        """Rebuild the Tools menu so the labels match the current shortcuts."""
        menu = getattr(self, "_tools_menu", None)
        if menu is None:
            return
        menu.delete(0, "end")

        def acc(action_id: str) -> str:
            return key_to_label(self.keymap.get(action_id, ""))

        entries = [
            ("✎  Multi-Rename tool…",        "multi_rename",   self.open_multi_rename),
            ("⇄  Compare files…",            "compare_files",  self.open_compare),
            ("⇆  Synchronize directories…",  "sync_dirs",      self.open_sync),
            ("⧉  Find duplicate files…",     "duplicates",     self.open_duplicates),
            (None, None, None),
            ("👁  Quick View panel",          "quick_view",     self.toggle_quick_view),
            ("🌿  Branch view (files)",       "branch_view",    self.toggle_branch_view),
            ("🌳  Branch view (with folders)", "branch_view_dirs", self.toggle_branch_view_dirs),
            (None, None, None),
            ("📦  Browse archive…",           "browse_archive", self.open_archive_browser),
            ("📦  Pack…",                     "pack",           self.pack_files_as),
            ("📂  Unpack",                    "unpack",         self.unpack_any),
            ("💿  Create ISO / IMG image…",   "make_image",     self.make_image),
            (None, None, None),
            ("🔐  Checksums…",                "checksums",      self.open_checksums),
            ("✂  Split file…",               "split_file",     self.open_split),
            ("🔗  Combine split parts",       "combine_files",  self.open_combine),
            (None, None, None),
            ("⭐  Directory hotlist…",        "hotlist",        self.open_hotlist),
            ("⭐  Add current folder to hotlist", None,         self.add_current_to_hotlist),
            (None, None, None),
            ("⇪  Transfer presets (1-click copy/move jobs)…", "transfer_presets",
                                              self.open_transfer_presets),
            ("⚖  Smart-queue conflict rules…", "conflict_rules",
                                              self.open_conflict_rules),
            ("⤴  Relocator rules…", "relocator",  self.open_relocator_rules),
            ("⤴  Relocator — run a rule now…", None, self.open_relocator),
            ("(2)  “(2)-suffix” answers…",     None, self.open_twin_rules),
            (None, None, None),
            (">_  Command bar",              "command_bar",    self.toggle_command_bar),
            ("📚  Command library…",          "command_library", self.open_command_library),
            (None, None, None),
            ("🖨  Print / export listing…",   "print_listing",  self.open_print_listing),
            (None, None, None),
            ("▦  Disk usage (treemap)…",     "treemap",        self.open_treemap),
            ("🏷  File tags…",                "tags",           self.open_tags),
            ("⌘  Command palette…",          "palette",        self.open_palette),
            ("↶  Undo history…",             "undo_history",   self.open_undo),
            ("🔒  Locked files waiting to be removed…", None,
                                              self.show_unlock_pending),
            (None, None, None),
            ("🖧  Browse network shares…",    None,             self.open_shares),
            ("🔍  Find network locations…",   None,             self.open_network_locations),
            ("🔌  Connect to a PC (connection file)…", None,    self.open_connect_pc),
            ("📤  Share this PC's drives…",    None,             self.open_share_this_pc),
            ("🌐  Server for connection files…", None,          self.open_pc_relay),
            ("📱  Phones / portable devices…", None,            self.open_portable_devices),
            (None, None, None),
            ("📁  Folders first when sorting", None,            self.toggle_folders_first),
            ("🔄  Toggle auto-refresh",       "auto_refresh",   self.toggle_auto_refresh),
            ("⌨  Configure shortcuts…",      "shortcuts",      self.open_shortcut_config),
            ("🔧  Configure toolbar…",        "toolbar_config", self.open_toolbar_config),
            ("🔌  Configure my tools (Send to)…", "tools_config", self.open_tools_config),
            ("🕒  Dates & deletion…",          "dates_delete",   self.open_dates_delete),
            (None, None, None),
            ("📋  Cursor trace log…",          None,             self.open_trace_log),
        ]
        for label, action_id, command in entries:
            if label is None:
                menu.add_separator()
            else:
                menu.add_command(label=label, command=command,
                                 accelerator=acc(action_id) if action_id else "")

    def _create_tooltip(self, widget, text):
        widget.bind("<Enter>", lambda e, t=text: self._show_tooltip(e, t))
        widget.bind("<Leave>", lambda e: self._hide_tooltip())

    def _show_tooltip(self, event, text):
        try:
            x = event.widget.winfo_rootx() + 25
            y = event.widget.winfo_rooty() + 25
            self._tooltip = tk.Toplevel(event.widget)
            self._tooltip.wm_overrideredirect(True)
            self._tooltip.wm_geometry(f"+{x}+{y}")
            ttk.Label(
                self._tooltip, text=text,
                background="#ffffe0", relief="solid", borderwidth=1, padding=4
            ).pack()
        except Exception:
            pass

    def _hide_tooltip(self):
        if hasattr(self, "_tooltip"):
            try:
                self._tooltip.destroy()
            except Exception:
                pass

    # ══ Inline conflict bar ═════════════════════════════════════════════
    # "The queue button goes ⚠ but nothing pops up, and when the queue DOES
    # open it takes my arrow keys."  This is the third way: the question is
    # answered in the MAIN window, on a strip above the status bar.  It is
    # part of the file manager, so it can never cover the panels and can never
    # be buried behind another program.  Ctrl+Alt+1…5 answer it from anywhere;
    # the buttons say which number is which.
    #
    # revAO — it now ARMS its first answer when it appears: the keyboard cursor
    # lands on "1  Overwrite old", so a plain Enter answers, ←/→ walk to
    # another choice, and Esc (or ↑/↓) hands the keys straight back to the file
    # list.  It never does this while you are typing in a rename box or a
    # dialog field.  Settings ▸ General ▸ "The bar arms its first answer" turns
    # it off again, restoring the original hands-off-the-keyboard behaviour.
    #
    # Which of the three ways is used is Settings ▸ General ▸ "When a copy
    # hits a name clash":  bar (this) | dialog (stop and ask at once) |
    # queue (the old ⚠ button and nothing else).

    # ONE NAME PER MODE, part two (revK1G).  The 2026-09-12 rename fixed the
    # combobox (_CONFLICT_CHOICES) and forgot this bar, so the two names that
    # entry names as the CAUSE of the misreading — "Overwrite old" and
    # "Overwrite newer" — were still on screen here.  Nothing is stored by
    # label, so these are free to say the truth, and the fifth one now says it
    # from BOTH sides: the incoming file's, and the one already on disk.
    _CBAR_ACTIONS = [
        ("1  Overwrite always",  "overwrite_all",
         "Replace the file that is already there, old or new"),
        ("2  Backup-rename old", "backup_old",
         "Keep the old one under a Backup<code>- name; the new one takes the name"),
        ("3  Rename new",        "auto_rename",
         "Keep both — the incoming file gets a (2) suffix"),
        ("4  Skip",              "skip_all",
         "Leave what is there; do not copy these"),
        ("5  Overwrite if newer", "overwrite_older",
         "Replace only where the incoming file is the newer one — "
         "i.e. overwrite the older copy, keep the newer or same-age one"),
    ]

    def _create_conflict_bar(self):
        self._cbar = tk.Frame(self, bg="#5a1020", padx=8, pady=5)
        self._cbar_shown = False
        self._cbar_sig   = None          # what is on screen, to avoid redraws

        top = tk.Frame(self._cbar, bg="#5a1020")
        top.pack(fill="x")
        self._cbar_head = tk.Label(
            top, text="", bg="#5a1020", fg="#ffd0dd", anchor="w",
            font=("Segoe UI", 10, "bold"))
        self._cbar_head.pack(side="left")
        tk.Button(top, text="✖", bg="#5a1020", fg="#ffd0dd", bd=0,
                  activebackground="#7a2038", activeforeground="white",
                  font=("Segoe UI", 9, "bold"),
                  command=self._cbar_cancel_job).pack(side="right")
        tk.Button(top, text="Details…", bg="#5a1020", fg="#ffd0dd", bd=0,
                  activebackground="#7a2038", activeforeground="white",
                  font=("Segoe UI", 8),
                  command=self._cbar_details).pack(side="right", padx=(0, 10))

        self._cbar_detail = tk.Label(
            self._cbar, text="", bg="#5a1020", fg="#e8aabc", anchor="w",
            justify="left", font=("Segoe UI", 8))
        self._cbar_detail.pack(fill="x", pady=(2, 4))

        row = tk.Frame(self._cbar, bg="#5a1020")
        row.pack(fill="x")
        # revAO — the bar now ARMS its first choice.  When it appears the
        # keyboard cursor sits on "1  Overwrite old", so plain Enter answers
        # straight away and ←/→ walk to another choice first; Esc hands the
        # keys back to the file list.  (It used to refuse the keyboard on
        # purpose so the arrows stayed in the panels — that is still available
        # as Settings ▸ General ▸ "the clash bar takes the keyboard".)
        self._cbar_buttons = []
        for label, mode, tip in self._CBAR_ACTIONS:
            b = tk.Button(row, text=label, bg="#f0e0e6", fg="black",
                          activebackground="#ffffff", font=("Segoe UI", 8),
                          takefocus=1, highlightthickness=2,
                          highlightbackground="#5a1020",
                          highlightcolor="#ffe680",
                          command=lambda m=mode: self._cbar_resolve(m))
            b.pack(side="left", padx=3)
            self._create_tooltip(b, tip)
            self._cbar_buttons.append(b)
        self._cbar_hint = tk.Label(
            row, text="   (←/→ pick · Enter = do it · Esc = Skip"
                      " · ↑/↓ back to the list · Ctrl+Alt+1…5)",
            bg="#5a1020", fg="#c08095", font=("Segoe UI", 8))
        self._cbar_hint.pack(side="left", padx=(6, 0))
        b_always = tk.Button(row, text="⚖  Always do this here…",
                             bg="#f0e0e6", fg="black",
                             activebackground="#ffffff", font=("Segoe UI", 8),
                             takefocus=1, highlightthickness=2,
                             highlightbackground="#5a1020",
                             highlightcolor="#ffe680",
                             command=self._cbar_always)
        b_always.pack(side="right", padx=3)
        # "Always do this here…" is a legitimate answer too, so it is the last
        # stop on the ←/→ ring.  ✖ Cancel-the-job deliberately is NOT: it
        # throws the copy away and must stay a deliberate mouse click.
        self._cbar_buttons.append(b_always)

        for i, b in enumerate(self._cbar_buttons):
            b.bind("<FocusIn>",  lambda e, w=b: self._cbar_paint(w, True))
            b.bind("<FocusOut>", lambda e, w=b: self._cbar_paint(w, False))
            b.bind("<Left>",     lambda e, i=i: self._cbar_step(i, -1))
            b.bind("<Right>",    lambda e, i=i: self._cbar_step(i, +1))
            b.bind("<Home>",     lambda e: self._cbar_goto(0))
            b.bind("<End>",      lambda e: self._cbar_goto(-1))
            b.bind("<Return>",   lambda e, w=b: (w.invoke(), "break")[1])
            b.bind("<KP_Enter>", lambda e, w=b: (w.invoke(), "break")[1])
            # Esc = SKIP.  It used to hand the keyboard back to the file
            # list, which left the question sitting there unanswered — and Esc
            # is the key you reach for to wave one file away.  Up/Down are the
            # way out now, and they were already doing that job.
            b.bind("<Escape>",   lambda e: (self._cbar_resolve("skip_all"), "break")[1])
            # Up/Down belong to the file list even while the bar has the keys —
            # one press and the cursor is back where the files are.
            b.bind("<Up>",       lambda e: self._cbar_release_keys())
            b.bind("<Down>",     lambda e: self._cbar_release_keys())

        # The shortcuts live on the toplevel, not on the bar, so they answer
        # wherever the keyboard happens to be — but ONLY while the bar is up
        # (they are unbound again when it goes away).
        self._cbar_keys_bound = False

    # ── The ⚡ button's four states (revBS) ────────────────────────────────

    def _queue_top_mode(self) -> int:
        """The SAVED state: 0 closed · 1 open/free · 2 above the file manager ·
        3 above everything.  It is what a window opened automatically comes up
        in; what is actually on screen is _queue_top_mode_effective()."""
        try:
            m = int(self.settings.get("queue_top_mode", QUEUE_MODE_OVER_FM))
        except Exception:
            m = QUEUE_MODE_OVER_FM
        return m if m in (0, 1, 2, 3) else QUEUE_MODE_OVER_FM

    def _queue_top_mode_effective(self) -> int:
        """What is ON SCREEN right now.  The button is coloured from this, so a
        remembered "red" can never paint the bolt red while nothing is open —
        and the first click after a start therefore always gives state 1."""
        try:
            win = getattr(self.task_queue_mgr, "_window", None)
            if win is None or not win.winfo_exists():
                return QUEUE_MODE_CLOSED
            return int(getattr(win, "_mode_now", QUEUE_MODE_CLOSED) or 0)
        except Exception:
            return QUEUE_MODE_CLOSED

    def _set_queue_top_mode(self, mode: int, save: bool = True,
                            from_window: bool = False):
        """Put the Task Queue into one of the four states and repaint ⚡.

        from_window=True comes from the queue's own ✖ / Escape: that window has
        already hidden itself, so only the setting and the button colour have
        to catch up — calling _hide() again from here would be a loop."""
        try:
            mode = int(mode)
        except Exception:
            mode = QUEUE_MODE_FREE
        mode = max(QUEUE_MODE_CLOSED, min(QUEUE_MODE_OVER_ALL, mode))
        self.settings["queue_top_mode"] = mode
        if save:
            try:
                self.save_settings()
            except Exception:
                pass
        try:
            if mode == QUEUE_MODE_CLOSED:
                if not from_window:
                    win = getattr(self.task_queue_mgr, "_window", None)
                    if win is not None and win.winfo_exists():
                        win._hide()
            else:
                self.task_queue_mgr.ensure_window().apply_top_mode(mode)
        except Exception as exc:
            _log(f"Task Queue: state {mode} could not be applied: {exc}")
        self._update_queue_btn()

    def _cycle_queue_top_mode(self):
        """⚡ LEFT-click — closed → open → above the file manager → above
        everything → closed again.  One button for the whole question.

        It steps on from what is ON SCREEN, not from the saved value, so the
        first click after a start opens the queue instead of "closing" a window
        that was never showing."""
        nxt = (self._queue_top_mode_effective() + 1) % 4
        self._set_queue_top_mode(nxt)
        try:
            self._flash_status(_QUEUE_MODE_FLASH.get(nxt, ""))
        except Exception:
            pass

    def _close_queue_window(self):
        """⚡ RIGHT-click — shut the Task Queue window from any state."""
        self._set_queue_top_mode(QUEUE_MODE_CLOSED)
        try:
            self._flash_status(_QUEUE_MODE_FLASH[QUEUE_MODE_CLOSED])
        except Exception:
            pass

    def _paint_queue_btn(self, mode: int):
        """Colour the ⚡ button by the state the queue is in.

        ttk ignores bg= on the Windows themes, so the state is carried by the
        BOLT itself: green open, orange above the file manager, red above
        everything — and the plain theme colour back again when it is closed.
        Static; nothing here blinks."""
        try:
            if not getattr(self, "_queue_mode_styles_made", False):
                st = ttk.Style()
                for m, col in _QUEUE_MODE_COLOUR.items():
                    st.configure(f"QueueMode{m}.TButton", foreground=col,
                                 font=("Segoe UI", 9, "bold"))
                self._queue_mode_styles_made = True
            name = (f"QueueMode{mode}.TButton"
                    if mode in _QUEUE_MODE_COLOUR else "TButton")
            self._queue_btn.configure(style=name, width=4)
        except Exception:
            pass

    def _set_queue_btn_alert(self, on: bool):
        """Red bold face on the ⚡/⚠ toolbar button while a job is waiting.

        A ttk.Button ignores bg= on the Windows themes, so this goes through a
        style; the button is also made wider so "⚠1 ANSWER" is not clipped
        down to "⚠1…".  Static — nothing here blinks."""
        try:
            if not getattr(self, "_queue_alert_style_made", False):
                st = ttk.Style()
                st.configure("QueueAlert.TButton",
                             foreground="#c00028",
                             font=("Segoe UI", 9, "bold"))
                self._queue_alert_style_made = True
            if on:
                self._queue_btn.configure(style="QueueAlert.TButton", width=11)
            else:
                self._queue_btn.configure(style="TButton", width=4)
        except Exception:
            pass

    def _conflict_alert_mode(self) -> str:
        """bar | dialog | queue — Settings ▸ General."""
        m = str(self.settings.get("conflict_alert_mode", "bar")).lower()
        return m if m in ("bar", "dialog", "queue") else "bar"

    # ── The bar's own keyboard (revAO) ────────────────────────────────────

    def _cbar_wants_keys(self) -> bool:
        """Should the bar arm its first choice when it appears?

        Settings ▸ General.  Off restores the old behaviour exactly: the bar
        never touches the keyboard and only Ctrl+Alt+1…5 (or the mouse) answer
        it, so the arrow keys never leave the file list."""
        return bool(self.settings.get("conflict_bar_keys", True))

    @staticmethod
    def _cbar_paint(btn, focused: bool):
        """Static look for the armed choice — a white face inside a yellow
        ring.  Nothing here blinks or animates; it is one redraw per move."""
        try:
            if focused:
                btn.configure(bg="#ffffff", relief="solid", bd=2,
                              font=("Segoe UI", 8, "bold"))
            else:
                btn.configure(bg="#f0e0e6", relief="raised", bd=1,
                              font=("Segoe UI", 8))
        except Exception:
            pass

    def _cbar_step(self, index: int, delta: int):
        """←/→ — move to the next choice, wrapping round the ends."""
        n = len(self._cbar_buttons)
        if n:
            self._cbar_goto((index + delta) % n)
        return "break"

    def _cbar_goto(self, index: int):
        try:
            self._cbar_buttons[index].focus_set()
        except Exception:
            pass
        return "break"

    def _cbar_arm(self):
        """Put the keyboard cursor on the FIRST choice, so plain Enter answers.

        Never grabs the keyboard out of a text box (an inline rename, the
        command bar, a dialog field) — that would type the answer into the
        wrong place."""
        if not self._cbar_wants_keys():
            return
        try:
            if self._focus_in_text_widget():
                return
            if self._cbar_buttons:
                self._cbar_buttons[0].focus_set()
        except Exception:
            pass

    def _cbar_release_keys(self):
        """Esc / ↑ / ↓ — give the keyboard back to the active file list."""
        try:
            panel = self.get_active_panel()
            if panel is not None and hasattr(panel, "tree"):
                panel.tree.focus_set()
        except Exception:
            pass
        return "break"

    def _cbar_has_keys(self) -> bool:
        """True while the keyboard cursor is on one of the bar's buttons."""
        try:
            return self.focus_get() in self._cbar_buttons
        except Exception:
            return False

    def _cbar_escape_skip(self, _e=None):
        """Esc anywhere in the main window, while a clash is waiting = Skip.

        Bound on the TOPLEVEL, so it answers wherever the keyboard happens to
        be — the file list, the bar, a tab strip.  It stands back for a text
        box (an inline rename, the command bar): there Escape has to keep
        meaning "cancel what I am typing", and returning None instead of
        "break" leaves that binding to do its job."""
        if not getattr(self, "_cbar_shown", False):
            return None
        try:
            if self._focus_in_text_widget():
                return None
        except Exception:
            return None
        self._cbar_resolve("skip_all")
        return "break"

    def _cbar_bind_keys(self, on: bool):
        try:
            top = self.winfo_toplevel()
            if on and not self._cbar_keys_bound:
                for i, (_lbl, mode, _t) in enumerate(self._CBAR_ACTIONS, start=1):
                    top.bind(f"<Control-Alt-Key-{i}>",
                             lambda e, m=mode: (self._cbar_resolve(m), "break")[1])
                top.bind("<Escape>", self._cbar_escape_skip, add="+")
                self._cbar_keys_bound = True
            elif not on and self._cbar_keys_bound:
                for i in range(1, len(self._CBAR_ACTIONS) + 1):
                    top.unbind(f"<Control-Alt-Key-{i}>")
                top.unbind("<Escape>")
                self._cbar_keys_bound = False
        except Exception:
            pass

    def _conflict_bar_sync(self):
        """Show / hide / redraw the bar from the queue's own state.

        Driven by _update_queue_btn, which the queue already calls on every
        change — so the bar cannot get out of step with the ⚠ counter."""
        try:
            if self._conflict_alert_mode() != "bar":
                self._conflict_bar_hide()
                return
            task = self.task_queue_mgr.first_conflict_task()
            if task is None:
                self._conflict_bar_hide()
                return
            clashes = list(task.pending_conflicts or [])
            sig = (task.task_id, len(clashes))
            if not self._cbar_shown:
                self._cbar.pack(fill="x", before=self.statusbar)
                self._cbar_shown = True
                self._cbar_bind_keys(True)
                # Arm the first choice on the next idle cycle — the bar has to
                # be mapped before focus_set() will stick.
                self.after_idle(self._cbar_arm)
            if sig == self._cbar_sig:
                return                     # nothing changed — leave it alone
            self._cbar_sig = sig
            self._cbar_head.configure(
                text=f"⚠  {len(clashes)} file(s) already exist at the destination"
                     f"  —  {task.description}")
            self._cbar_detail.configure(text=self._cbar_detail_text(clashes))
        except Exception as exc:
            _log(f"Conflict bar refresh failed: {exc}")

    def _cbar_detail_text(self, clashes: list) -> str:
        """First clash spelled out (both sizes and dates), then the rest by
        name — enough to answer without opening anything."""
        if not clashes:
            return ""
        first = clashes[0]
        src, dst = first.get("src", ""), first.get("dst", "")

        def _info(p):
            try:
                st = os.stat(p)
                return (_fmt_size(st.st_size),
                        datetime.fromtimestamp(st.st_mtime).strftime("%Y-%m-%d %H:%M"),
                        st.st_size, st.st_mtime)
            except Exception:
                return ("?", "?", -1, -1.0)

        s_sz, s_dt, s_b, s_m = _info(src)
        d_sz, d_dt, d_b, d_m = _info(dst)
        if s_b >= 0 and s_b == d_b and abs(s_m - d_m) <= 2:
            verdict = "✓ identical (same size, same date)"
        elif s_m > d_m:
            verdict = "the incoming file is NEWER"
        elif s_m < d_m:
            verdict = "the file already there is newer"
        else:
            verdict = "same date, different size"
        line = (f"{os.path.basename(src)}      "
                f"incoming  {s_sz}  {s_dt}      ·      "
                f"already there  {d_sz}  {d_dt}      ·      {verdict}")
        if len(clashes) > 1:
            rest = ",  ".join(os.path.basename(c.get("src", ""))
                              for c in clashes[1:4])
            more = f"  … +{len(clashes) - 4} more" if len(clashes) > 4 else ""
            line += f"\nalso:  {rest}{more}"
        return line

    def _conflict_bar_hide(self):
        if getattr(self, "_cbar_shown", False):
            # Hand the keyboard back BEFORE unpacking: a widget that loses its
            # place in the layout while it holds the focus leaves the whole
            # window keyboard-less, and the arrow keys look dead until you
            # click a panel.
            had_keys = self._cbar_has_keys()
            try:
                self._cbar.pack_forget()
            except Exception:
                pass
            self._cbar_shown = False
            self._cbar_sig   = None
            self._cbar_bind_keys(False)
            if had_keys:
                self._cbar_release_keys()

    def _cbar_resolve(self, mode: str):
        """Answer for every job that is parked on a clash, then get out of
        the way.  _conflict_bar_hide() hands the keyboard back to the file
        list; if ANOTHER job is waiting the bar stays up and re-arms its first
        choice, so a run of clashes is answered with a run of Enters."""
        if not getattr(self, "_cbar_shown", False):
            return
        had_keys = self._cbar_has_keys()
        if self.task_queue_mgr.resolve_pending_conflicts(mode):
            self._flash_status(
                f"Name clashes: {_CONFLICT_LABEL.get(mode, mode)}  —  job released")
        self._conflict_bar_sync()
        if had_keys and getattr(self, "_cbar_shown", False):
            self.after_idle(self._cbar_arm)

    def _cbar_details(self):
        """Open the Task Queue for the full list (it still never takes keys)."""
        try:
            self.task_queue_mgr.alert_window()
        except Exception as exc:
            _log(f"Could not open the Task Queue from the conflict bar: {exc}")

    def _cbar_always(self):
        """Straight to the auto-rule tick, with the 'covers' pickers, so this
        route can stop asking altogether."""
        self._cbar_details()

    def _cbar_cancel_job(self):
        """Drop the parked job entirely — nothing is copied."""
        task = self.task_queue_mgr.first_conflict_task()
        if task is None:
            self._conflict_bar_hide()
            return
        if not messagebox.askyesno(
                "Cancel job",
                f"Cancel this job and copy nothing?\n\n{task.description}",
                parent=self):
            return
        try:
            self.task_queue_mgr.cancel_task(task.task_id)
        except Exception as exc:
            _log(f"Could not cancel the parked job: {exc}")
        self._update_queue_btn()
        self._conflict_bar_sync()

    def _create_statusbar(self):
        self.statusbar = ttk.Frame(self)
        self.statusbar.pack(fill="x")
        # Three clearly-labelled sections, each self-contained, so there is
        # never any doubt about "which path?":
        #   LEFT  section = the LEFT  panel  (path | file/folder counts | free)
        #   middle        = which panel is active + how many items are marked
        #   RIGHT section = the RIGHT panel  (path | file/folder counts | free)
        # The active side's section is tinted (accent) — the other is dimmed.
        self._left_disk  = ttk.Label(self.statusbar, text="", relief="sunken",
                                     anchor="w")
        self._counts_lbl = ttk.Label(self.statusbar, text="", relief="sunken",
                                     anchor="center")
        self._right_disk = ttk.Label(self.statusbar, text="", relief="sunken",
                                     anchor="w")
        # A fourth section that only exists while the Task Queue is working.
        # "It ends up in the Task queue, but I do not see the task queue" — the
        # ⚡ button only ever said how MANY jobs were pending, so a copy could
        # run for ten minutes with nothing in the main window to show for it.
        # This says what is moving, how far it has got, how fast, and how long
        # is left — and takes itself away the moment the queue is quiet, so an
        # idle program still has no moving parts anywhere.
        self._queue_lbl = ttk.Label(self.statusbar, text="", relief="sunken",
                                    anchor="w", foreground=C_ACCENT)
        self._queue_lbl_shown = False
        self._queue_lbl_text  = None
        self._left_disk.grid( row=0, column=0, sticky="we", padx=1, pady=1)
        self._counts_lbl.grid(row=0, column=1, sticky="we", padx=6, pady=1)
        self._right_disk.grid(row=0, column=2, sticky="we", padx=1, pady=1)
        # Left and right sections share the width equally; the middle sits
        # centred between them and takes only what it needs.
        self.statusbar.columnconfigure(0, weight=1, uniform="sb")
        self.statusbar.columnconfigure(2, weight=1, uniform="sb")
        self._update_disk_info()
        self._update_counts()
        self._tick_queue_status()

    # ── The queue, seen from the main window ──────────────────────────────

    def _queue_status_text(self, mgr) -> str:
        """One line about whatever the queue is doing right now, or ""."""
        cur = (getattr(mgr, "_current_task", None)
               or getattr(mgr, "_current_fast", None)
               or getattr(mgr, "_current_bus", None)
               or getattr(mgr, "_current_reloc", None))
        if cur is None:
            return ""
        icon = {TaskType.COPY: "📋", TaskType.MOVE: "🚚",
                TaskType.PACK: "📦", TaskType.UNPACK: "📂"}.get(
                    cur.task_type, "⚡")
        name = os.path.basename(mgr._prog_file or "") or cur.description
        if len(name) > 42:
            name = name[:39] + "…"
        parts = [f"{icon}  {name}"]
        cur_n, total_n = mgr._prog_cur, mgr._prog_total
        if total_n > 0 and cur_n > 0:
            parts.append(f"{min(100, cur_n * 100 // total_n)}%")
            if (getattr(mgr, "_prog_unit", "files") == "bytes"
                    and mgr._prog_start):
                el = _time.monotonic() - mgr._prog_start
                if el > 0.5:
                    rate = cur_n / el
                    parts.append(f"{_fmt_size(int(rate))}/s")
                    left = (total_n - cur_n) / rate if rate > 0 else 0
                    if left >= 4:
                        parts.append(f"~{left / 60:.0f} min left" if left >= 90
                                     else f"~{left:.0f} s left")
        try:
            pending = mgr.pending_count()
        except Exception:
            pending = 0
        if pending > 1:
            parts.append(f"+{pending - 1} waiting")
        return "   ·   ".join(parts)

    def _tick_queue_status(self):
        """Twice a second, but ONLY while something is actually running: the
        label is removed when the queue falls quiet, and an unchanged line is
        never rewritten (a status bar that repaints itself on a timer is a
        status bar that flickers).

        revCI: the line is now OPT-IN (Settings > General > Display,
        "queue_in_statusbar", default OFF).  The Task Queue window already
        shows the same facts in far more detail, and a bar that changes all
        the time while files move was a distraction.  When off, the label stays
        hidden and the timer only wakes every 3 s to notice a settings change."""
        delay = 500
        try:
            mgr = getattr(self, "task_queue_mgr", None)
            lbl = getattr(self, "_queue_lbl", None)
            if not self.settings.get("queue_in_statusbar", False):
                delay = 3000
                if lbl is not None and self._queue_lbl_shown:
                    lbl.grid_remove()
                    self._queue_lbl_shown = False
                    self._queue_lbl_text  = None
                mgr = None
            if mgr is not None and lbl is not None:
                txt = self._queue_status_text(mgr)
                if txt:
                    if not self._queue_lbl_shown:
                        lbl.grid(row=0, column=3, sticky="we", padx=1, pady=1)
                        self._queue_lbl_shown = True
                    if txt != self._queue_lbl_text:
                        self._queue_lbl_text = txt
                        lbl.configure(text=txt)
                elif self._queue_lbl_shown:
                    lbl.grid_remove()
                    self._queue_lbl_shown = False
                    self._queue_lbl_text  = None
        except Exception:
            pass
        finally:
            try:
                self.after(delay, self._tick_queue_status)
            except Exception:
                pass

    def _refresh_side_highlight(self):
        """Tint the ACTIVE panel's status section (accent) and dim the other,
        so which side — and which path — is the 'current window' is obvious.
        Cheap: only changes label colours, no disk access."""
        active = getattr(self, "active_panel", "left")
        for lbl, side in ((getattr(self, "_left_disk", None),  "left"),
                          (getattr(self, "_right_disk", None), "right")):
            if lbl is None:
                continue
            try:
                lbl.config(foreground=(C_ACCENT if side == active else C_FG_DIM))
            except Exception:
                pass

    # ── Paths handed in from the command line ───────────────────────────

    def show_cli_path(self, path: str):
        """Show *path* in the active panel: a folder is entered, a file is
        shown in its own folder with the cursor on it."""
        try:
            path = os.path.abspath((path or "").strip().strip('"'))
            if not os.path.exists(path):
                return
            panel = self.get_active_panel()
            folder = path if os.path.isdir(path) else os.path.dirname(path)
            panel.change_directory(folder)
            if not os.path.isdir(path):
                want = os.path.basename(path)
                for iid in panel.tree.get_children():
                    if panel._fullname(iid).lower() == want.lower():
                        panel.tree.selection_set(iid)
                        panel.tree.focus(iid)
                        panel.tree.see(iid)
                        break
            # Someone asked for this window; put it where they can see it.
            top = self.winfo_toplevel()
            top.deiconify()
            top.lift()
            top.focus_force()
        except Exception as exc:
            # NOT log.error(): this program has no logging module logger,
            # only _log() — so the old call raised NameError from INSIDE the
            # error handler and turned a handled failure into a crash.
            _log(f"could not show {path}: {exc}")

    def _drain_cli_paths(self):
        """MAIN thread: take whatever the listener thread has queued.

        Polled from here rather than pushed with after() from the socket
        thread — see _fm_serve()."""
        q = getattr(self, "_cli_queue", None)
        if q is None:
            self._cli_queue = q = []
        while q:
            self.show_cli_path(q.pop(0))
        try:
            self.after(400, self._drain_cli_paths)
        except Exception:
            pass

    def calc_folder_sizes(self):
        """Alt+Shift+Enter — measure the folders in the ACTIVE panel.

        Without it the Size column is empty for folders, so sorting folders by
        size (the hollow ▵ arrow) has nothing to sort on.  Press again while
        it runs to stop it."""
        try:
            panel = self.get_active_panel()
            if hasattr(panel, "calc_folder_sizes"):
                panel.calc_folder_sizes()
        except Exception as exc:
            _log(f"folder sizes failed: {exc}")

    def toggle_auto_folder_sizes(self):
        """Turn the "folders show a SIZE too" MODE on or off (revBD).

        Alt+Shift+Enter measures once, on demand; this is the standing setting
        — every folder listing measures itself from now on.  Same switch as the
        checkbox in Settings → Display, put on a key so it can be flipped in
        the folder you are standing in."""
        on = not self.settings.get("auto_folder_sizes", False)
        self.settings["auto_folder_sizes"] = on
        try:
            self.save_settings()
        except Exception:
            pass
        if on:
            for p in (self.get_active_panel(), self.get_inactive_panel()):
                try:
                    p.calc_folder_sizes(only_missing=True)
                except Exception:
                    pass
        try:
            self._counts_lbl.config(
                text=("📁 Folder sizes: ON — every listing measures itself"
                      if on else "📁 Folder sizes: off"))
            self.after(2500, self._update_counts)
        except Exception:
            pass

    def _update_counts(self):
        """Middle status section: which panel is active, and how many items are
        marked there ("X of N selected")."""
        lbl = getattr(self, "_counts_lbl", None)
        if lbl is None:
            return
        try:
            side      = self.active_panel
            side_name = "Left" if side == "left" else "Right"
            panel     = self.get_active_panel()
            if getattr(panel, "is_remote", False):
                lbl.config(text=f"▸ {side_name} active  (FTP)")
            else:
                n_files = getattr(panel, "_n_files", 0)
                n_dirs  = getattr(panel, "_n_dirs", 0)
                total   = n_files + n_dirs
                marked  = sum(1 for iid in getattr(panel, "_marked", ())
                              if panel._fullname(iid) != "..")
                if marked:
                    lbl.config(text=f"✔ {marked} of {total} selected  ({side_name})")
                else:
                    lbl.config(text=f"▸ {side_name} active")
        except Exception:
            lbl.config(text="")
        self._refresh_side_highlight()

    def _create_context_menu(self):
        self.context_menu = tk.Menu(self, tearoff=0)
        self.context_menu.add_command(label="View / Edit  (F3)",   command=self.view_file)
        # Running a program and editing it are two different things, and for a
        # .py both are reasonable — so both are on the menu instead of one
        # being guessed at (revBH).
        self.context_menu.add_command(label="▶  Run",
                                      command=self.run_selected)
        self.context_menu.add_command(label="▶  Run in a console  (see output)",
                                      command=self.run_selected_console)
        self.context_menu.add_separator()
        self.context_menu.add_command(label="Open in my program  (F4)",
                                      command=self.edit_file)
        self.context_menu.add_command(label="Open in 2nd program  (Shift+F4)",
                                      command=self.edit_file_secondary)
        self.context_menu.add_command(label="Open with Windows default",
                                      command=self.edit_file_default)
        self.context_menu.add_command(label="Open with…  (Ctrl+F4)",
                                      command=self.open_with_dialog)
        self.context_menu.add_command(label="Copy  (F5)",         command=self.copy_files)
        self.context_menu.add_command(label="Move  (F6)",         command=self.move_files)
        self.context_menu.add_command(label="Rename  (F2)",       command=self._rename_selected)
        self.context_menu.add_command(label="Rename extension  (Shift+F2)",
                                      command=self._rename_ext_selected)
        self.context_menu.add_command(label="Delete",             command=self.delete_files)
        self.context_menu.add_separator()
        # Clipboard (revBK).  "Copy the file name" and "copy the whole path"
        # are two different jobs and guessing which one was meant is a coin
        # toss, so both are here — with the marked files one per line.
        self._clip_menu = tk.Menu(self.context_menu, tearoff=0)
        self._clip_menu.add_command(
            label="Name only            Faktura.rtf",
            command=lambda: self.copy_selection_to_clipboard("name"))
        self._clip_menu.add_command(
            label="Name, no extension   Faktura",
            command=lambda: self.copy_selection_to_clipboard("stem"))
        self._clip_menu.add_command(
            label="Full path            C:\\Papper\\Faktura.rtf",
            command=lambda: self.copy_selection_to_clipboard("full"))
        self._clip_menu.add_command(
            label='Full path, quoted    "C:\\Papper\\Faktura.rtf"',
            command=lambda: self.copy_selection_to_clipboard("quoted"))
        self._clip_menu.add_command(
            label="Folder only          C:\\Papper",
            command=lambda: self.copy_selection_to_clipboard("folder"))
        self.context_menu.add_cascade(label="📋  Copy to clipboard",
                                      menu=self._clip_menu)
        self.context_menu.add_separator()
        # Per-folder sort override (DEL 45) — rebuilt on every right-click so it
        # names the folder you clicked and shows what is set for it.
        self._foldersort_menu = tk.Menu(self.context_menu, tearoff=0)
        self.context_menu.add_cascade(label="🔀  Sort override for this folder",
                                      menu=self._foldersort_menu)
        self.context_menu.add_separator()
        self.context_menu.add_command(label="New folder",         command=self.new_folder)
        self.context_menu.add_command(label="Properties",         command=self.show_properties)
        self.context_menu.add_command(label="Change attributes…", command=self.change_attributes)
        self.context_menu.add_command(label="🕒  Set date and time to NOW",
                                      command=self.set_dates_now)
        self.context_menu.add_separator()
        self.context_menu.add_command(label="Multi-Rename…",      command=self.open_multi_rename)
        self.context_menu.add_command(label="Backup rename…",     command=self.backup_rename_selected)
        self.context_menu.add_command(label="Compare files…",     command=self.open_compare)
        self.context_menu.add_command(label="Checksums…",         command=self.open_checksums)
        self.context_menu.add_command(label="Browse archive…",    command=self.open_archive_browser)
        self.context_menu.add_command(label="Pack…",              command=self.pack_files_as)
        self.context_menu.add_command(label="Unpack",             command=self.unpack_any)
        self.context_menu.add_command(label="Split file…",        command=self.open_split)
        self.context_menu.add_separator()
        # "Send to" is rebuilt every time the menu opens, so it can show only
        # the tools that apply to whatever is selected right now.
        self._sendto_menu = tk.Menu(self.context_menu, tearoff=0)
        self.context_menu.add_cascade(label="Send to", menu=self._sendto_menu)
        # Tags submenu — also rebuilt each time, to show what is already set
        self._tags_menu = tk.Menu(self.context_menu, tearoff=0)
        self.context_menu.add_cascade(label="Tags", menu=self._tags_menu)
        self.context_menu.add_separator()
        self.context_menu.add_command(label="Open Command Prompt (Admin)", command=self.open_cmd)
        self.context_menu.add_command(label="Open PowerShell (Admin)",    command=self.open_powershell)
        self.context_menu.add_command(label="Export path",                command=self.export_path)

    def _bind_keys(self):
        # Tab is bound on the root window so it fires before tkinter's own
        # focus-traversal class binding, which would otherwise steal focus.
        self.master.bind("<Tab>", self._on_tab_key, add=False)
        self.bind_all("<Return>", lambda e: self.on_enter_key(e))
        self.bind_all("<Delete>", lambda e: self.delete_files())
        # Alt+Up — the Explorer key for the parent folder, alongside the
        # rebindable Backspace in KEY_ACTIONS.  Both exist because Enter on
        # ".." used to be the ONLY key that went up, which meant hitting one
        # exact row and running a program on every miss.
        self.bind_all("<Alt-Up>", self._parent_key)
        self._bound_sequences: list = []
        self.rebind_keys()

    def rebind_keys(self):
        """(Re-)apply every shortcut from self.keymap.

        Called at startup and again whenever the user edits the shortcuts,
        so a rebind takes effect immediately without a restart.
        """
        for seq in getattr(self, "_bound_sequences", []):
            try:
                self.unbind_all(seq)
            except Exception:
                pass
        self._bound_sequences = []

        for action_id, method_name in KEY_METHODS.items():
            seq = self.keymap.get(action_id, "")
            if not seq:
                continue
            method = getattr(self, method_name, None)
            if method is None:
                _log(f"Shortcut {action_id}: no method named {method_name!r}")
                continue

            def handler(event, m=method, aid=action_id):
                # Never fire a shortcut while the user is typing in a field
                focused = event.widget
                if isinstance(focused, (tk.Entry, ttk.Entry, tk.Text, ttk.Combobox)):
                    return
                try:
                    m()
                except Exception as exc:
                    _log(f"Shortcut {aid} failed: {exc}")
                    _crash_report(type(exc), exc, exc.__traceback__,
                                  f"shortcut:{aid}")
                return "break"

            try:
                self.bind_all(seq, handler)
                self._bound_sequences.append(seq)
            except Exception as exc:
                _log(f"Could not bind {seq} for {action_id}: {exc}")

        # The two cursor jumps also need a WIDGET-level binding on each panel's
        # tree — see bind_panel_jumps() for why bind_all alone is not enough.
        for _side in ("left_panel", "right_panel"):
            self.bind_panel_jumps(getattr(self, _side, None))

        # Keep the menu accelerators in step with the bindings
        self._rebuild_tools_menu()

    # Actions that move the cursor inside the file list itself.
    _PANEL_JUMP_ACTIONS = ("goto_first_file", "goto_first_folder")

    def bind_panel_jumps(self, panel):
        """Bind the cursor-jump keys straight on a panel's tree.

        Tk matches a binding whose modifiers are a SUBSET of the event's, so
        the Treeview's own <Key-Down> class binding ALSO fires on Ctrl+Down.
        Without a widget-level binding that returns "break", the cursor would
        first step one row and only then jump — a visible double move.  These
        stay rebindable: rebind_keys() re-applies them from the keymap."""
        tree = getattr(panel, "tree", None)
        if tree is None:
            return
        for seq in getattr(panel, "_jump_seqs", []):
            try:
                tree.unbind(seq)
            except Exception:
                pass
        panel._jump_seqs = []
        for aid in self._PANEL_JUMP_ACTIONS:
            seq = self.keymap.get(aid, "")
            method = getattr(self, KEY_METHODS.get(aid, ""), None)
            if not seq or method is None:
                continue

            def handler(_event, m=method):
                m()
                return "break"

            try:
                tree.bind(seq, handler)
                panel._jump_seqs.append(seq)
            except Exception as exc:
                _log(f"Could not bind {seq} on the {panel.side} panel: {exc}")

    # ── Small wrappers so every action has a no-argument method ──────────

    def _disk_menu_left(self):
        self.show_disk_menu("left")

    def _disk_menu_right(self):
        self.show_disk_menu("right")

    # ── Workspace cycling (Shift+Left / Shift+Right) ─────────────────────
    def _ws_cycle_prev(self):
        """Shift+Left — switch to the previous saved Workspace (whole profile)."""
        self._ws_cycle(-1)

    def _ws_cycle_next(self):
        """Shift+Right — switch to the next saved Workspace (whole profile)."""
        self._ws_cycle(+1)

    def _ws_cycle(self, direction: int):
        """Step through the saved Workspaces (the bar under the toolbar).

        This is a WHOLE-profile switch: the target loads onto both panels, so
        exactly ONE workspace stays highlighted.  (Loading just one side left the
        previous profile still lit on the other side — two buttons highlighted at
        once.)  Wraps around at the ends."""
        names = list(self.workspaces)
        if not names:
            self._flash_status("No Workspaces saved yet — use ＋ Save on the "
                               "Workspace bar first.")
            return
        # The "current" profile is whatever is loaded on the active side, or the
        # other side if the active one isn't in a workspace.
        side  = self.active_panel
        other = "right" if side == "left" else "left"
        cur   = self._ws_name.get(side) or self._ws_name.get(other)
        if cur in names:
            i = (names.index(cur) + direction) % len(names)
        else:
            i = 0 if direction > 0 else len(names) - 1
        target = names[i]

        # Load onto BOTH panels (temporarily forcing both check-boxes on).
        old_l, old_r = self._ws_apply_left.get(), self._ws_apply_right.get()
        try:
            self._ws_apply_left.set(True)
            self._ws_apply_right.set(True)
            self._ws_load(target)
        finally:
            self._ws_apply_left.set(old_l)
            self._ws_apply_right.set(old_r)

        # Guarantee a single highlight: if a panel ended up on a DIFFERENT
        # workspace (e.g. the target doesn't define that side), drop its active
        # marker so two profiles are never lit at the same time.
        changed = False
        for s in ("left", "right"):
            if self._ws_name.get(s) not in (target, None):
                self._ws_name[s]   = None
                self._ws_active[s] = False
                changed = True
        if changed:
            self._render_workspace_bar()
        self._flash_status(f"Workspace: {target}")

    # ── Tab switching / moving on the active panel ───────────────────────
    def _tab_prev(self):
        """Ctrl+Left — switch to the previous tab on the active panel (wraps)."""
        self._cycle_tab(-1)

    def _tab_next(self):
        """Ctrl+Right — switch to the next tab on the active panel (wraps)."""
        self._cycle_tab(+1)

    def _cycle_tab(self, direction: int):
        side = self.active_panel
        tabs = self.left_tabs if side == "left" else self.right_tabs
        if len(tabs) <= 1:
            return
        idx = self.left_tab_idx if side == "left" else self.right_tab_idx
        self._switch_to_tab(side, (idx + direction) % len(tabs))

    def _tab_move_leftmost(self):
        """Alt+Left — move the active tab all the way to the left ('Most')."""
        side = self.active_panel
        idx  = self.left_tab_idx if side == "left" else self.right_tab_idx
        self._move_tab_to_end(side, idx, "start")

    def _tab_move_rightmost(self):
        """Alt+Right — move the active tab all the way to the right ('Most')."""
        side = self.active_panel
        idx  = self.left_tab_idx if side == "left" else self.right_tab_idx
        self._move_tab_to_end(side, idx, "end")

    # ══ Tab pairs (F8 cycle) ══════════════════════════════════════════════
    #  A pair links a LEFT tab with a RIGHT tab.  F8 steps through the pairs,
    #  jumping BOTH panels at once.  Pair 1 is implicit = the leftmost tab on
    #  each side; user pairs (2,3,…) are made by right-clicking a tab.

    def _same_addr(self, a: str, b: str) -> bool:
        """True when two paths point at the SAME folder (case + separators
        normalised), so a pair follows its folder to whatever tab shows it."""
        try:
            return (os.path.normcase(os.path.normpath(a))
                    == os.path.normcase(os.path.normpath(b)))
        except Exception:
            return a == b

    def _tab_index_for_path(self, side: str, path: str) -> int:
        """First tab index on *side* whose folder == *path*, or -1 if none."""
        if not path:
            return -1
        tabs = self.left_tabs if side == "left" else self.right_tabs
        for i, p in enumerate(tabs):
            if self._same_addr(p, path):
                return i
        return -1

    def _pair_cycle_list(self) -> list:
        """The ordered list F8 steps through: [(left_idx, right_idx, label), …].
        Pair 1 (leftmost tabs) is included unless it is switched off.  USER
        pairs are linked by folder ADDRESS, so the tab index is looked up live —
        the pair follows its folder to whatever tab (and position) now shows it.
        A side with no open tab for its folder is -1 (left where it is); a pair
        with NEITHER side open is skipped."""
        out = []
        if self._pair1_in_cycle:
            out.append((0, 0, "1"))
        for i, p in enumerate(self._tab_pairs, start=2):
            l = self._tab_index_for_path("left",  p.get("left", ""))
            r = self._tab_index_for_path("right", p.get("right", ""))
            if l == -1 and r == -1:
                continue                      # both folders closed → dead pair
            out.append((l, r, str(i)))
        return out

    def _cycle_tab_pairs(self):
        """F8 — jump to the NEXT tab pair (wrapping): switch the left panel to
        the pair's left folder and the right panel to its right folder."""
        cyc = self._pair_cycle_list()
        if not cyc:
            self._flash_status(
                "No tab pairs to cycle — right-click a tab ▸ “Tab pairs” to make "
                "one (the start pair is currently off).")
            return
        self._pair_pos = (self._pair_pos + 1) % len(cyc)
        l_idx, r_idx, label = cyc[self._pair_pos]
        # Move both panels (a -1 side has no open tab → leave it), THEN flash the
        # pair message last so it wins over the per-tab path flash.
        if 0 <= l_idx < len(self.left_tabs):
            self._switch_to_tab("left", l_idx)
        if 0 <= r_idx < len(self.right_tabs):
            self._switch_to_tab("right", r_idx)
        lname = (os.path.basename(self.left_tabs[l_idx])
                 if 0 <= l_idx < len(self.left_tabs) else "—")
        rname = (os.path.basename(self.right_tabs[r_idx])
                 if 0 <= r_idx < len(self.right_tabs) else "—")
        self._flash_status(
            f"Pair {label}  ({self._pair_pos + 1}/{len(cyc)})   "
            f"◧ {lname}   ◨ {rname}")

    def _pair_add_this_tab(self, side: str, idx: int, pair_no):
        """Link the FOLDER of the tab at (side, idx) as the *side* member of a
        pair.  pair_no None → make a NEW pair, taking the current active tab's
        folder on the OTHER side as its member.  pair_no ≥ 2 → edit that pair."""
        tabs = self.left_tabs if side == "left" else self.right_tabs
        if not (0 <= idx < len(tabs)):
            return
        this_path  = tabs[idx]
        other      = "right" if side == "left" else "left"
        other_tabs = self.right_tabs if other == "right" else self.left_tabs
        other_idx  = self.right_tab_idx if other == "right" else self.left_tab_idx
        other_path = (other_tabs[other_idx]
                      if 0 <= other_idx < len(other_tabs) else "")
        if pair_no is None:
            pair = {"left": "", "right": ""}
            pair[side]  = this_path
            pair[other] = other_path
            self._tab_pairs.append(pair)
            self._flash_status(
                f"Made pair {len(self._tab_pairs) + 1}: {side} = "
                f"{os.path.basename(this_path) or this_path}.")
        else:
            i = pair_no - 2
            if 0 <= i < len(self._tab_pairs):
                self._tab_pairs[i][side] = this_path
                self._flash_status(
                    f"Pair {pair_no}: {side} linked to "
                    f"{os.path.basename(this_path) or this_path}.")
        self._pairs_changed()

    def _pair_new_from_current(self):
        """Save the CURRENT active left + right folders together as a new pair."""
        li, ri = self.left_tab_idx, self.right_tab_idx
        lp = self.left_tabs[li]  if 0 <= li < len(self.left_tabs)  else ""
        rp = self.right_tabs[ri] if 0 <= ri < len(self.right_tabs) else ""
        self._tab_pairs.append({"left": lp, "right": rp})
        self._flash_status(
            f"Saved current Left+Right folders as pair {len(self._tab_pairs) + 1}.")
        self._pairs_changed()

    def _pair_clear(self, pair_no: int):
        """Remove a user pair (2,3,…); later pairs shift down to fill the gap."""
        i = pair_no - 2
        if 0 <= i < len(self._tab_pairs):
            self._tab_pairs.pop(i)
            self._flash_status(f"Cleared pair {pair_no}.")
            self._pairs_changed()

    def _pair_toggle_start(self):
        """Include / exclude the implicit start pair (Pair 1) from the F8 cycle."""
        self._pair1_in_cycle = not self._pair1_in_cycle
        self._flash_status(
            f"Start pair (1) is now "
            f"{'IN' if self._pair1_in_cycle else 'OUT of'} the F8 cycle.")
        self._pairs_changed()

    def _pairs_linking(self, side: str, path: str) -> list:
        """Pair numbers (2,3,…) whose *side* folder == *path*."""
        return [i + 2 for i, p in enumerate(self._tab_pairs)
                if self._same_addr(p.get(side, ""), path)]

    def _break_pairs(self, side: str, path: str):
        """Drop every pair whose *side* folder == *path* (its link is gone)."""
        self._tab_pairs = [p for p in self._tab_pairs
                           if not self._same_addr(p.get(side, ""), path)]
        self._pairs_changed()

    def _confirm_close_linked_tab(self, side: str, idx: int) -> bool:
        """Guard for closing a tab that a pair links.  Returns True when the
        close may proceed.  If ANOTHER tab on the SAME side shows the SAME
        folder, the link simply rides along on that one and we close silently;
        otherwise this is the last tab for that folder, so we warn and — on
        Yes — break the pair(s).  Returns False only when the user cancels."""
        tabs = self.left_tabs if side == "left" else self.right_tabs
        if not (0 <= idx < len(tabs)):
            return True
        path   = tabs[idx]
        linked = self._pairs_linking(side, path)
        if not linked:
            return True
        # Another tab on this side with the same folder keeps the link alive →
        # no warning, the pair just moves to that tab.
        if any(j != idx and self._same_addr(p, path)
               for j, p in enumerate(tabs)):
            return True
        many = len(linked) > 1
        if not _ask_yes_no(
                "Linked tab",
                f"This tab is linked in tab pair{'s' if many else ''} "
                f"{', '.join(str(n) for n in linked)} (F8 cycle).\n"
                f"It is the only open tab for this folder, so closing it will "
                f"BREAK {'those pairs' if many else 'that pair'}.\n\nClose anyway?",
                parent=self):
            return False
        self._break_pairs(side, path)
        return True

    def _store_pairs_into(self, ws: dict):
        """Write the tab pairs (folder addresses) into a workspace dict."""
        ws["pairs"] = [[str(p.get("left", "")), str(p.get("right", ""))]
                       for p in self._tab_pairs]
        ws["pair1_in_cycle"] = bool(self._pair1_in_cycle)

    def _load_pairs_from(self, ws: dict):
        """Restore tab pairs (folder addresses) from a workspace dict.  Legacy
        index-based pairs (ints, from an earlier build) are dropped."""
        raw = ws.get("pairs", [])
        self._tab_pairs = []
        if isinstance(raw, list):
            for item in raw:
                try:
                    l, r = item[0], item[1]
                    if isinstance(l, str) and isinstance(r, str):
                        self._tab_pairs.append({"left": l, "right": r})
                except Exception:
                    pass
        self._pair1_in_cycle = bool(ws.get("pair1_in_cycle", True))
        self._pair_pos = 0

    def _pairs_changed(self):
        """After any pair edit: clamp the cycle position and persist the pairs
        into whatever Workspace is loaded (pairs are a whole-profile property)."""
        cyc = self._pair_cycle_list()
        self._pair_pos = (self._pair_pos % len(cyc)) if cyc else 0
        saved = set()
        for side in ("left", "right"):
            name = self._ws_name.get(side)
            if name and name in self.workspaces and name not in saved:
                self._store_pairs_into(self.workspaces[name])
                saved.add(name)
        if saved:
            self._save_workspaces()

    def _manage_tab_pairs(self):
        """List / clear the tab pairs and toggle whether the start pair cycles."""
        dlg = tk.Toplevel(self)
        _setup_toplevel(dlg, "Tab pairs (F8 cycle)", self)
        dlg.resizable(False, False)
        body = ttk.Frame(dlg, padding=12)
        body.pack(fill="both", expand=True)

        ttk.Label(
            body,
            text="F8 cycles these Left + Right tab pairs, jumping BOTH panels at\n"
                 "once.  A pair is linked by FOLDER, so it follows its folder to\n"
                 "whatever tab shows it.  Pair 1 is the leftmost tab on each side.",
            justify="left").pack(anchor="w", pady=(0, 8))

        inc_var = tk.BooleanVar(value=self._pair1_in_cycle)

        list_frame = ttk.Frame(body)

        def _name_for(side, path):
            base = os.path.basename(path) or path or "—"
            if path and self._tab_index_for_path(side, path) == -1:
                base += "  (no open tab)"
            return base

        def _rebuild():
            for w in list_frame.winfo_children():
                w.destroy()
            l1 = os.path.basename(self.left_tabs[0])  if self.left_tabs  else "?"
            r1 = os.path.basename(self.right_tabs[0]) if self.right_tabs else "?"
            in1 = "✓" if self._pair1_in_cycle else "—"
            ttk.Label(list_frame,
                      text=f"[{in1}] Pair 1 (start)    ◧ {l1}    ◨ {r1}"
                      ).grid(row=0, column=0, sticky="w", pady=2)
            for i, p in enumerate(self._tab_pairs):
                no = i + 2
                ln = _name_for("left",  p.get("left", ""))
                rn = _name_for("right", p.get("right", ""))
                ttk.Label(list_frame,
                          text=f"[✓] Pair {no}    ◧ {ln}    ◨ {rn}"
                          ).grid(row=no, column=0, sticky="w", pady=2)
                ttk.Button(list_frame, text="Clear", width=7,
                           command=lambda n=no: (self._pair_clear(n), _rebuild())
                           ).grid(row=no, column=1, padx=(12, 0))
            if not self._tab_pairs:
                ttk.Label(list_frame,
                          text="(No extra pairs yet — right-click a tab ▸ "
                               "“Tab pairs” to add one.)",
                          foreground="#888888"
                          ).grid(row=99, column=0, sticky="w", pady=(6, 0))

        def _toggle_inc():
            self._pair1_in_cycle = bool(inc_var.get())
            self._pairs_changed()
            _rebuild()

        ttk.Checkbutton(body,
                        text="Include the start pair (Pair 1) in the cycle",
                        variable=inc_var, command=_toggle_inc).pack(anchor="w")
        list_frame.pack(fill="both", expand=True, pady=(8, 0))
        _rebuild()

        ttk.Button(body, text="Close", width=10,
                   command=dlg.destroy).pack(anchor="e", pady=(10, 0))

    def _on_tab_key(self, event):
        """Always switch panel on Tab; allow normal Tab in Entry/Combobox."""
        focused = self.focus_get()
        if isinstance(focused, (ttk.Entry, tk.Entry, ttk.Combobox)):
            # Let Tab work normally in text-input widgets
            return
        self.switch_panel()
        return "break"

    # ── Panel / navigation ────────────────────────────────────────────────

    def _focus_in_text_widget(self) -> bool:
        """True when the keyboard focus is inside a text-entry widget — an inline
        rename box, a dialog field, the command bar, etc.  GLOBAL shortcuts that
        act on files (Delete → trash, Enter → open) MUST bail out in that case,
        or typing in the box would fire them.  This is what stopped a Delete
        keypress while renaming from trashing the selected file."""
        # An inline rename entry is tracked directly and is the common case.
        if getattr(self, "rename_item", None) is not None:
            return True
        try:
            w = self.focus_get()
        except Exception:
            w = None
        if w is None:
            return False
        try:
            cls = w.winfo_class()
        except Exception:
            return False
        return cls in ("Entry", "TEntry", "Text", "TCombobox",
                       "Spinbox", "TSpinbox", "Listbox")

    def on_enter_key(self, event=None):
        # Never open/navigate while typing in a text field (e.g. inline rename).
        if self._focus_in_text_widget():
            return
        shift_held = event is not None and bool(event.state & 0x1)
        ctrl_held  = event is not None and bool(event.state & 0x4)
        panel = self.get_active_panel()
        # Act on the CURSOR row, not on the blue selection.
        #
        # Marking rows TC-style leaves the cursor where it is but empties
        # tree.selection(), so this used to fall straight into "nothing
        # selected" and Enter did nothing at all.  Measured in
        # File_manager_cursor.log, five times over:
        #     *R Helpfiles s=- f=Database g=- m31  | nothing selected
        #     *R Helpfiles s=- f=ziprar   g=- m117 | nothing selected
        # - 31 and 117 rows marked, no selection, and the cursor sitting on a
        # perfectly good folder.  Walking to an UNmarked row re-created the
        # selection, which is why it worked there and only there.
        row = panel.tree.focus()
        if not (row and panel.tree.exists(row)):
            sel = panel.tree.selection()
            row = sel[0] if sel else ""
        if not row:
            self._ct("ENTER-KEY", "no cursor row — Enter did nothing")
            return
        sel   = (row,)
        text  = panel.tree.item(row, "text")
        fname = panel._fullname(row)
        # THE line to look for.  "acts-on" is what Enter is about to do; if it
        # is not the row you were looking at, the lines just above say who
        # moved it and when.
        _bsel = panel.tree.selection()
        _bnm = (panel._fullname(_bsel[0])
                if _bsel and panel.tree.exists(_bsel[0]) else "-")
        self._ct("ENTER-KEY",
                 f"acts-on={fname!r} (cursor); blue-selection={_bnm!r}"
                 + ("" if _bnm in (fname, "-") else
                    "   <<< CURSOR AND SELECTION DISAGREE — cursor wins")
                 + (f"; marked={len(getattr(panel, '_marked', ()) or ())}"
                    if getattr(panel, "_marked", None) else "")
                 + (f"; shift={shift_held} ctrl={ctrl_held}"
                    if (shift_held or ctrl_held) else ""))
        if getattr(panel, "archive_ctx", None):
            panel.archive_activate(fname, shift_held, ctrl_held)
        elif text == "..":
            panel.go_up()
        elif getattr(panel, "is_remote", False):
            vals = panel.tree.item(sel[0], "values")
            if vals and vals[0] == "Folder":
                panel.change_directory(fname)
            else:
                local = self._download_to_help(panel, panel.get_selected()[0])
                self._open_file_activated(local, shift_held, ctrl_held)
        else:
            full = os.path.join(panel.current_path, fname)
            if os.path.isdir(full):
                if ctrl_held:
                    # Ctrl+Enter — pop up the whole sub-folder tree to jump into
                    DirTreePopup(self, panel, full)
                elif shift_held:
                    # Shift+Enter — dive to the deepest first sub-folder
                    panel.dive_to_deepest(full)
                else:
                    panel.change_directory(full)
            elif not shift_held and not ctrl_held and is_archive(full):
                # Plain Enter on an archive: browse INTO it like a folder,
                # instead of popping up the read-only Archive viewer.
                panel.enter_archive(full)
            else:
                # A file: plain = Windows default, Shift = built-in viewer,
                # Ctrl = per-type opener (else built-in).  See _open_file_activated.
                self._open_file_activated(full, shift_held, ctrl_held)

    # ══ Cursor trace (revAP) ═══════════════════════════════════════════
    #
    # _ct() writes ONE line holding the complete cursor state of BOTH panels,
    # so a log line is a full picture and not a fragment you have to piece
    # together from neighbours.  Every call that can move a cursor calls it.
    # Reading a line:
    #
    #   ENTER-KEY  [on_enter_key:10467]  *L A=..  s=.. f=.. g=- m0 |R B=x.txt …
    #    ^event     ^which code            ^ ^   ^    ^    ^   ^
    #    |          |                      | |   |    |    |   `- marked count
    #    |          |                      | |   |    |    `- grey (inactive) row
    #    |          |                      | |   |    `- tree.focus() row
    #    |          |                      | |   `- the blue selection
    #    |          |                      | `- folder the panel stands in
    #    |          |                      `- "*" = this is the ACTIVE panel
    #    |          `- method:line that is doing it
    #    `- what happened
    #
    # If the blue row (s=) and the row Enter acts on ever differ, or s= is not
    # the same as g= was one line earlier, the log says so in black and white.

    @staticmethod
    def _ct_panel(panel, active: bool) -> str:
        """One panel's cursor state, compact."""
        try:
            tree = panel.tree
            def nm(iid):
                if not iid:
                    return "-"
                try:
                    if not tree.exists(iid):
                        return "<gone>"
                    return panel._fullname(iid) or "-"
                except Exception:
                    return "<err>"
            sel  = [nm(i) for i in tree.selection()]
            grey = [nm(i) for i in tree.get_children()
                    if "inactive_sel" in tree.item(i, "tags")]
            pin  = getattr(panel, "_cursor_pin", ("", 0.0))
            age  = _time.time() - (pin[1] or 0)
            return (f"{'*' if active else ' '}{panel.side[0].upper()} "
                    f"{os.path.basename(panel.current_path.rstrip(chr(92))) or panel.current_path}"
                    f" s={','.join(sel) if sel else '-'}"
                    f" f={nm(tree.focus())}"
                    f" g={','.join(grey) if grey else '-'}"
                    f" m{len(getattr(panel, '_marked', ()))}"
                    f" pin={pin[0] or '-'}"
                    f"{'' if not pin[0] else f'({age:.1f}s)'}"
                    f" n={len(tree.get_children())}")
        except Exception as exc:
            return f"<panel state unreadable: {exc}>"

    def _ct(self, event: str, note: str = "", depth: int = 1):
        """Write one trace line with BOTH panels' state."""
        if not _trace.enabled:
            return
        try:
            caller = ""
            try:
                fr = sys._getframe(depth)
                caller = f"{fr.f_code.co_name}:{fr.f_lineno}"
            except Exception:
                pass
            parts = []
            for side in ("left", "right"):
                pan = getattr(self, f"{side}_panel", None)
                if pan is None:
                    continue
                parts.append(self._ct_panel(pan, self.active_panel == side))
            _trace.write(event, " |".join(parts), note, caller)
        except Exception:
            pass

    def _sync_inactive_cursor(self, panel):
        self._ct("SYNC-INACTIVE-in", f"panel={panel.side}", depth=2)
        try:
            self.__sync_inactive_cursor(panel)
        finally:
            self._ct("SYNC-INACTIVE-out", f"panel={panel.side}", depth=2)

    def __sync_inactive_cursor(self, panel):
        """Guarantee the invariant the whole cursor story rests on:

            an INACTIVE panel shows EXACTLY ONE weakly-marked (grey) row,
            tree.focus() points at that same row, and there is no real
            selection left over — so Tab has one unambiguous row to turn
            blue, and that is the row Enter then acts on.

        Everything else about the inactive panel's cursor is derived from
        here.  Before this existed the grey row and the keyboard cursor were
        maintained in three separate places (demote, refresh, and the
        post-copy clean-up) which could disagree — and when they disagreed,
        the row that lit up on Tab was not the row you had been looking at.

        Which row: the one already grey, else the keyboard cursor, else what
        is selected, else the panel's default.  A MARKED (red) row keeps its
        own colour and is never greyed — the red already says where it is.
        """
        try:
            tree = panel.tree
            kids = tree.get_children()
            if not kids:
                return
            grey = [i for i in kids if "inactive_sel" in tree.item(i, "tags")]
            target = None
            for cand in (grey[0] if grey else None,
                         tree.focus(),
                         (tree.selection() or (None,))[0]):
                if cand and tree.exists(cand):
                    target = cand
                    break
            if target is None:
                target = self._panel_default_cursor(panel)
            if target is None:
                return
            for i in kids:                      # exactly one grey row
                tags = list(tree.item(i, "tags"))
                if "inactive_sel" in tags and i != target:
                    tags.remove("inactive_sel")
                    tree.item(i, tags=tags)
            if target not in getattr(panel, "_marked", ()):
                tags = list(tree.item(target, "tags"))
                if "inactive_sel" not in tags:
                    tags.append("inactive_sel")
                    tree.item(target, tags=tags)
            sel = tree.selection()
            if sel:
                tree.selection_remove(*sel)     # no real selection while inactive
            tree.focus(target)
        except Exception:
            pass

    def _demote_panel(self, panel):
        self._ct("DEMOTE-in", f"panel={panel.side}", depth=2)
        try:
            self.__demote_panel(panel)
        finally:
            self._ct("DEMOTE-out", f"panel={panel.side}", depth=2)

    def __demote_panel(self, panel):
        """Turn a panel's real (dark-blue) selection + marks into the muted
        'inactive' look, so the active cursor colour leaves this panel.

        revAO — demoting a panel TWICE used to erase its grey cursor entirely.
        The second pass stripped every 'inactive_sel' tag and then had no
        selection left to put one back from, because the first pass had already
        cleared it.  That happens routinely: change_directory() calls
        focus_set(), whose <FocusIn> demotes the other side, and the next Tab
        or click demotes it again.  The panel was then left with no visible
        cursor at all, and Tab had to guess where to put it back.

        A panel with no selection still has a keyboard cursor — tree.focus() —
        so that row is what gets greyed.  Demote is now idempotent: the
        inactive panel always shows where its cursor stands, and Tab brings
        exactly that row back as the blue one."""
        try:
            for item in getattr(panel, "_marked", ()):
                panel._set_mark_tag(item, active=False)
            for item in panel.tree.get_children():
                tags = list(panel.tree.item(item, "tags"))
                if "inactive_sel" in tags:
                    tags.remove("inactive_sel")
                    panel.tree.item(item, tags=tags)
            # The selection is the best hint about where the cursor was, so
            # hand it to the helper as the focus row before it is cleared.
            sel = list(panel.tree.selection())
            if sel and not panel.tree.focus():
                panel.tree.focus(sel[0])
            self._sync_inactive_cursor(panel)
        except Exception:
            pass

    def _promote_panel(self, panel):
        self._ct("PROMOTE-in", f"panel={panel.side}", depth=2)
        try:
            self.__promote_panel(panel)
        finally:
            self._ct("PROMOTE-out", f"panel={panel.side}", depth=2)

    def __promote_panel(self, panel):
        """Restore a panel's real selection (dark blue) + active marks.

        The fallback used to be "select row 0", which is the ".." row — so
        coming back from another program and clicking a file could leave the
        cursor on the parent dots, and the next Enter went UP a level instead
        of opening the file.  Now the panel's remembered row wins, and ".." is
        only ever the cursor when the folder holds nothing else.

        revAO — the row that ends up BLUE and the row Enter acts on are now
        guaranteed to be the same one, and it is scrolled into view:

          * every stray grey 'inactive_sel' tag is stripped, not only the ones
            that are being restored, so a ghost grey row can never sit next to
            the real blue one;
          * the keyboard cursor (tree.focus) is pulled onto the same row as the
            selection — they could drift apart, and Enter reads the SELECTION
            while the arrow keys move from FOCUS;
          * tree.see() makes sure the row is actually on screen, so "the blue
            one" is never something scrolled out of sight;
          * the row is pinned by name for a moment (see _cursor_pin), so an
            auto-refresh landing just after a Tab cannot slide the cursor onto
            the file below.
        """
        try:
            tree = panel.tree
            for item in getattr(panel, "_marked", ()):
                panel._set_mark_tag(item, active=True)
            restore = []
            for i in tree.get_children():
                tags = list(tree.item(i, "tags"))
                if "inactive_sel" in tags:
                    restore.append(i)
                    tags.remove("inactive_sel")
                    tree.item(i, tags=tags)
            target = None
            # revCD — a plain mouse click on this panel a moment ago: the row
            # under the mouse wins over the remembered grey keyboard row.
            clicked = None
            try:
                c_iid, c_name, c_when = getattr(panel, "_click_target",
                                                ("", "", 0.0))
                if (c_iid and (_time.time() - c_when) <= 0.8
                        and tree.exists(c_iid)
                        and panel._fullname(c_iid) == c_name):
                    clicked = c_iid
            except Exception:
                clicked = None
            if clicked:
                tree.selection_set(clicked)
                target = clicked
            elif restore:
                tree.selection_set(*restore)
                target = restore[0]
            else:
                sel = tree.selection()
                foc = tree.focus()
                if sel:
                    # Keep whatever is already highlighted, but make the
                    # keyboard cursor agree with it.
                    target = foc if (foc and foc in sel) else sel[0]
                else:
                    target = self._panel_default_cursor(panel)
                    if target:
                        tree.selection_set(target)
            if target and tree.exists(target):
                tree.focus(target)
                if not clicked:          # the clicked row is under the mouse
                    try:
                        tree.see(target)
                    except Exception:
                        pass
                panel._cursor_pin = (panel._fullname(target), _time.time())
                # Arriving here by Tab or a click is NOT a Home press, so the
                # next Home must still mean "top of the list".
                panel._home_stamp = ("", 0.0)
        except Exception:
            pass

    @staticmethod
    def _panel_default_cursor(panel):
        """Which row should carry the cursor when a panel has none.

        Order: the row the keyboard cursor already stands on (INCLUDING the
        ".." dots), else the row it last stood on (matched by name, so it
        survives a rebuild), else the first row that is NOT "..", else "..".

        The focus row comes first because of revAO: skipping straight to
        "_last_cursor_name" quietly slid the cursor off a deliberate ".." and
        onto the first FILE just below it — so a Tab followed by Enter opened
        a file instead of going up a level.  A cursor that is really on ".."
        is an answer, not a missing value.
        """
        tree = panel.tree
        kids = tree.get_children()
        if not kids:
            return None
        try:
            foc = tree.focus()
            if foc and tree.exists(foc):
                _trace.write("DEFAULT-CURSOR",
                             note=f"panel={panel.side} -> the focus row "
                                  f"{panel._fullname(foc)!r}")
                return foc
        except Exception:
            pass
        wanted = getattr(panel, "_last_cursor_name", "")
        if wanted:
            for iid in kids:
                try:
                    if panel._fullname(iid) == wanted:
                        return iid
                except Exception:
                    break
        for iid in kids:
            if tree.item(iid, "text") != "..":
                _trace.write("DEFAULT-CURSOR",
                             note=f"panel={panel.side} -> FIRST ROW BELOW the "
                                  f"dots ({panel._fullname(iid)!r}) - no focus "
                                  f"row and no remembered row {wanted!r}")
                return iid
        return kids[0]

    def _activate_side(self, new_side: str, set_focus: bool = True):
        """Make *new_side* the active panel and DEMOTE the other panel's real
        (dark-blue) selection to the muted inactive colour — so the active
        cursor can appear in ONLY ONE panel at a time.

        Every activation path (Tab, a mouse click, keyboard focus) goes through
        here.  Before this existed, clicking a panel changed `active_panel` but
        left the OTHER panel's dark-blue selection on screen, so BOTH looked
        active — and F5/F6 then acted on the wrong panel.  That is the accident
        this prevents."""
        if new_side not in ("left", "right"):
            return
        if getattr(self, "_activating", False):
            self._ct("ACTIVATE-skip",
                     f"to={new_side} set_focus={set_focus} — reentrant, ignored",
                     depth=2)
            return
        self._ct("ACTIVATE-in", f"to={new_side} set_focus={set_focus}", depth=2)
        self._activating = True
        try:
            entering = self.left_panel if new_side == "left" else self.right_panel
            leaving  = self.get_active_panel()
            if leaving is not entering:
                self._demote_panel(leaving)
                self.active_panel = new_side
                self._promote_panel(entering)
            else:
                # Already the active side — still make sure the OTHER panel is
                # demoted, in case a stray dark-blue selection lingers there.
                other = self.right_panel if new_side == "left" else self.left_panel
                self._demote_panel(other)
                self.active_panel = new_side
            if set_focus:
                try:
                    entering.tree.focus_set()
                except Exception:
                    pass
            self.sync_side_panels()
        finally:
            self._activating = False
        self._ct("ACTIVATE-out", f"to={new_side}", depth=2)

    def switch_panel(self):
        """Tab — activate the OTHER panel."""
        other = "right" if self.active_panel == "left" else "left"
        self._ct("TAB-before", f"going to the {other.upper()} panel")
        self._activate_side(other, set_focus=True)
        self._ct("TAB-after", f"now on the {other.upper()} panel")

    # ── Cursor jumps between the folder block and the file block ─────────
    #
    # Home/End go all the way to the top/bottom and Page Up/Down move one
    # window-full, so neither lands on the FIRST FILE when a folder holds
    # hundreds of sub-folders.  These two do exactly that, in whatever order
    # the list is currently sorted:
    #     Ctrl+Down  →  the first file  (the row just below the last folder)
    #     Ctrl+Up    →  the first folder (the row just below "..")
    # Both are rebindable in Settings ▸ Configure shortcuts.

    def _goto_row_kind(self, want_dir: bool):
        """Move the active panel's cursor to the first folder / first file row.

        Display order is what counts, so this follows the panel's current sort
        (and the "folders first" setting) instead of re-deriving anything.
        """
        panel = self.get_active_panel()
        tree  = getattr(panel, "tree", None)
        if tree is None:
            return
        kids = tree.get_children()
        if not kids:
            return

        def _is_dir(iid):
            try:
                return tree.set(iid, "type") == "Folder"
            except Exception:
                return False

        target = None
        for iid in kids:
            if tree.item(iid, "text") == "..":
                continue          # the parent-directory dots are never the target
            if _is_dir(iid) == want_dir:
                target = iid
                break

        if target is None:
            # Nothing of that kind here.  Land somewhere sensible rather than
            # doing nothing at all: the last row when hunting for files, the
            # first real row when hunting for folders.
            rest = [i for i in kids if tree.item(i, "text") != ".."]
            if not rest:
                target = kids[0]
            else:
                target = rest[-1] if not want_dir else rest[0]
            self._flash_status("No folders here." if want_dir else "No files here.",
                               1500)

        tree.see(target)
        tree.selection_set(target)
        tree.focus(target)
        tree.focus_set()

    def _goto_first_file(self):
        """Ctrl+Down — jump to the topmost FILE, past '..' and all folders."""
        self._goto_row_kind(want_dir=False)

    def _goto_first_folder(self):
        """Ctrl+Up — jump to the topmost FOLDER, just past the '..' row."""
        self._goto_row_kind(want_dir=True)

    def sync_side_panels(self):
        """Point Quick View and the command bar at the active panel."""
        qv = getattr(self, "quickview", None)
        if qv is not None and qv.visible:
            qv.update_current()
        bar = getattr(self, "cmdbar", None)
        if bar is not None and bar.visible:
            bar.update_prompt()
        # The bottom-bar counter follows the active panel too
        self._update_counts()

    def _set_initial_focus(self):
        """Put a cursor in each panel at startup; dim the inactive (right) one.

        Both cursors land on the first REAL row, never on the ".." dots — an
        Enter straight after startup should open something, not climb a level.
        """
        # Right panel: mark its cursor row as inactive selection (grayed)
        rtree  = self.right_panel.tree
        rfirst = self._panel_default_cursor(self.right_panel)
        if rfirst:
            tags = list(rtree.item(rfirst, "tags"))
            if "inactive_sel" not in tags:
                tags.append("inactive_sel")
            rtree.item(rfirst, tags=tags)

        # Left panel: real selection + keyboard focus
        tree  = self.left_panel.tree
        first = self._panel_default_cursor(self.left_panel)
        if first:
            tree.selection_set(first)
            tree.focus(first)
        tree.focus_set()

    def get_active_panel(self):
        return self.left_panel if self.active_panel == "left" else self.right_panel

    def get_inactive_panel(self):
        return self.right_panel if self.active_panel == "left" else self.left_panel

    def show_disk_menu(self, side):
        panel = self.left_panel if side == "left" else self.right_panel
        menu  = tk.Menu(self, tearoff=0)
        if getattr(panel, "is_remote", False):
            menu.add_command(label="Disconnect FTP",
                             command=lambda: self.unmount_ftp_panel(side))
            menu.post(self.winfo_rootx(), self.winfo_rooty())
            return
        disks = self._get_available_disks()
        # Jump this panel to the EXACT folder the other panel is showing
        # (same folder, same drive) — handy for lining both panels up.
        other = self.right_panel if side == "left" else self.left_panel
        if (not getattr(other, "is_remote", False)
                and os.path.isdir(other.current_path)):
            menu.add_command(
                label=f"⇉  Same folder as other panel   ({other.current_path})",
                command=lambda p=other.current_path: self._change_disk(
                    side, p, use_memory=False))
            menu.add_separator()

        # ── Network: never an empty "type it yourself" box any more ───────
        menu.add_cascade(label="🖧  Network location",
                         menu=self._build_network_submenu(menu, side))
        # ── Phones, cameras, MP3 players (MTP — no drive letter) ──────────
        menu.add_cascade(label="📱  Phone / portable device",
                         menu=self._build_devices_submenu(menu, side))
        menu.add_separator()
        for path, (total, free), info in disks:
            # Letter FIRST — before the icon, not after it — then the volume
            # name: "D:\  💾  8 TB Backup 1".  Two reasons: two look-alike
            # drives are told apart at a glance, and the drive letter sits at
            # position 0 of the label, where the mnemonic underline is right
            # whichever way Tk counts characters (an emoji in front used to
            # push the count out by one and kill the key press entirely).
            # A drive with no volume label set in Windows simply has no name
            # to show; the kind (Fixed / Removable / Network / CD-DVD) is
            # always there.
            vol   = info["label"].strip()
            # If this panel already stood somewhere on that volume, say so in
            # the label — the entry then goes THERE, not to the root, and you
            # can see that before you pick it.
            back = self._drive_recall(side, path)
            hint = ""
            if back != path:
                tail = os.path.splitdrive(back)[1].strip("\\/")
                hint = f"   ⤷ {tail}"
            label = (f"{path}   {info['icon']}"
                     + (f"  {vol}" if vol else "")
                     + f"   —   {free} free of {total}   ({info['kind']})"
                     + hint)
            menu.add_command(
                label=label,
                # The drive LETTER itself is the mnemonic — while this menu
                # is open, pressing e.g. "x" jumps straight to X:.  It only
                # works for as long as the menu stays posted; it is not a
                # standing keyboard shortcut anywhere else.
                underline=_underline_at(label, path[0]),
                command=lambda d=path: self._change_disk(side, d)
            )
        menu.add_separator()
        for name, path in self.settings.get("favorites", []):
            menu.add_command(label=name,
                             command=lambda p=path: self._change_disk(side, p))
        menu.add_separator()
        panel = self.left_panel if side == "left" else self.right_panel
        menu.add_command(
            label="📌  Pin current folder as start folder",
            command=lambda: self._pin_start_dir(side, panel.current_path)
        )
        x = 0 if side == "left" else self.winfo_width() // 2
        menu.post(self.winfo_rootx() + x, self.winfo_rooty())

    # ── Drive-menu sub-menus (network + portable devices) ────────────────

    def _build_network_submenu(self, parent_menu, side):
        """Ready-made network targets — no need to know any path by heart.

        Lists, in this order: the drive letters Windows already has mapped,
        your saved network favourites, the network paths you opened recently,
        and finally the ways to FIND something new (browse/scan).
        """
        sub = tk.Menu(parent_menu, tearoff=0)
        sub.add_command(label="🔍  Find network locations…  (browse / scan)",
                        command=lambda: NetworkDriveDialog(self, side))
        sub.add_separator()

        try:
            _avail, mapped = _net_get_drive_info_cached()
        except Exception:
            mapped = []
        if mapped:
            sub.add_command(label="—  Mapped network drives  —", state="disabled")
            for letter, unc in mapped:
                # Letter first here as well, for the same mnemonic reason as
                # the plain disks above.
                lbl = f"{letter}\\   🔗   →   {unc}"
                sub.add_command(
                    label=lbl,
                    # These have a drive letter too — same "press the letter
                    # while the menu is open" shortcut as the plain disks.
                    underline=_underline_at(lbl, letter[0]),
                    command=lambda d=f"{letter}\\": self._change_disk(side, d))
            sub.add_separator()

        favs = [f for f in _net_load_favorites() if f.get("path")]
        if favs:
            sub.add_command(label="—  Saved favourites  —", state="disabled")
            for fav in favs:
                p   = fav["path"]
                ltr = fav.get("letter", "")
                sub.add_command(
                    label=f"📌  {p}" + (f"   ({ltr})" if ltr else ""),
                    command=lambda q=p: self._change_disk(side, q))
            sub.add_separator()

        recent = self.settings.get("net_recent", [])
        if recent:
            sub.add_command(label="—  Recently opened  —", state="disabled")
            for p in recent[:10]:
                sub.add_command(label=f"🕘  {p}",
                                command=lambda q=p: self._change_disk(side, q))
            sub.add_separator()

        sub.add_command(label="🖧  Browse shares of one computer…",
                        command=self.open_shares)
        sub.add_command(label="📡  Scan the LAN for computers…",
                        command=self.open_network_window)
        sub.add_command(label="⌨  Type a path by hand…",
                        command=lambda: self._connect_network_drive(side))
        return sub

    def _build_devices_submenu(self, parent_menu, side):
        """Phones / cameras / media players that Windows shows WITHOUT a drive
        letter (MTP).  Those can never appear in the drive list, which is why a
        connected phone looked missing — they live here instead."""
        sub = tk.Menu(parent_menu, tearoff=0)
        sub.add_command(label="📱  Open device browser…",
                        command=lambda: PortableDeviceWindow(self, side))
        sub.add_separator()
        try:
            devices = mtp_list_devices_cached()
        except Exception as exc:
            devices = []
            _log(f"Portable device scan failed: {exc}")
        if devices:
            for dev in devices:
                sub.add_command(
                    label=f"📱  {dev['name']}",
                    command=lambda d=dev: PortableDeviceWindow(self, side,
                                                               device=d["name"]))
        else:
            sub.add_command(label="(no phone / camera detected)", state="disabled")
        sub.add_separator()
        # A phone in "USB drive" mode DOES get a letter — surface those too, so
        # both connection modes are reachable from the same place.
        removables = [d for d in self._get_available_disks()
                      if d[2]["kind"] in ("Removable", "CD/DVD")]
        if removables:
            sub.add_command(label="—  Removable drives  —", state="disabled")
            for path, (total, free), info in removables:
                sub.add_command(
                    label=f"{info['icon']}  {path}{info['label']}   ({free} free)",
                    command=lambda d=path: self._change_disk(side, d))
            sub.add_separator()
        sub.add_command(label="🔄  Rescan now  (just plugged something in?)",
                        command=self._rescan_devices)
        return sub

    def _rescan_devices(self):
        """Drop the cached device / mapped-drive lists so the next drive menu
        goes and looks again — for when you plug a phone in with the menu
        already open."""
        _MTP_CACHE["when"] = 0.0
        _NET_DRIVES_CACHE["when"] = 0.0
        _mtp_warm_caches()
        self._flash_status("Re-scanning devices — open the drive menu again.",
                           2500)

    def _show_disk_overview(self):
        win = tk.Toplevel(self)
        _setup_toplevel(win, "Disk overview", self)
        win.geometry("480x300")
        tree = ttk.Treeview(win, columns=("kind", "total", "free"), selectmode="browse")
        tree.heading("#0",     text="Drive")
        tree.heading("kind",   text="Type")
        tree.heading("total",  text="Total")
        tree.heading("free",   text="Free")
        tree.column("#0",    width=180)
        tree.column("kind",  width=100, anchor="w")
        tree.column("total", width=110, anchor="e")
        tree.column("free",  width=110, anchor="e")
        # The row TEXT now carries an icon and the volume label, so the real
        # path is kept beside it instead of being read back out of the label.
        iid_path = {}
        for path, sizes, info in self._get_available_disks():
            iid = tree.insert("", "end",
                              text=f"{info['icon']} {path}{info['label']}",
                              values=(info["kind"],) + tuple(sizes))
            iid_path[iid] = path
        tree.pack(fill="both", expand=True, padx=6, pady=6)
        tree.bind("<Double-1>",
                  lambda e: self._open_selected_disk(tree, win, iid_path))
        frm = ttk.Frame(win)
        frm.pack(fill="x", padx=6, pady=4)
        ttk.Button(frm, text="Open",
                   command=lambda: self._open_selected_disk(tree, win, iid_path)
                   ).pack(side="left")
        ttk.Button(frm, text="Close", command=win.destroy).pack(side="right")

    def _open_selected_disk(self, tree, win, iid_path=None):
        item = tree.selection()
        if item:
            path = (iid_path or {}).get(item[0]) or tree.item(item[0], "text")
            self.get_active_panel().change_directory(path)
            win.destroy()

    def _get_available_disks(self):
        """Every drive letter Windows currently has, with what KIND it is.

        Returns [(path, (total, free), info)] where info carries an icon, the
        volume label and a human kind ("Fixed", "Removable", "Network", …).
        Knowing the kind matters: a phone in "USB drive" mode shows up as
        Removable, while a phone in the normal MTP mode has no letter at all
        (see the Phone / portable device sub-menu)."""
        disks = []
        for d in "ABCDEFGHIJKLMNOPQRSTUVWXYZ":
            path = f"{d}:\\"
            if not os.path.exists(path):
                continue
            try:
                free_b  = ctypes.c_ulonglong(0)
                total_b = ctypes.c_ulonglong(0)
                ctypes.windll.kernel32.GetDiskFreeSpaceExW(
                    ctypes.c_wchar_p(path), None,
                    ctypes.pointer(total_b), ctypes.pointer(free_b)
                )
                t = total_b.value;  f = free_b.value
                sizes = (
                    f"{t//(1024**3)} GB" if t else "N/A",
                    f"{f//(1024**3)} GB" if f else "N/A",
                )
            except Exception:
                sizes = ("N/A", "N/A")
            disks.append((path, sizes, _drive_kind_info(path)))
        return disks

    def _connect_network_drive(self, side):
        """Type a UNC path by hand — the no-blink fallback for when you already
        know exactly where you are going.  Everything else lives in
        NetworkDriveDialog (ready-made lists + scanning)."""
        path = _ask_text(self, "Connect network drive",
                         "Enter path (e.g. \\\\server\\share):")
        if path:
            self._change_disk(side, path)

    def _remember_net_path(self, path: str):
        """Keep the last network locations that actually opened, so the drive
        menu can offer them instead of an empty box."""
        try:
            if not str(path).startswith("\\\\"):
                return
            recent = [p for p in self.settings.get("net_recent", [])
                      if os.path.normcase(p) != os.path.normcase(path)]
            recent.insert(0, path)
            self.settings["net_recent"] = recent[:15]
            self.save_settings()
        except Exception:
            pass

    # ── Drive memory: where you were standing on each volume ─────────────
    # Switching D: → C: → D: used to drop you in D:\ every time.  Every
    # navigation records the folder against its volume; picking that volume
    # from the drive menu goes back there instead of to the root.

    @staticmethod
    def _drive_key(path: str) -> str:
        """The volume a path lives on, as a dictionary key.

        "D:\\Foo\\Bar" → "d:";   "\\\\nas\\media\\x" → "\\\\nas\\media".
        Returns "" for anything with no volume of its own (an MTP device
        pseudo-path, a half-typed path) — the caller reads that as "do not
        remember this one"."""
        try:
            drv = os.path.splitdrive(str(path))[0]
        except Exception:
            return ""
        return os.path.normcase(drv) if drv else ""

    @staticmethod
    def _is_volume_root(path: str) -> bool:
        """True for "D:\\" and "\\\\nas\\media\\" — nothing below the volume."""
        try:
            return os.path.splitdrive(str(path))[1].strip("\\/") == ""
        except Exception:
            return False

    def _drive_mem(self, side: str) -> dict:
        """The live per-volume map for one panel (created on first use)."""
        store = getattr(self, "_drive_last", None)
        if not isinstance(store, dict):
            saved = self.settings.get("drive_last", {})
            store = {"left": {}, "right": {}}
            if isinstance(saved, dict):
                for s in ("left", "right"):
                    if isinstance(saved.get(s), dict):
                        store[s] = dict(saved[s])
            self._drive_last = store
        return store.setdefault(side, {})

    def _remember_drive_dir(self, side: str, path: str):
        """Record "this is where <side> stands on that volume".

        Called on every navigation, so it must stay cheap: it only touches a
        dictionary.  The write to disk happens in _change_disk, which is the
        rare, deliberate action."""
        key = self._drive_key(path)
        if not key:
            return
        self._drive_mem(side)[key] = str(path)

    def _drive_recall(self, side: str, path: str) -> str:
        """Turn a bare volume root into the folder this panel last stood in.

        Anything that is not a bare root (a favourite, a network path, "same
        folder as the other panel") is handed back untouched — those already
        say exactly where to go."""
        if not self.settings.get("drive_memory", True):
            return path
        if not self._is_volume_root(path):
            return path
        key = self._drive_key(path)
        if not key:
            return path
        remembered = self._drive_mem(side).get(key, "")
        if not remembered or self._is_volume_root(remembered):
            return path
        # The volume may have been unplugged and a different one given the
        # same letter since — check the folder is really there before jumping.
        try:
            if not os.path.isdir(remembered):
                return path
        except Exception:
            return path
        return remembered

    def _save_drive_mem(self):
        """Write the drive memory out now (save_settings folds it in itself).

        Called when you actually change drive — a rare, deliberate action, so
        one small JSON write is nothing.  Every other save (Settings, close)
        carries it along too."""
        try:
            self.save_settings()
        except Exception as exc:
            _log(f"Could not save the drive memory: {exc}")

    def _change_disk(self, side, path, use_memory: bool = True):
        """Send one panel to *path*.

        *use_memory* False means "go EXACTLY there" — used by "same folder as
        the other panel", which would otherwise line the panels up with a
        remembered folder instead of with the other panel."""
        panel = self.left_panel if side == "left" else self.right_panel
        if getattr(panel, "is_remote", False):
            messagebox.showinfo("Info", "Panel is FTP-mounted. Disconnect first.")
            return
        # Leaving this volume: make sure where we stand right now is recorded
        # before we go, then see whether the target volume has a folder
        # waiting for us.
        try:
            self._remember_drive_dir(side, panel.current_path)
        except Exception:
            pass
        target = self._drive_recall(side, path) if use_memory else path
        panel.change_directory(target)
        if target != path:
            self._flash_status(f"↩  Back where you left {self._drive_key(path).upper()}"
                               f"  —  {target}   (↖ goes to the root)")
        self._remember_net_path(target)
        self._save_drive_mem()
        self._update_disk_info()

    def _pin_start_dir(self, side: str, path: str):
        """Save current path as the permanent start directory for this panel."""
        key = f"start_dir_{side}"
        self.settings[key] = path
        self.save_settings()
        messagebox.showinfo(
            "Start folder pinned",
            f"{'Left' if side == 'left' else 'Right'} panel will now start in:\n{path}"
        )

    def _update_disk_info(self):
        """Rebuild both side sections of the status bar.  Each shows its own
        panel's path, its file/folder counts and the drive's free space, so the
        LEFT section is always the left panel and the RIGHT section always the
        right one — no more guessing which path belongs to which side."""
        # The ⚖ Rules button stands over these same two folders, so it is kept
        # in step here — the one place that already runs whenever either panel
        # settles.  It costs nothing while the pair has not changed (DEL 52).
        try:
            self._rules_btn_sync()
        except Exception:
            pass
        def side_text(panel, side_name):
            if getattr(panel, "is_remote", False):
                return (f"{side_name}   FTP {panel.host}:{panel.port}"
                        f"   |   {panel.current_path}")
            path = panel.current_path
            nf   = getattr(panel, "_n_files", 0)
            nd   = getattr(panel, "_n_dirs", 0)
            return (f"{side_name}   {path}   |   "
                    f"{nf} files, {nd} folders   |   "
                    f"{self._get_disk_info(path)}")
        try:
            self._left_disk.config( text=side_text(self.left_panel,  "◧ LEFT"))
            self._right_disk.config(text=side_text(self.right_panel, "◨ RIGHT"))
        except Exception:
            pass
        self._refresh_side_highlight()

    def _get_disk_info(self, path):
        try:
            free_b  = ctypes.c_ulonglong(0)
            total_b = ctypes.c_ulonglong(0)
            root = os.path.splitdrive(path)[0] + "\\"
            ctypes.windll.kernel32.GetDiskFreeSpaceExW(
                ctypes.c_wchar_p(root), None,
                ctypes.pointer(total_b), ctypes.pointer(free_b)
            )
            f = free_b.value;  t = total_b.value
            # ...and WHICH FORMAT, permanently on screen (revBO).  The status
            # bar has always had room for it and has never said it; asking
            # required a right-click.  Cached per drive — a file system does
            # not change under you, and this runs every time either panel
            # settles, for both sides.
            return (f"{f//(1024**2):,} MB free of {t//(1024**3):,} GB"
                    + _fs_name_cached(root))
        except Exception:
            return "Disk info unavailable"

    def refresh_panels(self):
        self.left_panel.refresh()
        self.right_panel.refresh()
        # A refresh is where a deletion of ours lands, so this is the natural
        # place to notice that some OTHER tab was standing in what just went
        # (revBU).  A handful of isdir() calls next to two full directory
        # scans — it costs nothing here.
        try:
            self._rescue_gone_tabs()
        except Exception as exc:
            _log(f"Tab rescue sweep: {exc}")
        self._update_disk_info()

    # ── A folder a tab was standing in has gone (revBU) ───────────────────

    def _folder_vanished(self, gone: str, landed: str):
        """The visible panel found its folder deleted and walked up to *landed*.

        Say so, and check every OTHER tab at once — the same delete may have
        taken the ground out from under three of them, and finding that out one
        by one as you click them is finding out too late."""
        try:
            self._flash_status(
                f"The folder was deleted — this tab moved up to  {landed}", 8000)
        except Exception:
            pass
        try:
            self._rescue_gone_tabs()
        except Exception as exc:
            _log(f"Tab rescue after {gone!r}: {exc}")

    def _rescue_gone_tabs(self) -> int:
        """Every tab standing in a folder that no longer exists walks UP.

        Asked for in as many words (revBU): "Alla påverkade tabbar ska gå upp
        ett steg, så länge som det krävs, till dess att de når en icke-raderad
        katalog."  So: both panels, every tab in the strip, not just the one
        being looked at — and up one level at a time, never across the disk to
        the user folder.

        FTP panels and UNC server paths are left alone: testing a network path
        that is down can block for seconds, and a window that stops answering
        is worse than a stale tab.
        Returns how many tabs moved.
        """
        moved = 0
        for side in ("left", "right"):
            panel = self.left_panel if side == "left" else self.right_panel
            if panel is None or getattr(panel, "is_remote", False):
                continue
            tabs    = self.left_tabs if side == "left" else self.right_tabs
            cur_idx = self.left_tab_idx if side == "left" else self.right_tab_idx
            changed = False
            for i, p in enumerate(list(tabs)):
                if not p or _path_is_network(p):
                    continue
                try:
                    if os.path.isdir(p):
                        continue
                except Exception:
                    continue
                up = _nearest_existing_dir(p)
                if not up or os.path.normcase(up) == os.path.normcase(p):
                    continue
                tabs[i] = up
                changed  = True
                moved   += 1
                _log(f"Tab {side}#{i}: {p!r} is gone — moved up to {up!r}")
                if i == cur_idx:
                    # The visible one: its own refresh() has usually put it
                    # here already, but a tab switched to while the folder was
                    # going can still be behind.  NOT change_directory() — this
                    # may be running from inside that panel's own refresh().
                    panel.current_path = os.path.abspath(up)
            if changed:
                try:
                    self._render_tab_bar(side)
                    self._ws_autosave_extras(side)
                except Exception as exc:
                    _log(f"Tab strip could not be redrawn: {exc}")
        return moved

    # ══ Build watch (revAR) ════════════════════════════════════════════
    #
    # "Is the program I run still the program I wrote?"  Compares each source
    # .py against the program built from it and says which ones have moved on.
    # It never builds anything — see the build_watch_scan comment block.

    def _build_watch_startup(self):
        """The quiet check at startup.  Filesystem work on a worker thread,
        one status line on the UI thread, and nothing at all when there is
        nothing to say."""
        chosen = list(self.settings.get("watch_chosen") or [])
        if not chosen:
            return
        srcs  = list(self.settings.get("watch_src_dirs") or [])
        bilds = list(self.settings.get("watch_build_dirs") or [])

        def work():
            try:
                rows = [r for r in build_watch_scan(srcs, bilds)
                        if r["name"] in chosen]
            except Exception as exc:
                _log(f"Build watch failed: {exc}")
                return
            _ui_call(self, lambda: self._build_watch_report(rows))

        threading.Thread(target=work, daemon=True).start()

    def _build_watch_report(self, rows: list):
        stale = [r for r in rows if r["state"] in ("newer source", "never built")]
        slow  = [r for r in rows if r["state"] == "one-file"]
        bits = []
        if stale:
            bits.append(f"{len(stale)} with newer source ("
                        + ", ".join(r["name"] for r in stale[:3])
                        + (" …" if len(stale) > 3 else "") + ")")
        if slow:
            bits.append(f"{len(slow)} still built one-file (slow to start)")
        self._build_watch_last = rows
        if not bits:
            self._ct("BUILD-WATCH", f"{len(rows)} watched, all up to date")
            return
        msg = "Programs: " + "  ·  ".join(bits) + "   —  Settings ▸ My programs"
        self._ct("BUILD-WATCH", msg)
        self._flash_status(msg, 12000)

    def _schedule_trace_prune(self):
        """Re-prune every 30 minutes, for sessions that run for days."""
        try:
            self.after(30 * 60 * 1000, self._trace_prune_tick)
        except Exception:
            pass

    def _trace_prune_tick(self):
        try:
            _trace.prune()
        except Exception:
            pass
        self._schedule_trace_prune()

    def open_trace_log(self):
        """Show the cursor trace log — the file to send when the cursor lands
        somewhere you did not put it."""
        try:
            if not TRACE_PATH.exists():
                messagebox.showinfo(
                    "Cursor trace log",
                    "Nothing has been logged yet.\n\n"
                    f"It will be written to:\n{TRACE_PATH}",
                    parent=self)
                return
            _trace.close()          # flush before anything reads it
            self._open_file_activated(str(TRACE_PATH), False, False)
        except Exception as exc:
            messagebox.showerror("Cursor trace log", str(exc), parent=self)

    def _refresh_and_refocus(self):
        self._ct("REFRESH+REFOCUS", depth=2)
        return self.__refresh_and_refocus()

    def __refresh_and_refocus(self):
        """Post-operation refresh that ALSO hands the keyboard back to the active
        file list, so the arrow keys work again with no mouse click — but only
        when our own window is the foreground app, so it never yanks focus from
        another program the user switched to while the job ran in the background."""
        self.refresh_panels()
        try:
            if os.name == "nt":
                try:
                    user32 = ctypes.windll.user32
                    fg  = user32.GetForegroundWindow()
                    our = user32.FindWindowW(None, self.winfo_toplevel().title())
                    # Foreground is some OTHER program (or the Task Queue) → leave
                    # focus alone; the queue has its own keyboard watchdog.
                    if fg and our and fg != our:
                        return
                except Exception:
                    pass
            panel = self.get_active_panel()
            if panel is not None and hasattr(panel, "tree"):
                panel.tree.focus_set()
        except Exception:
            pass

    # ── Helpfiles path control ────────────────────────────────────────────

    def choose_save_path(self, preferred_dir: str, filename: str) -> str:
        ext = Path(filename).suffix.lower()
        if ext != ".py" and self.settings.get("force_helpdir_saves", False):
            return str(HELP_DIR)
        return preferred_dir

    # ── File operations ───────────────────────────────────────────────────

    def _parent_key(self, event=None):
        """Alt+Up — parent folder, never anything else.

        Bails out while the keyboard is in a text field, the same way every
        rebindable shortcut does, so Alt+Up in a rename box is left alone."""
        w = getattr(event, "widget", None)
        if isinstance(w, (tk.Entry, ttk.Entry, tk.Text, ttk.Combobox)):
            return
        if self._focus_in_text_widget():
            return
        self.go_up()
        return "break"

    def go_up(self):
        panel = self.get_active_panel()
        if getattr(panel, "archive_ctx", None):
            panel.archive_go_up()
        else:
            panel.go_up()

    def go_root(self):
        panel = self.get_active_panel()
        if getattr(panel, "archive_ctx", None):
            panel.archive_ctx = None
            panel._hide_archive_bar()
        panel.go_root()

    # ── F4 / external program ─────────────────────────────────────────────
    #  Windows remembers the program you once picked in its "Open with" box and
    #  then never asks again — which is how a stray choice (Notepad, say) turns
    #  into "F4 always opens the wrong editor" with no obvious way back.  So the
    #  program F4 uses is decided HERE, in this program's own settings, in three
    #  steps, most specific first:
    #     1. a per-extension entry in Settings ▸ Custom openers
    #     2. the F4 program in Settings ▸ Custom openers (optionally limited to
    #        a list of extensions)
    #     3. whatever Windows associates with the file
    #  Shift+F4 skips 1 and 2 (straight to Windows), and Ctrl+F4 opens Windows'
    #  own "Open with" dialog so a bad association can be re-picked.

    def _f4_exts(self) -> set:
        """Extensions the F4 program covers.  Empty set = every file."""
        raw = self.settings.get("f4_extensions", "") or ""
        out = set()
        for tok in raw.replace(";", ",").split(","):
            tok = tok.strip().lower()
            if tok:
                out.add(tok if tok.startswith(".") else "." + tok)
        return out

    def _launch_program(self, program: str, args: str, path: str,
                        label: str = "F4") -> bool:
        """Start `program` on `path`.  `args` may contain %1 for the file name;
        with no %1 the file is appended.  Returns True when it started.
        *label* names the setting in error messages (e.g. "F4" / "Shift+F4")."""
        program = (program or "").strip().strip('"')
        if not program:
            return False
        if not os.path.isfile(program) and not shutil.which(program):
            messagebox.showerror(
                "Program not found",
                f"The program set for {label} does not exist:\n{program}\n\n"
                "Fix it in Settings ▸ Custom openers.")
            return False
        try:
            argstr = (args or "").strip()
            if argstr:
                if "%1" in argstr:
                    parts = _split_args(argstr.replace("%1", path))
                else:
                    parts = _split_args(argstr) + [path]
            else:
                parts = [path]
            cmd = [program] + parts
            # A .py is not something Windows can execute.  Handed straight to
            # CreateProcess it answers "…is not a valid Win32 application",
            # which is what a custom opener pointing at one of his own
            # programs looks like now that they are run as SOURCES rather
            # than builds — "bort med exe, ersatt F3 med Py-filen".
            # pythonw, not python: a console window would flash up otherwise.
            if program.lower().endswith((".py", ".pyw")):
                pyw = _real_pythonw()
                if not pyw:
                    messagebox.showerror(
                        "No Python found",
                        f"{program}\n\nThis is a Python source file, and no "
                        "python.exe could be found to run it with.\n\n"
                        "Point the setting at the built .exe instead, or "
                        "install Python.")
                    return False
                cmd = [pyw, program] + parts
            subprocess.Popen(cmd)
            return True
        except Exception as exc:
            messagebox.showerror("Could not start program",
                                 f"{program}\n\n{exc}\n\n"
                                 "Falling back to the Windows default.")
            return False

    # ── DefaultHub — ONE file decides what opens what ───────────────────
    #
    # <home>\Helpfiles\DefaultHub\defaults.json is written by DefaultHub and
    # read by every one of my programs, so "PDFs open in X instead of PDFull"
    # is one edit in ONE place instead of 122 edits in 122 sources.
    #
    # Here it sits BELOW this program's own per-type openers — a local
    # override should still win — and ABOVE the Windows association.  A kind
    # the table marks "system" is a deliberate "let Windows have it", not a
    # gap, so it stops the search rather than falling through.

    def _hub_data(self) -> dict:
        """DefaultHub's whole file, read once and remembered.

        Measured 2026-09-05: 0.11 ms to read and parse, 0.05 ms warm.  Read
        lazily, so nothing is spent at start-up.  Missing or half-written
        means "no opinion" — never an error."""
        cached = getattr(self, "_hub_cache", None)
        if cached is not None:
            return cached
        data = {}
        try:
            f = os.path.join(APP_ROOT, "Helpfiles", "DefaultHub",
                             "defaults.json")
            if os.path.isfile(f):
                with open(f, "r", encoding="utf-8") as fh:
                    data = json.load(fh) or {}
        except Exception:
            data = {}
        self._hub_cache = data if isinstance(data, dict) else {}
        return self._hub_cache

    def _hub_kinds(self) -> dict:
        kinds = self._hub_data().get("kinds") or {}
        return kinds if isinstance(kinds, dict) else {}

    def _hub_py_roots(self) -> list:
        """Where DefaultHub says the programs live — its "py_roots" list, or
        the same automatic search it does when that list is empty.

        A target is only a NAME, and `APP_ROOT\\Py` alone cannot find one: the
        music programs are in `1---Musik\\Py` and Chess / Foul_bridge sit in
        their own folder under `1---Annat`.  The house-keeping folders are
        skipped on purpose — `0---Retired` and `0---Claude_work_dir` hold
        copies that are deliberately NOT his live programs."""
        listed = self._hub_data().get("py_roots") or []
        roots = []
        for entry in listed:
            entry = str(entry).strip()
            if not entry:
                continue
            # A RELATIVE entry ("1---Musik\\Py") is the shape DefaultHub
            # writes, and it is the point: an absolute path in a data file is
            # the first thing to break when the tree changes drive, which it
            # did on 2026-09-08 (C: -> X:).  Resolve it against APP_ROOT, the
            # same way the block in the other programs resolves it against
            # its roots.  An absolute one is still honoured.
            roots.append(entry if os.path.isabs(entry)
                         else os.path.join(APP_ROOT, entry))
        if roots:
            return roots
        roots = []
        seen  = set()

        def _add(d):
            try:
                if not os.path.isdir(d):
                    return
                ap, key = os.path.abspath(d), os.path.normcase(os.path.abspath(d))
            except Exception:
                return
            if key not in seen:
                seen.add(key)
                roots.append(ap)

        _add(os.path.join(APP_ROOT, "Py"))
        try:
            for entry in sorted(os.listdir(APP_ROOT)):
                low = entry.lower()
                if (low in ("py", "helpfiles", "icons", "folder-exe", "downloads")
                        or low.startswith("0---") or low.startswith("~")):
                    continue
                sub = os.path.join(APP_ROOT, entry)
                if not os.path.isdir(sub):
                    continue
                _add(os.path.join(sub, "Py"))
                try:
                    for name in sorted(os.listdir(sub)):
                        if name.lower().startswith("~") or "~deleted~" in name.lower():
                            continue
                        world = os.path.join(sub, name)
                        if (os.path.isdir(world)
                                and any(f.lower().endswith(".py")
                                        for f in os.listdir(world))):
                            _add(world)
                except OSError:
                    pass
        except OSError:
            pass
        return roots

    def _hub_command_for(self, path: str):
        """(program, args) DefaultHub wants for this file, or (None, "")."""
        try:
            ext = os.path.splitext(path)[1].lower()
            if not ext:
                return (None, "")
            name = ""
            for k in (self._hub_kinds() or {}).values():
                try:
                    if k.get("match_type") != "extension":
                        continue
                    if ext not in [str(m).lower() for m in (k.get("match") or [])]:
                        continue
                    if k.get("target_type") != "suite":
                        return (None, "")      # "system" — Windows' job
                    name = str(k.get("target") or "")
                    break
                except Exception:
                    continue
            # Never hand a file to myself — that is how you build a loop.
            if not name or name.lower() == "file_manager":
                return (None, "")
            # THE .PY WINS; a build is only the fallback.  A build is not
            # faster (that was one-FILE builds) and it is the only thing that
            # can be out of date — preferring it means quietly running last
            # week's code.  The .py is the file that actually gets edited.
            #
            # EVERY .py folder is searched before ANY build folder, or a stale
            # build in the main tree would beat the live source of a music
            # program.  The folder list is DefaultHub's — see _hub_py_roots.
            roots = self._hub_py_roots()
            for root in roots:
                script = os.path.join(root, name + ".py")
                if os.path.isfile(script):
                    pyw = _real_pythonw()
                    if pyw:
                        return (pyw, f'"{script}" "%1"')
                    break                 # no interpreter — try the builds
            for root in roots:
                exe = os.path.join(os.path.dirname(root), "Folder-exe",
                                   name, name + ".exe")
                if os.path.isfile(exe):   # no source, or no interpreter
                    return (exe, "")
        except Exception:
            pass
        return (None, "")

    def _open_local_file(self, path, use_overrides: bool = True,
                         use_hub: bool = True):
        """Open *path* outside this program.  With use_overrides=False the
        user's own F4 program and per-type openers are skipped, so you always
        get whatever Windows associates with the file (Shift+F4).

        *use_hub* is separate on purpose.  DefaultHub's table is not a
        forgotten local setting — it is the one place he WRITES DOWN which
        program owns a file type, shared by every program in the tree — so it
        applies on a plain double-click too, while the local overrides stay
        behind their own opt-in.  Shift+F4 turns both off and asks Windows."""
        ext = os.path.splitext(path)[1].lower()
        if use_overrides:
            # 1) per-extension opener
            custom = self.settings.get("custom_openers", {}) or {}
            if custom.get(ext):
                if self._launch_program(custom[ext],
                                        (self.settings.get("custom_opener_args", {})
                                         or {}).get(ext, ""), path):
                    return
            # 2) the F4 program (all files, or only the listed extensions)
            prog = (self.settings.get("f4_program", "") or "").strip()
            if prog:
                exts = self._f4_exts()
                if not exts or ext in exts:
                    if self._launch_program(prog,
                                            self.settings.get("f4_args", ""), path):
                        return
        # 3) DefaultHub's table — the shared choice for ALL my programs.
        #    Checked for existence first, so a stale entry falls quietly
        #    through to Windows instead of raising an error box.
        #    OUTSIDE the use_overrides block since revBE: this is the answer
        #    he wrote down himself, and skipping it was why a .jpg or a .pdf
        #    did nothing at all on Enter — it went to a Windows association
        #    that does not exist on this machine.
        if use_hub:
            hub_prog, hub_args = self._hub_command_for(path)
            if hub_prog:
                if self._launch_program(hub_prog, hub_args, path,
                                        label="DefaultHub"):
                    return
        # 4) Windows / desktop association
        #
        # os.startfile() is ASYNCHRONOUS — it returns as soon as the shell has
        # started the process, so the number logged here is what THIS program
        # spent, not how long the other program took to appear.  If this says
        # 3 ms and the window shows up a minute later, the minute is inside
        # the program that was started, not in here.  That is exactly how the
        # one-file .exe unpacking was pinned down; see "My programs".
        started = _time.time()
        try:
            if os.name == "nt":
                os.startfile(path)          # type: ignore[attr-defined]
            else:
                subprocess.Popen(["xdg-open", path])
            ms = (_time.time() - started) * 1000
            self._ct("OPEN-association",
                     f"handed {os.path.basename(path)} to Windows in {ms:.0f} ms "
                     f"(this call is async — the wait after it is the other "
                     f"program starting)")
            if ms > 1000:
                self._flash_status(
                    f"Windows took {ms/1000:.1f} s just to accept the file — "
                    f"see Settings ▸ My programs", 6000)
        except Exception as exc:
            # "No application is associated with this file" is the normal
            # answer on a machine that has no default apps registered, and an
            # error box is a useless one — it tells him what did NOT happen
            # and leaves him where he started.  Offer the two real ways on:
            # the built-in viewer, and Windows' own Open-with box.
            self._no_association_fallback(path, exc)

    def run_selected(self, console: bool = False):
        """Right-click ▸ ▶ Run — start the selected file (revBH)."""
        path = self._resolve_selected_local(self.get_active_panel())
        if not path:
            return
        if os.path.isdir(path):
            self._flash_status("That is a folder — Enter opens it.")
            return
        if not _is_runnable(path) and not _ask_yes_no(
                "Run",
                f"{os.path.basename(path)} is not a program file.\n\n"
                f"Hand it to Windows and let it decide what to do?",
                parent=self):
            return
        self._run_program(path, console=console)

    def run_selected_console(self):
        """Right-click ▸ ▶ Run in a console — same, with a window that STAYS.

        This is how you read the error from a script that would otherwise
        appear to do nothing at all."""
        self.run_selected(console=True)

    def _run_program(self, path: str, console: bool = False) -> bool:
        """Start *path* as a program.  True when it started (revBH).

        A .py is run through **pythonw.exe** unless a console is asked for.
        Windows' own association for .py is `python.exe "%1"`, which throws up
        a console window behind every one of his GUI programs — Tower and the
        open-with block both go out of their way to use pythonw for exactly
        that reason, so Enter here does the same.  `console=True` (right-click
        ▸ Run in a console) is the way to see the output of a script that
        really is a command-line tool, and to read an error that would
        otherwise vanish with the window.

        Never `run()`, always `Popen` — waiting would freeze the file manager
        until the program he just started is closed."""
        ext = os.path.splitext(path)[1].lower()
        folder = os.path.dirname(path) or None
        try:
            if ext in (".py", ".pyw"):
                # A frozen File_manager.exe must NEVER launch [sys.executable,
                # …] for a .py — that starts a second File_manager, not Python.
                exe = _real_python() if console else _real_pythonw()
                if not exe:
                    os.startfile(path)          # type: ignore[attr-defined]
                    self._flash_status(f"Started  {os.path.basename(path)}"
                                       "   (via Windows — no Python found)")
                    return True
                flags = 0 if console else getattr(subprocess, "CREATE_NO_WINDOW", 0)
                subprocess.Popen([exe, path], cwd=folder, creationflags=flags)
            elif console and ext in (".bat", ".cmd", ".ps1"):
                # Keep the window open after the script ends, or the one thing
                # he opened a console for — the output — is gone instantly.
                cmd = os.path.join(os.environ.get("SystemRoot", r"C:\Windows"),
                                   "System32", "cmd.exe")
                if ext == ".ps1":
                    ps = os.path.join(os.environ.get("SystemRoot", r"C:\Windows"),
                                      "System32", "WindowsPowerShell", "v1.0",
                                      "powershell.exe")
                    subprocess.Popen([cmd, "/k", ps, "-ExecutionPolicy",
                                      "Bypass", "-File", path], cwd=folder)
                else:
                    subprocess.Popen([cmd, "/k", path], cwd=folder)
            else:
                os.startfile(path)              # type: ignore[attr-defined]
            self._flash_status(f"Started  {os.path.basename(path)}"
                               + ("   (console)" if console else ""))
            return True
        except Exception as exc:
            self._flash_status(f"Could not start {os.path.basename(path)} — {exc}",
                               6000)
            _log(f"run failed for {path}: {exc}")
            return False

    def _no_association_fallback(self, path, exc):
        """Windows would not open the file.  Offer what actually can (revBE)."""
        name = os.path.basename(path)
        ext  = os.path.splitext(path)[1].lower() or "(no extension)"
        # The built-in viewer shows anything as text at worst, so only offer
        # it where it really renders the file — otherwise a JPG would be
        # offered as a screen of binary noise.
        can_view = ext in (_VIEWER_PDF_EXTS | _VIEWER_IMAGE_EXTS
                           | _VIEWER_AUDIO_EXTS)
        hub_target = ""
        try:
            for k in (self._hub_kinds() or {}).values():
                if (k.get("match_type") == "extension"
                        and ext in [str(m).lower() for m in (k.get("match") or [])]):
                    hub_target = str(k.get("target") or "")
                    break
        except Exception:
            pass
        if hub_target:
            why = (f"DefaultHub says {ext} belongs to \"{hub_target}\", but that "
                   f"program could not be found — check the target and the "
                   f"program folders in DefaultHub.")
        else:
            why = (f"Windows has no program registered for {ext}, and DefaultHub "
                   f"has no rule for it either.  Add one in DefaultHub and every "
                   f"program in the tree learns it at once.")
        if can_view:
            ok = _ask_yes_no(
                "Could not open",
                f"{name}\n\n{why}\n\nOpen it in the built-in viewer instead?",
                parent=self)
            if ok:
                self._open_builtin_viewer(path)
                return
        else:
            ok = _ask_yes_no(
                "Could not open",
                f"{name}\n\n{why}\n\nShow Windows' \"Open with\" box?",
                parent=self)
            if ok:
                try:
                    subprocess.Popen(["rundll32.exe",
                                      "shell32.dll,OpenAs_RunDLL", path])
                except Exception:
                    pass
                return
        self._flash_status(f"Could not open {name} — {exc}", 6000)

    def open_with_dialog(self):
        """Ctrl+F4 — Windows' own 'Open with' box for the selected file.

        This is the way OUT of a wrong association: Windows only asks once and
        then remembers, so there is otherwise no way to change your mind from
        inside a file manager."""
        path = self._resolve_selected_local(self.get_active_panel())
        if not path:
            return
        if os.name != "nt":
            self._open_local_file(path, use_overrides=False, use_hub=False)
            return
        try:
            subprocess.Popen(["rundll32.exe", "shell32.dll,OpenAs_RunDLL", path])
        except Exception as exc:
            messagebox.showerror("Open with", f"Could not show the dialog:\n{exc}")

    def _resolve_selected_local(self, panel):
        """Return a local path for the panel's selected file — downloading it
        first if the panel is a remote (FTP) one.  Returns None if nothing
        usable is selected.

        A panel standing INSIDE an archive has no real path for its rows (the
        folder beside the zip joined with an inner name is a file that does not
        exist), so the file is pulled out to a temp folder first (rev CF)."""
        if getattr(panel, "archive_ctx", None):
            return self._extract_archive_cursor_file(panel)
        if getattr(panel, "is_remote", False):
            sel = panel.get_selected()
            if not sel or sel[1]:
                return None
            try:
                return self._download_to_help(panel, sel[0])
            except Exception as exc:
                messagebox.showerror("FTP error", f"Download failed: {exc}")
                return None
        selected = panel.get_selected()
        if not selected or not os.path.isfile(selected):
            return None
        return selected

    def _extract_archive_cursor_file(self, panel):
        """Extract the marked / cursor FILE of an archive panel to a temp folder
        and return its path (None for a folder, '..', or a failed extraction)."""
        ctx = panel.archive_ctx
        names = panel.archive_selected_inner_names()
        if not names:
            return None
        inner = _norm_member(names[0])
        is_file = any(_norm_member(e.name) == inner and not e.is_dir
                      for e in ctx["entries"])
        if not is_file:
            return None
        tmp = tempfile.mkdtemp(prefix="fm_archview_")
        try:
            archive_extract_members(ctx["archive_path"], tmp, [inner])
        except ArchiveError as exc:
            _archive_error_box(self, exc)
            return None
        local = os.path.join(tmp, *inner.split("/"))
        if not os.path.isfile(local):
            messagebox.showinfo("Archive", "Could not extract that file.",
                                parent=self)
            return None
        return local

    def _external_opener_for(self, path: str):
        """The external program YOUR settings pick for this file, or None.

        Same resolution order the F4 key uses — a per-extension opener first,
        then the general F4 program (limited to its extension list, if it has
        one).  Returns (program, args, label)."""
        ext = os.path.splitext(path)[1].lower()
        custom = self.settings.get("custom_openers", {}) or {}
        if custom.get(ext):
            return (custom[ext],
                    (self.settings.get("custom_opener_args", {}) or {}).get(ext, ""),
                    "custom opener")
        prog = (self.settings.get("f4_program", "") or "").strip()
        if prog:
            exts = self._f4_exts()
            if not exts or ext in exts:
                return (prog, self.settings.get("f4_args", ""), "F4 program")
        return None

    def view_file(self):
        """F3 — view the selected file.

        With "Use my external program for F3 too" ticked (Settings ▸ Custom
        openers, ON by default) F3 hands the file to the SAME external program
        F4 would use, so one editor serves both keys and the built-in reader
        stays out of the way.  When no external program covers that file type,
        the built-in reader (text / image / PDF / audio) still handles it —
        otherwise F3 would simply do nothing.  Shift+Enter always forces the
        built-in reader regardless of this setting."""
        path = self._resolve_selected_local(self.get_active_panel())
        if not path:
            return
        if self.settings.get("f3_use_external", True):
            opener = self._external_opener_for(path)
            if opener and self._launch_program(opener[0], opener[1], path,
                                               label="F3 / F4"):
                return
        self._open_builtin_viewer(path)

    def edit_file(self):
        """F4 — open the selected file in the external program you chose
        (Settings ▸ Custom openers), or the Windows association if you chose
        none."""
        path = self._resolve_selected_local(self.get_active_panel())
        if path:
            self._open_local_file(path)

    def _f4b_exts(self) -> set:
        """Extensions the Shift+F4 (second) program covers.  Empty = every file."""
        raw = self.settings.get("f4b_extensions", "") or ""
        out = set()
        for tok in raw.replace(";", ",").split(","):
            tok = tok.strip().lower()
            if tok:
                out.add(tok if tok.startswith(".") else "." + tok)
        return out

    def edit_file_secondary(self):
        """Shift+F4 — open in your SECOND external program (Settings ▸ Custom
        openers ▸ 'Shift+F4 — second program', e.g. a different editor).

        With no second program set it falls back to the Windows association —
        exactly what Shift+F4 did before, so nothing is lost by default."""
        path = self._resolve_selected_local(self.get_active_panel())
        if not path:
            return
        prog = (self.settings.get("f4b_program", "") or "").strip()
        if prog:
            ext  = os.path.splitext(path)[1].lower()
            exts = self._f4b_exts()
            if (not exts or ext in exts) and self._launch_program(
                    prog, self.settings.get("f4b_args", ""), path,
                    label="Shift+F4"):
                return
        # No second program (or it did not apply / failed) → Windows association.
        # DefaultHub is skipped here too: Shift+F4 and Ctrl+F4 are the way OUT
        # to Windows, and a way out that quietly consults the table is no way out.
        self._open_local_file(path, use_overrides=False, use_hub=False)

    def edit_file_default(self):
        """Ignore my own F4 program; use the Windows association.  (Unbound by
        default now that Shift+F4 opens the second program — re-map it in
        Configure shortcuts if you want a dedicated key for it.)"""
        path = self._resolve_selected_local(self.get_active_panel())
        if path:
            self._open_local_file(path, use_overrides=False, use_hub=False)

    # ══════════════════════════════════════════════════════════════════════
    #  DEL 45 — PER-FOLDER SORT OVERRIDE
    # ----------------------------------------------------------------------
    #  "In XYZ123 I always want Name A→Z, even though the window is set to
    #   Modified newest-first."
    #
    #  A folder can carry its own sort, which wins over the panel's sort while
    #  you stand in it — and only there.  Set it by right-clicking a folder (or
    #  anywhere in the list, for the folder you are in) ▸ "Sort override".
    #  Optionally it applies to that folder's sub-folders too, so one rule can
    #  cover a whole tree.  Stored in Helpfiles/redigerare/folder_sorts.json as
    #      "<lower-case path>": {"sort": [f_col, f_rev, d_col, d_rev],
    #                            "sub": bool, "path": "<as typed>"}
    #  Nothing about the window's own sort is touched, so leaving the folder
    #  puts you straight back to your normal order.
    # ══════════════════════════════════════════════════════════════════════

    @staticmethod
    def _fs_key(path: str) -> str:
        """The dictionary key for a folder (case- and slash-insensitive)."""
        try:
            return os.path.normcase(os.path.abspath(path)).rstrip("\\/")
        except Exception:
            return (path or "").lower()

    def folder_sort_for(self, path: str):
        """The sort that should be used in *path*, or None.

        Returns (sort_list, rule_path, inherited).  An exact rule always wins;
        otherwise the nearest ancestor marked "apply to sub-folders" is used."""
        if not path or not self.folder_sorts:
            return None
        key = self._fs_key(path)
        rule = self.folder_sorts.get(key)
        if isinstance(rule, dict) and rule.get("sort"):
            return list(rule["sort"]), rule.get("path", path), False
        # Walk up: the closest ancestor whose rule says "sub-folders too" wins.
        parent = key
        while True:
            nxt = os.path.dirname(parent)
            if not nxt or nxt == parent:
                break
            parent = nxt
            rule = self.folder_sorts.get(parent)
            if isinstance(rule, dict) and rule.get("sort") and rule.get("sub"):
                return list(rule["sort"]), rule.get("path", parent), True
        return None

    def set_folder_sort(self, path: str, sort, sub=None, quiet=False):
        """Give *path* its own sort.  `sort` is [f_col, f_rev, d_col, d_rev]."""
        key = self._fs_key(path)
        old = self.folder_sorts.get(key) if isinstance(
            self.folder_sorts.get(key), dict) else {}
        self.folder_sorts[key] = {
            "sort": list(sort),
            "sub":  bool(old.get("sub", False)) if sub is None else bool(sub),
            "path": os.path.abspath(path),
        }
        _save_json_dict(FOLDER_SORTS_PATH, self.folder_sorts, portable=True)
        self._apply_folder_sorts()
        if quiet:
            # Header clicks land here — a popup on every click would be noise.
            self._flash_status(
                f"Sort override updated for “{os.path.basename(path) or path}” "
                f"(this folder only — the window's own sort is untouched)")
        else:
            _flash_ok(self, f"Sort override saved for\n{os.path.basename(path) or path}",
                      "Folder sort")

    def set_folder_sort_sub(self, path: str, value: bool):
        """Turn the 'also applies to sub-folders' flag on or off."""
        key = self._fs_key(path)
        rule = self.folder_sorts.get(key)
        if not isinstance(rule, dict) or not rule.get("sort"):
            return
        rule["sub"] = bool(value)
        _save_json_dict(FOLDER_SORTS_PATH, self.folder_sorts, portable=True)
        self._apply_folder_sorts()

    def clear_folder_sort(self, path: str):
        """Drop the override so the folder follows the window's sort again."""
        key = self._fs_key(path)
        if key in self.folder_sorts:
            del self.folder_sorts[key]
            _save_json_dict(FOLDER_SORTS_PATH, self.folder_sorts, portable=True)
            self._apply_folder_sorts()
            _flash_ok(self, "Override removed — this folder follows the "
                            "window's sort again.", "Folder sort")
        else:
            self._flash_status("This folder has no sort override of its own.")

    def _apply_folder_sorts(self):
        """Re-sort both panels after the rules changed."""
        for p in (self.left_panel, self.right_panel):
            try:
                if not getattr(p, "is_remote", False):
                    p._reapply_sort()
            except Exception:
                pass

    # Presets offered in the right-click menu.  (label, files_col, files_rev)
    FOLDER_SORT_FILE_PRESETS = (
        ("Name  A → Z",             "#0",       False),
        ("Name  Z → A",             "#0",       True),
        ("Modified  newest first",  "modified", True),
        ("Modified  oldest first",  "modified", False),
        ("Size  largest first",     "size",     True),
        ("Size  smallest first",    "size",     False),
        ("Type  A → Z",             "type",     False),
    )
    FOLDER_SORT_DIR_PRESETS = (
        ("Name  A → Z",             "#0",       False),
        ("Name  Z → A",             "#0",       True),
        ("Modified  newest first",  "modified", True),
        ("Modified  oldest first",  "modified", False),
    )

    def _folder_sort_target(self):
        """Which folder the override menu acts on: the SELECTED folder if one is
        highlighted, otherwise the folder the panel is standing in."""
        panel = self.get_active_panel()
        if panel is None or getattr(panel, "is_remote", False):
            return None
        try:
            sel = panel.get_selected()
            if sel and os.path.isdir(sel) and os.path.basename(sel) != "..":
                return sel
        except Exception:
            pass
        return panel.current_path

    def build_folder_sort_menu(self, menu=None, target=None):
        """Fill the 'Sort override' cascade — rebuilt on every right-click so it
        always names the folder you actually clicked and ticks its current
        setting."""
        if menu is None:
            menu = getattr(self, "_foldersort_menu", None)
        if menu is None:
            return
        menu.delete(0, "end")
        if target is None:
            target = self._folder_sort_target()
        if not target:
            menu.add_command(label="(not available here)", state="disabled")
            return

        name = os.path.basename(target) or target
        hdr = menu.add_command(label=f"Folder:  {name}", state="disabled")

        cur = self.folder_sort_for(target)
        cur_sort = cur[0] if cur else None
        inherited = bool(cur and cur[2])
        if cur and inherited:
            menu.add_command(
                label=f"(inherited from {os.path.basename(cur[1]) or cur[1]})",
                state="disabled")
        menu.add_separator()

        panel = self.get_active_panel()

        def _remember_current():
            self.set_folder_sort(target, panel.get_sort_state())

        menu.add_command(label="📌  Remember the sort I am using now",
                         command=_remember_current)
        menu.add_separator()

        # ---- Files ----
        fm = tk.Menu(menu, tearoff=0)
        for label, col, rev in self.FOLDER_SORT_FILE_PRESETS:
            mark = "● " if (cur_sort and cur_sort[0] == col
                            and bool(cur_sort[1]) == rev and not inherited) else "    "
            fm.add_command(
                label=mark + label,
                command=lambda c=col, r=rev, t=target: self._folder_sort_set_part(
                    t, files=(c, r)))
        menu.add_cascade(label="Files sorted by", menu=fm)

        # ---- Folders ----
        dm = tk.Menu(menu, tearoff=0)
        for label, col, rev in self.FOLDER_SORT_DIR_PRESETS:
            mark = "● " if (cur_sort and cur_sort[2] == col
                            and bool(cur_sort[3]) == rev and not inherited) else "    "
            dm.add_command(
                label=mark + label,
                command=lambda c=col, r=rev, t=target: self._folder_sort_set_part(
                    t, dirs=(c, r)))
        menu.add_cascade(label="Sub-folders sorted by", menu=dm)

        menu.add_separator()
        own = self.folder_sorts.get(self._fs_key(target))
        if isinstance(own, dict) and own.get("sort"):
            sub_var = tk.BooleanVar(value=bool(own.get("sub")))
            self._foldersort_subvar = sub_var          # keep a reference alive
            menu.add_checkbutton(
                label="Also use it in this folder's sub-folders",
                variable=sub_var,
                command=lambda t=target, v=sub_var: self.set_folder_sort_sub(
                    t, v.get()))
            menu.add_command(label="✖  Remove this folder's override",
                             command=lambda t=target: self.clear_folder_sort(t))
        menu.add_command(label="🗂  All folder overrides…",
                         command=self.open_folder_sort_manager)

    def _folder_sort_set_part(self, target, files=None, dirs=None):
        """Set only the file half or only the folder half of a folder's sort,
        leaving the other half as it already is (or as the panel shows now)."""
        cur = self.folder_sort_for(target)
        panel = self.get_active_panel()
        base = list(cur[0]) if cur else list(panel.get_sort_state())
        if files:
            base[0], base[1] = files[0], bool(files[1])
        if dirs:
            base[2], base[3] = dirs[0], bool(dirs[1])
        self.set_folder_sort(target, base)

    def show_empty_area_menu(self, panel, event):
        """Right-click on the EMPTY space under the file list. A small menu that
        acts on the folder you are standing IN, so the sort override is reachable
        even when the folder has no row of its own to click."""
        self._activate_side(panel.side, set_focus=False)
        menu = tk.Menu(self, tearoff=0)
        here = panel.current_path
        menu.add_command(label=f"Folder:  {os.path.basename(here) or here}",
                         state="disabled")
        menu.add_separator()
        sub = tk.Menu(menu, tearoff=0)
        self.build_folder_sort_menu(sub, here)
        menu.add_cascade(label="🔀  Sort override for this folder", menu=sub)
        menu.add_separator()
        menu.add_command(label="New folder", command=self.new_folder)
        menu.add_command(label="Refresh", command=self.refresh_panels)
        menu.add_command(label="Export path", command=self.export_path)
        try:
            menu.tk_popup(event.x_root, event.y_root)
        finally:
            menu.grab_release()

    def open_folder_sort_manager(self):
        FolderSortManagerWindow(self)

    def _is_previewable(self, path: str) -> bool:
        """Return True if the built-in viewer can render this type visually
        (image or PDF).  Used where a text fallback would be meaningless."""
        ext = os.path.splitext(path)[1].lower()
        return ext in _VIEWER_IMAGE_EXTS or ext in _VIEWER_PDF_EXTS

    def _reader_exts(self) -> set:
        """The user's comma-separated 'open in reader' extensions (Settings),
        as a set of lower-case '.ext' strings.  Default: .nfo and .txt."""
        raw = self.settings.get("reader_extensions", "nfo, txt") or ""
        out = set()
        for tok in raw.replace(";", ",").split(","):
            tok = tok.strip().lower()
            if not tok:
                continue
            out.add(tok if tok.startswith(".") else "." + tok)
        return out

    def _opens_in_reader(self, path: str) -> bool:
        """True when Enter / double-click on this file should open the BUILT-IN
        reader rather than the external program — i.e. its extension is in the
        user's reader list (Settings ▸ General ▸ Display).  F3 always uses the
        reader regardless; this only governs Enter / double-click."""
        ext = os.path.splitext(path)[1].lower()
        return ext in self._reader_exts()

    def _open_builtin_viewer(self, path: str):
        """Open the built-in viewer (text / PDF / image / audio)."""
        _BuiltinViewerWindow(self, path)

    def _open_file_activated(self, path: str, shift: bool = False,
                             ctrl: bool = False):
        """Open a FILE the way a double-click / Enter should, per the modifier:

          • plain  → the Windows default association (an archive browses into
                     it instead; a type in your reader-extensions list opens in
                     the built-in viewer).  Simple and predictable.
          • SHIFT  → the built-in viewer / player, whatever the type.
          • CTRL   → the per-type opener you set in Settings ▸ Custom openers;
                     if there is none for this type, the built-in viewer.

        Your F4 program is NOT used here — that stays on the F4 key, so a plain
        double-click can never fire an external program you didn't expect."""
        if shift:
            self._open_builtin_viewer(path)
            return
        if ctrl:
            ext    = os.path.splitext(path)[1].lower()
            custom = self.settings.get("custom_openers", {}) or {}
            if custom.get(ext):
                args = (self.settings.get("custom_opener_args", {}) or {}).get(ext, "")
                if self._launch_program(custom[ext], args, path,
                                        label="per-type opener"):
                    return
            self._open_builtin_viewer(path)
            return
        # Plain activation
        if is_archive(path):
            ArchiveBrowser(self, self, path)
            return
        if self._opens_in_reader(path):
            self._open_builtin_viewer(path)
            return
        # A PROGRAM is started, not opened (revBH).  This has to come before
        # DefaultHub: its "text" kind quite rightly lists .py, .bat and .ps1 —
        # those ARE text files, and every other program of his handing one over
        # should get the editor.  But Enter in a FILE MANAGER on a program
        # means run it.  Getting that wrong made his whole collection of .py
        # unstartable except through Tower.
        if (self.settings.get("activate_runs_programs", True)
                and _is_runnable(path)):
            if self._run_program(path):
                return
        # Two separate switches, and they are NOT the same promise:
        #
        #   activate_uses_openers (default OFF) — this program's own per-type
        #       openers and the F4 program.  Off keeps the old promise that a
        #       plain double-click can never fire an external program you had
        #       forgotten you set.
        #   activate_uses_hub (default ON, revBE) — DefaultHub's table, the
        #       one place he writes down which program owns a file type for
        #       the WHOLE tree.  That is not a forgotten setting, it is the
        #       written-down answer to "what opens a .jpg", so a plain Enter
        #       obeys it.  With it off, .jpg and .pdf did nothing at all: they
        #       fell through to a Windows association this machine has never
        #       had.  Shift+F4 / Ctrl+F4 are still the way out to Windows.
        self._open_local_file(
            path,
            use_overrides=bool(self.settings.get("activate_uses_openers",
                                                 False)),
            use_hub=bool(self.settings.get("activate_uses_hub", True)))

    def copy_files(self):
        self._ct("COPY-start")
        src = self.get_active_panel()
        dst = self.get_inactive_panel()

        # INTO an in-panel archive view → add the selection to the archive
        # (this used to fall through to dst.current_path, which for an archive
        # panel is the folder the archive sits in — the files landed beside it)
        if getattr(dst, "archive_ctx", None):
            self._copy_move_into_archive(src, dst, move=False)
            return

        # out of an in-panel archive view → extract the selection
        if getattr(src, "archive_ctx", None):
            self._copy_move_from_archive(src, dst, move=False)
            return

        # remote → local
        if getattr(src, "is_remote", False) and not getattr(dst, "is_remote", False):
            sel = src.get_selected()
            if not sel or sel[1]:
                messagebox.showinfo("Info", "Folder copy from FTP is not supported.")
                return
            target = self.choose_save_path(dst.current_path, os.path.basename(sel[0]))
            local  = os.path.join(target, os.path.basename(sel[0]))
            try:
                src.download_file(sel[0], local)
                self.refresh_panels()
            except Exception as exc:
                messagebox.showerror("FTP error", f"Download failed: {exc}")
            return

        # local → remote
        if not getattr(src, "is_remote", False) and getattr(dst, "is_remote", False):
            local_path = src.get_selected()
            if not local_path or os.path.isdir(local_path):
                messagebox.showinfo("Info", "Please upload a file, not a folder.")
                return
            try:
                dst.upload_file(local_path)
                self.refresh_panels()
            except Exception as exc:
                messagebox.showerror("FTP error", f"Upload failed: {exc}")
            return

        # local → local
        if not getattr(src, "is_remote", False) and not getattr(dst, "is_remote", False):
            sources = src.get_all_selected()
            if sources:
                self._copy_move_local(sources, dst.current_path, move=False)
                # Copy done — drop the red marks and leave a single clear cursor
                # (the files stay put, but they should not remain "marked").
                src._clear_marks_and_selection()
            return

        messagebox.showinfo("Info", "FTP→FTP copy is not supported in this version.")

    def move_files(self):
        src = self.get_active_panel()
        dst = self.get_inactive_panel()
        self._ct("MOVE-start", f"from={src.side} to={dst.side}")

        # INTO an in-panel archive view → add, then trash the originals
        if getattr(dst, "archive_ctx", None):
            self._copy_move_into_archive(src, dst, move=True)
            return

        # out of an in-panel archive view → extract, then remove from archive
        if getattr(src, "archive_ctx", None):
            self._copy_move_from_archive(src, dst, move=True)
            return

        # remote → local (download + delete)
        if getattr(src, "is_remote", False) and not getattr(dst, "is_remote", False):
            sel = src.get_selected()
            if not sel or sel[1]:
                messagebox.showinfo("Info", "Folder move from FTP is not supported.")
                return
            target = self.choose_save_path(dst.current_path, os.path.basename(sel[0]))
            local  = os.path.join(target, os.path.basename(sel[0]))
            try:
                src.download_file(sel[0], local)
                src.delete_path(sel[0], is_dir=False)
                self.refresh_panels()
            except Exception as exc:
                messagebox.showerror("FTP error", f"Move failed: {exc}")
            return

        # local → remote (upload + delete)
        if not getattr(src, "is_remote", False) and getattr(dst, "is_remote", False):
            lp = src.get_selected()
            if not lp or os.path.isdir(lp):
                messagebox.showinfo("Info", "Move is only supported for files, not folders.")
                return
            try:
                dst.upload_file(lp)
                os.remove(lp)
                self.refresh_panels()
            except Exception as exc:
                messagebox.showerror("FTP error", f"Move failed: {exc}")
            return

        # local → local
        if not getattr(src, "is_remote", False) and not getattr(dst, "is_remote", False):
            sources = src.get_all_selected()
            if not sources:
                return
            if len(sources) == 1 and os.path.dirname(sources[0]) == dst.current_path:
                self._rename_file_dialog(sources[0])
            else:
                self._copy_move_local(sources, dst.current_path, move=True)
                # The source files are committed to leaving — drop their red
                # marks and blue highlight now, so they don't linger as "still
                # selected" and can't be re-dragged once the move runs.
                if hasattr(src, "_clear_marks_and_selection"):
                    src._clear_marks_and_selection()
            return

        messagebox.showinfo("Info", "FTP→FTP move is not supported in this version.")

    def _copy_move_from_archive(self, src, dst, move: bool):
        """Copy (F5) or Move (F6) the marked selection OUT of an in-panel
        archive view and into the other panel's real folder."""
        if getattr(dst, "is_remote", False):
            messagebox.showinfo(
                "Info",
                "Copying straight out of an archive to FTP isn't supported — "
                "copy to a local folder first, then upload.")
            return
        names = src.archive_selected_inner_names()
        if not names:
            return
        ctx = src.archive_ctx
        dest_dir = dst.current_path
        # Revision CF: extract into a hidden staging folder INSIDE the
        # destination and let the ordinary queue move it up from there, so a
        # name clash is asked about / backed up like every other copy.
        stage = os.path.join(
            dest_dir, f".fm-from-archive-{os.getpid()}-{int(_time.time())}")
        verb = "Extracting"
        dlg = _ProgressDialog(
            self, f"{verb} from {os.path.basename(ctx['archive_path'])}",
            total=len(names))
        cancelled = {"v": False}

        def on_progress(i, total, name):
            if dlg.cancelled:
                cancelled["v"] = True
                return False
            dlg.post("progress", i, total, name)
            return True

        def worker():
            try:
                # strip_prefix = the folder INSIDE the archive we are standing
                # in.  Without it, marking a file while inside "Icons/" put
                # <dest>\Icons\<file> at the destination — the sub-folder came
                # along on its own.  Marking the FOLDER (from outside it) is
                # how you ask for the folder.
                os.makedirs(stage, exist_ok=True)
                archive_extract_members(ctx["archive_path"], stage, names,
                                        progress=on_progress,
                                        strip_prefix=ctx.get("subpath", ""))
                self.after(0, lambda: self._archive_staged(
                    dlg, src, dst, move, ctx, names, stage))
            except Exception as exc:
                shutil.rmtree(stage, ignore_errors=True)
                self.after(0, lambda e=exc: self._archive_copy_failed(dlg, e))

        threading.Thread(target=worker, daemon=True).start()

    def _archive_staged(self, dlg, src, dst, move: bool, ctx, names, stage):
        """Main thread: the members are extracted into *stage* - queue the real
        transfer (a MOVE out of the staging folder) and arrange the follow-up."""
        dlg.post("done")
        try:
            items = [os.path.join(stage, n) for n in sorted(os.listdir(stage))]
        except OSError:
            items = []
        if not items:
            shutil.rmtree(stage, ignore_errors=True)
            messagebox.showinfo("Archive", "Nothing was extracted.", parent=self)
            return
        archive_path = ctx["archive_path"]
        prefix = _norm_member(ctx.get("subpath", "")).strip("/")

        def rel_of(n):
            n = _norm_member(n).strip("/")
            if prefix and n.startswith(prefix + "/"):
                n = n[len(prefix) + 1:]
            return n

        def staged_files():
            out = set()
            for dp, _dn, fns in os.walk(stage):
                for fn in fns:
                    out.add(os.path.relpath(os.path.join(dp, fn), stage)
                            .replace("\\", "/"))
            return out

        before = staged_files()

        def finished(task):
            # Worker thread, the job is over (done, skipped, failed or cancelled).
            try:
                if move:
                    after = staged_files()
                    delivered = before - after
                    kill = []
                    for n in names:
                        rel = rel_of(n)
                        top = os.path.join(stage, *rel.split("/"))
                        if not os.path.exists(top):
                            kill.append(n)          # all of it arrived
                        elif os.path.isdir(top):
                            kill.extend(
                                (prefix + "/" if prefix else "") + r
                                for r in delivered if r.startswith(rel + "/"))
                    if kill:
                        archive_delete_members(archive_path, kill)
            except Exception as exc:
                _log(f"Archive move: could not remove delivered members: {exc}")
            finally:
                shutil.rmtree(stage, ignore_errors=True)

            def refresh():
                self.refresh_panels()
                if move and src.archive_ctx is not None:
                    try:
                        src.archive_ctx["entries"] = archive_list(archive_path)
                    except ArchiveError:
                        src.exit_archive()
                        return
                    src._refresh_archive_view()
            _ui_call(self, refresh)

        task = self.task_queue_mgr.add_copy_move(items, dst.current_path, True,
                                                 conflict_mode="ask")
        task.description = (f"\U0001F4E6 {os.path.basename(archive_path)}  \u25B8  "
                            + task.description)
        task.on_finished = finished
        self._after_task_enqueued("Move queued" if move else "Copy queued",
                                  has_conflict=False)
        if hasattr(src, "_clear_marks_and_selection"):
            src._clear_marks_and_selection()

    def _archive_copy_done(self, dlg, src, dst, move: bool, was_cancelled: bool):
        dlg.post("done")
        self.refresh_panels()
        if move and src.archive_ctx is not None:
            try:
                src.archive_ctx["entries"] = archive_list(src.archive_ctx["archive_path"])
            except ArchiveError:
                # The archive is gone or unreadable now — just step back out.
                src.exit_archive()
                return
            src._refresh_archive_view()
        if hasattr(src, "_clear_marks_and_selection"):
            src._clear_marks_and_selection()
        if not was_cancelled:
            _flash_ok(self, f"{'Moved' if move else 'Copied'} to\n{dst.current_path}",
                      "Move" if move else "Copy")

    def _archive_copy_failed(self, dlg, exc):
        dlg.post("done")
        _archive_error_box(self, exc)

    # ── Copy / Move INTO an archive shown in a panel (rev CA) ─────────────
    #
    # The other direction (out of an archive) has always worked; INTO one did
    # not exist, so F5 / F6 / drag / Ctrl+V on a panel that was standing inside
    # a zip quietly used the folder the zip sits in as the target.  Now the
    # files are written into the archive itself, at the folder you are
    # standing in.  Only formats this program can also CREATE are writable
    # (PACK_FORMATS); RAR / ISO / CAB say so and nothing is copied anywhere.

    def _copy_move_into_archive(self, src, dst, move: bool):
        """F5 / F6 when the INACTIVE panel is browsing an archive."""
        if getattr(src, "is_remote", False):
            messagebox.showinfo(
                "Info",
                "Copying from FTP straight into an archive isn't supported — "
                "download to a local folder first.", parent=self)
            return
        if getattr(src, "archive_ctx", None):
            messagebox.showinfo(
                "Archive",
                "Both panels are inside archives.\n\nCopy out to a real folder "
                "first (F5), then into the other archive.", parent=self)
            return
        sources = src.get_all_selected()
        if not sources:
            return
        if self._add_to_archive(dst, sources, move):
            src._clear_marks_and_selection()

    def _add_to_archive(self, dst, paths, move: bool = False) -> bool:
        """Write *paths* (files / folders on disk) into the archive that panel
        *dst* is browsing, at the folder it is standing in.  Returns True when
        a job was started.  Shared by F5 / F6, drag & drop and Ctrl+V."""
        ctx = dst.archive_ctx
        if ctx is None:
            return False
        apath    = ctx["archive_path"]
        arc_name = os.path.basename(apath)
        fmt      = ctx.get("fmt", "")
        if fmt not in PACK_FORMATS:
            messagebox.showinfo(
                "Archive",
                f"{fmt.upper()} archives are read-only here — files can be "
                "copied OUT of them, but not added to them.\n\n"
                "Nothing was copied.", parent=self)
            return False
        me = os.path.normcase(os.path.abspath(apath))
        paths = [p for p in paths
                 if p and os.path.basename(p) != ".." and os.path.exists(p)
                 and os.path.normcase(os.path.abspath(p)) != me]
        if not paths:
            return False
        sub   = ctx.get("subpath", "")
        plans = {p: archive_add_plan([p], sub) for p in paths}
        plan  = [item for p in paths for item in plans[p]]
        if not plan:
            self._flash_status("Nothing to add — the selection holds no files.")
            return False

        existing = {_norm_member(e.name) for e in ctx["entries"] if not e.is_dir}
        clash    = sorted({a for _f, a, d in plan if not d and a in existing})
        skip     = set()
        if clash:
            shown = "\n".join("  " + c for c in clash[:8])
            more  = f"\n  … and {len(clash) - 8} more" if len(clash) > 8 else ""
            ans = messagebox.askyesnocancel(
                "Archive",
                f"{len(clash)} file(s) already exist in {arc_name}:\n\n"
                f"{shown}{more}\n\n"
                "Yes = replace them\nNo = skip them\nCancel = add nothing",
                parent=self)
            if ans is None:
                return False
            if ans is False:
                skip = set(clash)
        if skip:
            plan = [item for item in plan if item[1] not in skip]
            if not plan:
                return False
        # A move only removes an original that went in WHOLE.
        removable = ([p for p in paths
                      if not any(a in skip for _f, a, _d in plans[p])]
                     if move else [])

        dlg = _ProgressDialog(
            self, f"{'Moving' if move else 'Copying'} into {arc_name}",
            total=len(plan))
        cancelled = {"v": False}

        def on_progress(i, total, name):
            if dlg.cancelled:
                cancelled["v"] = True
                return False
            dlg.post("progress", i, total, name)
            return True

        def worker():
            try:
                archive_add_members(apath, plan, progress=on_progress)
                self.after(0, lambda: self._add_to_archive_done(
                    dlg, dst, ctx, removable, move, False))
            except Exception as exc:
                if cancelled["v"]:
                    self.after(0, lambda: self._add_to_archive_done(
                        dlg, dst, ctx, [], move, True))
                else:
                    self.after(0, lambda e=exc: self._archive_copy_failed(dlg, e))

        threading.Thread(target=worker, daemon=True).start()
        return True

    def _add_to_archive_done(self, dlg, dst, ctx, removable, move: bool,
                             was_cancelled: bool):
        dlg.post("done")
        if removable and not was_cancelled:
            self.move_to_trash(removable)
        try:
            ctx["entries"] = archive_list(ctx["archive_path"])
        except ArchiveError:
            if dst.archive_ctx is ctx:
                dst.exit_archive()
            return
        self.refresh_panels()
        if dst.archive_ctx is ctx:
            dst._refresh_archive_view()
        if not was_cancelled:
            _flash_ok(self,
                      f"{'Moved' if move else 'Copied'} into\n"
                      f"{os.path.basename(ctx['archive_path'])}",
                      "Move" if move else "Copy")

    # ══ Copy As / Move As (Shift+F5 / Shift+F6) ═════════════════════════
    # Like plain Copy/Move, but you get to type the destination first — a full
    # target path (with a new name) for a single item, or a target folder for a
    # multi-selection.

    def copy_files_as(self):
        """Shift+F5 — copy the selection to a destination you type."""
        self._copy_move_as(move=False)

    def move_files_as(self):
        """Shift+F6 — move the selection to a destination you type."""
        self._copy_move_as(move=True)

    def _copy_move_as(self, move: bool):
        verb = "Move" if move else "Copy"
        src  = self.get_active_panel()
        if getattr(src, "is_remote", False):
            messagebox.showinfo(verb + " As", f"{verb} As is not available for FTP panels.")
            return
        sources = src.get_all_selected()
        if not sources:
            return
        dst      = self.get_inactive_panel()
        dst_dir  = (dst.current_path if not getattr(dst, "is_remote", False)
                    else src.current_path)

        if len(sources) == 1:
            default_target = os.path.join(dst_dir, os.path.basename(sources[0]))
            new_path = self._ask_target_path(
                f"{verb} As", f"{verb} to (full path + name):", default_target)
            if not new_path:
                return
            self._do_single_copy_move_as(sources[0], new_path, move)
        else:
            folder = self._ask_target_path(
                f"{verb} As — folder",
                f"{verb} {len(sources)} items into this folder:",
                dst_dir, pick_folder=True)
            if not folder:
                return
            self._copy_move_local(sources, folder, move=move)
            src._clear_marks_and_selection()

    def _ask_target_path(self, title: str, prompt: str, initial: str,
                         pick_folder: bool = False) -> "str | None":
        """Small modal dialog: an editable path field (Enter = OK, Esc = Cancel)
        and a browse button.  Returns the typed path, or None on cancel."""
        top = tk.Toplevel(self)
        top.configure(bg=C_BG)
        top.resizable(True, False)
        result = {"path": None}

        wrap = tk.Frame(top, bg=C_BG, padx=14, pady=12)
        wrap.pack(fill="both", expand=True)
        tk.Label(wrap, text=prompt, bg=C_BG, fg=C_FG,
                 font=("Segoe UI", 10)).pack(anchor="w")

        row = tk.Frame(wrap, bg=C_BG)
        row.pack(fill="x", pady=(6, 10))
        var = tk.StringVar(value=initial)
        ent = tk.Entry(row, textvariable=var, width=60,
                       insertofftime=0, insertontime=9999999)
        ent.pack(side="left", fill="x", expand=True)

        def _browse():
            if pick_folder:
                d = filedialog.askdirectory(parent=top, title=title,
                                            initialdir=initial)
                if d:
                    var.set(d)
            else:
                d = filedialog.asksaveasfilename(
                    parent=top, title=title,
                    initialdir=os.path.dirname(initial),
                    initialfile=os.path.basename(initial))
                if d:
                    var.set(d)

        tk.Button(row, text="…", width=3, command=_browse,
                  bg=C_BG3, fg=C_FG, relief="flat").pack(side="left", padx=(4, 0))

        def _ok(_e=None):
            result["path"] = var.get().strip()
            top.destroy()

        btns = tk.Frame(wrap, bg=C_BG)
        btns.pack(fill="x")
        # normal button colour: green / grey (change to taste)
        tk.Button(btns, text="OK", width=10, command=_ok,
                  bg="green", fg="white", relief="flat").pack(side="left")
        tk.Button(btns, text="Cancel", width=10, command=top.destroy,
                  bg="grey", fg="white", relief="flat").pack(side="right")

        # House rules: grab_set, focus_force, Escape — in that order.
        top.title(title)
        top.transient(self.winfo_toplevel())
        top.grab_set()
        top.focus_force()
        top.bind("<Escape>", lambda e: top.destroy())
        top.bind("<Return>", _ok)
        ent.focus_set()
        ent.selection_range(0, tk.END)
        top.wait_window()
        return result["path"] or None

    def _do_single_copy_move_as(self, src_path: str, new_path: str, move: bool):
        verb = "Move" if move else "Copy"
        new_path = os.path.abspath(new_path)
        target_dir = os.path.dirname(new_path)
        if not target_dir or not os.path.basename(new_path):
            messagebox.showerror(verb + " As", "Please give a full destination path and name.")
            return
        if (os.path.normcase(os.path.abspath(src_path))
                == os.path.normcase(new_path)):
            return   # same file — nothing to do
        try:
            os.makedirs(target_dir, exist_ok=True)
        except Exception as exc:
            messagebox.showerror(verb + " As", f"Could not create folder:\n{exc}")
            return
        if os.path.exists(new_path):
            if not _ask_yes_no(
                    verb + " As — overwrite?",
                    f"{new_path}\n\nalready exists.  Overwrite it?"):
                return
            try:
                if os.path.isdir(new_path) and not os.path.islink(new_path):
                    shutil.rmtree(new_path)
                else:
                    os.remove(new_path)
            except Exception as exc:
                messagebox.showerror(verb + " As", f"Could not replace it:\n{exc}")
                return
        try:
            if os.path.isdir(src_path):
                shutil.move(src_path, new_path) if move else shutil.copytree(src_path, new_path)
            else:
                shutil.move(src_path, new_path) if move else shutil.copy2(src_path, new_path)
        except Exception as exc:
            messagebox.showerror(verb + " As", f"{verb} failed:\n{exc}")
            return
        self.refresh_panels()
        try:
            self.get_active_panel()._clear_marks_and_selection()
        except Exception:
            pass
        self._flash_status(f"{verb} As → {new_path}")

    def _rename_selected(self):
        """Trigger inline rename on the active panel's selected item."""
        panel = self.get_active_panel()
        if getattr(panel, "archive_ctx", None):
            messagebox.showinfo("Archive",
                                "Renaming isn't supported inside an archive view.")
            return
        sel   = panel.tree.selection()
        if sel:
            text = panel.tree.item(sel[0], "text")
            if text != "..":
                panel.start_rename(sel[0])

    def _rename_ext_selected(self):
        """Shift+F2 — inline rename of the EXTENSION of the selected file.

        F2 has always opened the NAME box, and the extension had no keyboard
        route whatsoever: the only way in was a 650 ms slow click on the Type
        column.  Same key plus Shift opens the other half, and TAB inside
        either box crosses over to the other one (revBM)."""
        panel = self.get_active_panel()
        if getattr(panel, "archive_ctx", None):
            messagebox.showinfo("Archive",
                                "Renaming isn't supported inside an archive view.")
            return
        sel = panel.tree.selection()
        if not sel:
            return
        if panel.tree.item(sel[0], "text") == "..":
            return
        if panel.tree.set(sel[0], "type") == "Folder":
            self._flash_status("A folder has no extension — F2 renames it.")
            return
        panel.start_rename_type(sel[0])

    def set_dates_now(self):
        """Stamp every selected file and folder with the CURRENT date and time.

        Nothing in this program moves a file's date behind your back.  A move
        on the same drive is a rename on disk and cannot touch it; a move
        across drives copies the file and re-applies the source's stamp; a
        copy keeps the date too unless Settings ▸ Dates says otherwise.  So
        when the date SHOULD read "now", it has to be asked for — and this is
        the asking.  It cannot be undone, which is why it asks first (revBM).
        """
        panel = self.get_active_panel()
        if getattr(panel, "is_remote", False):
            messagebox.showinfo("Info", "Dates can only be set on local files.")
            return
        targets = panel.get_all_selected()
        if not targets:
            return

        n_dirs = sum(1 for p in targets if os.path.isdir(p))
        what   = (os.path.basename(targets[0]) if len(targets) == 1
                  else f"{len(targets) - n_dirs} file(s) and {n_dirs} folder(s)")
        stamp  = datetime.now()
        if not _ask_yes_no(
                "Set date and time to NOW",
                f"{what}\n\nSet the modified date to\n"
                f"{stamp:%Y-%m-%d %H:%M:%S}?\n\n"
                "The old dates are gone for good — this cannot be undone.",
                parent=self, default_yes=False):
            return

        ts = stamp.timestamp()
        done, failed = 0, []
        for path in targets:
            try:
                os.utime(path, (ts, ts))
                done += 1
            except Exception as exc:
                failed.append(f"{os.path.basename(path)}: {exc}")
        self.refresh_panels()
        if failed:
            messagebox.showerror(
                "Set date and time to NOW",
                f"Stamped {done} item(s).\n\nFailed:\n" + "\n".join(failed[:12]),
                parent=self)
        else:
            _flash_ok(self, f"Stamped {done} item(s) with {stamp:%H:%M:%S}.",
                      "Date set to now")

    def rename_path(self, old_path: str, new_name: str, *, parent=None):
        """Rename *old_path* to *new_name* in the same folder.

        When the target name is already taken by ANOTHER file/folder, this shows
        the same "file already exists" dialog as copy/move — so you can Overwrite
        old, Backup-rename old (keep it as Backup<code>-…), Rename new (add a
        (2) suffix), or Skip — instead of just failing with "Could not rename".
        Records undo, remaps tags.  Returns the final path, or None if nothing
        happened (cancelled / skipped / error)."""
        parent   = parent or self
        new_name = (new_name or "").strip()
        old_name = os.path.basename(old_path)
        if not new_name or new_name == old_name:
            return None
        folder   = os.path.dirname(old_path)
        new_path = os.path.join(folder, new_name)

        # A case-only change on Windows (report.txt → Report.txt) is the SAME
        # file — os.path.exists() would say "taken", so allow it straight through.
        same_file = (os.path.normcase(os.path.abspath(new_path)) ==
                     os.path.normcase(os.path.abspath(old_path)))

        # If the name is "taken" only by a file you already deleted (marked,
        # hidden, still on disk), free it silently instead of nagging.
        if os.path.exists(new_path) and not same_file:
            self._clear_pending_if_deleted(new_path)

        if os.path.exists(new_path) and not same_file:
            dlg = _ConflictDlg(parent, old_path, new_path)
            parent.wait_window(dlg)
            action = dlg.action
            if action in (_ConflictDlg.CANCEL, _ConflictDlg.SKIP,
                          _ConflictDlg.SKIP_ALL):
                return None
            if action in (_ConflictDlg.AUTO_RENAME,):
                new_path = _auto_rename_path(new_path)          # the NEW file gets a (2)
            elif action in (_ConflictDlg.BACKUP_OLD, _ConflictDlg.BACKUP_OLD_ALL):
                if not self.task_queue_mgr._backup_existing(new_path):
                    # backup failed → fall back to overwriting the old file
                    try:
                        if os.path.isdir(new_path): shutil.rmtree(new_path)
                        else:                       os.remove(new_path)
                    except Exception as exc:
                        messagebox.showerror(
                            "Rename", f"Could not replace the existing file:\n{exc}",
                            parent=parent)
                        return None
            else:   # OVERWRITE / OVERWRITE_ALL — destroy the existing file
                try:
                    if os.path.isdir(new_path): shutil.rmtree(new_path)
                    else:                       os.remove(new_path)
                except Exception as exc:
                    messagebox.showerror(
                        "Rename", f"Could not replace the existing file:\n{exc}",
                        parent=parent)
                    return None

        try:
            os.rename(old_path, new_path)
        except Exception as exc:
            messagebox.showerror("Rename", f"Could not rename:\n{exc}", parent=parent)
            return None

        self.oplog.record("rename", [{"src": old_path, "dst": new_path}],
                          note=f"{old_name} → {os.path.basename(new_path)}")
        self.tagstore.remap([(old_path, new_path)])
        return new_path

    def _rename_file_dialog(self, path):
        basename = os.path.basename(path)
        new_name = _ask_text(self, "Rename", "New name:", initial=basename)
        if new_name and new_name != basename:
            final = self.rename_path(path, new_name)
            if final:
                # _refresh_and_refocus, not refresh_panels: the name box (and
                # any clash dialog behind it) held the keyboard, so the arrow
                # keys would otherwise stay dead until TAB TAB.
                self._refresh_and_refocus()
                panel = self.get_active_panel()
                if hasattr(panel, "_focus_row_by_name"):
                    panel._focus_row_by_name(os.path.basename(final))

    # ══ DEL 04c — "(2) suffix" twins ════════════════════════════════════
    # A file saved twice by the browser comes out as  Notes (2).py ,  Notes
    # (3).py … .  Copying one of those into the folder that already holds
    # Notes.py is not a name clash, so nothing used to stop and ask — and the
    # folder filled up with numbered near-duplicates.  These three methods are
    # the "same file, one (2) apart" answer to that.

    def _ask_suffix_twins(self, task):
        """Ask once per job what the "(2)" copies should be called.

        Called from the queue's preflight, which is HOLDING the job until this
        is answered — so every path out of here must end in a policy being
        applied (release_preflight), including the window being closed."""
        twins = list(getattr(task, "twins", []) or [])
        if not twins:
            self.task_queue_mgr.release_preflight(task)
            return
        src_dir = os.path.dirname(twins[0]["src"])
        dst_dir = task.dest_dir
        remembered = _match_twin_rule(src_dir, dst_dir)
        if remembered:
            self._apply_twin_policy(task, remembered, remembered_rule=True)
            return
        _SuffixTwinDlg(
            self, twins, src_dir, dst_dir,
            move=(task.task_type == TaskType.MOVE),
            on_done=lambda choice, always: self._twin_answer(
                task, choice, always, src_dir, dst_dir))

    def _twin_answer(self, task, choice: str, always: bool,
                     src_dir: str, dst_dir: str):
        if always and choice:
            _remember_twin_rule(src_dir, dst_dir, choice)
            self._flash_status(
                f"Remembered: {src_dir} → {dst_dir} …   "
                f"(TOOLS ▾ ▸ “(2)-suffix answers…” to undo)")
        self._apply_twin_policy(task, choice)

    def _apply_twin_policy(self, task, policy: str, remembered_rule: bool = False):
        """Fold the answer into the task, then let the queue run it."""
        twins = list(getattr(task, "twins", []) or [])
        n = len(twins)
        if policy in (_SuffixTwinDlg.BACKUP, _SuffixTwinDlg.OVER) and twins:
            for t in twins:
                try:
                    key = os.path.normcase(os.path.abspath(t["src"]))
                except Exception:
                    key = t["src"]
                task.rename_map[key] = t["base"]
            # Renaming them ON ARRIVAL turns each one into a real clash with
            # the file already there — which is the point.  The whole task
            # carries the policy, and it can only affect these files: a job
            # with any OTHER clash never gets this question (it is parked
            # instead), so there is nothing else here left to overwrite.
            task.conflict_mode = ("backup_old"
                                  if policy == _SuffixTwinDlg.BACKUP
                                  else "overwrite_all")
            what = ("old one kept as Backup…"
                    if policy == _SuffixTwinDlg.BACKUP else "old one replaced")
            self._flash_status(
                f"{n} file{'s' if n != 1 else ''} will land under the plain "
                f"name  ·  {what}"
                + ("   (remembered rule)" if remembered_rule else ""))
        task.twins = []
        self.task_queue_mgr.release_preflight(task)

    def open_twin_rules(self):
        """TOOLS ▾ — the remembered "always do this" answers, with a way out."""
        TwinRulesWindow(self)

    # ══ DEL 50 — Relocator ══════════════════════════════════════════════

    def open_relocator(self):
        """⤴ left-click — the rules, with how many files each would move."""
        RelocatorPopup(self, anchor=getattr(self, "_relocator_btn", None))

    def open_relocator_rules(self, new_rule: dict = None):
        RelocatorRulesWindow(self, new_rule=new_rule)

    def _relocator_queued(self, on_queued):
        """Tell the chain runner this rule has handed over everything it will.

        Called on EVERY way out of run_relocator_rule, including the ones that
        queue nothing at all — a chain that is waiting for a callback that
        never comes is a chain that stops dead on the first rule with a typo in
        its destination."""
        if on_queued is None:
            return
        try:
            on_queued()
        except Exception as exc:
            _log(f"Relocator: chain callback failed: {exc}")

    def run_relocator_rule(self, rule: dict, files: list = None,
                           quiet: bool = False, collect: list = None,
                           on_queued=None) -> int:
        """Queue what one rule wants moved.  Returns how many files that was.

        *collect* and *on_queued* are what let "Run all" run the rules one
        after another: every Task Queue job this rule creates is appended to
        *collect*, and *on_queued* is called once nothing more is coming — for
        a RETIRE rule that is only after the old copies have been carried out
        of the way, seconds later and on another thread.  The chain runner then
        waits for those jobs to FINISH before it so much as looks at the next
        rule.
        """
        active_dir = getattr(self.get_active_panel(), "current_path", "")
        if files is None:
            try:
                files = _relocator_scan(rule, active_dir)
            except Exception as exc:
                _log(f"Relocator: scan failed for {rule.get('name','')}: {exc}")
                files = []
        if not files:
            if not quiet:
                self._flash_status(
                    f"Relocator: nothing matches “{rule.get('name','')}” "
                    f"right now.")
            self._relocator_queued(on_queued)
            return 0
        dest = (rule.get("dest") or "").strip()
        if not dest:
            self._relocator_queued(on_queued)
            return 0
        try:
            os.makedirs(dest, exist_ok=True)
        except Exception as exc:
            messagebox.showerror(
                "Relocator",
                f"Could not create the destination folder:\n{dest}\n\n{exc}",
                parent=self)
            self._relocator_queued(on_queued)
            return 0

        # A "newer than the copy over there" rule can RETIRE what it replaces:
        # the old file is renamed Backup<code>- and moved to a third folder
        # BEFORE the new one lands.  That order is not a detail — it is the
        # only one that leaves a good copy at every instant, and the only one
        # that works on a program that is running (Windows lets a busy .exe be
        # renamed, never overwritten).
        if (rule.get("kind") == "newer"
                and (rule.get("retire_dir") or "").strip()):
            return self._relocator_retire_then_copy(rule, files, quiet,
                                                    collect, on_queued)

        return self._relocator_enqueue(rule, files, quiet, collect, on_queued)

    def _relocator_enqueue(self, rule: dict, files: list, quiet: bool,
                           collect: list = None, on_queued=None) -> int:
        """Hand one rule's files to the Task Queue."""
        if not files:
            self._relocator_queued(on_queued)
            return 0
        dest = (rule.get("dest") or "").strip()
        rename_map = {}
        if rule.get("strip_suffix"):
            for f in files:
                base = _strip_copy_suffix(os.path.basename(f))
                if base != os.path.basename(f):
                    try:
                        rename_map[os.path.normcase(os.path.abspath(f))] = base
                    except Exception:
                        pass
        # skip_twin_check: the rule has already said what happens to a "(2)"
        # name, so the queue must not stop and ask the same thing again.
        task = self.task_queue_mgr.add_copy_move(
            list(files), dest,
            move=(rule.get("action", "move") != "copy"),
            conflict_mode=(rule.get("conflict") or "backup_old"),
            rename_map=rename_map, skip_twin_check=True,
            reloc=True)
        if collect is not None and task is not None:
            collect.append(task)
        self._relocator_queued(on_queued)
        if not quiet:
            verb = "Moving" if rule.get("action", "move") != "copy" else "Copying"
            self._after_task_enqueued(
                f"Relocator · {verb.lower()} {len(files)} file(s) → {dest}")
        return len(files)

    def _relocator_retire_then_copy(self, rule: dict, files: list,
                                    quiet: bool, collect: list = None,
                                    on_queued=None) -> int:
        """Move each about-to-be-replaced file out of the way, then copy.

        The Backup<code>- names are worked out HERE, on the main thread, so the
        shared code pool (backup_codes.json) is only ever written from one
        place.  The moves themselves run in a worker thread — same volume they
        are instant renames, a different volume and it is a real copy nobody
        wants to sit and watch.  Only when they are done is the copy queued,
        which is what guarantees the order; two separate queue tasks could be
        re-ordered by the queue itself (or overtaken by the fast lane).
        """
        dest   = (rule.get("dest") or "").strip()
        retire = (rule.get("retire_dir") or "").strip()
        try:
            os.makedirs(retire, exist_ok=True)
        except Exception as exc:
            messagebox.showerror(
                "Relocator",
                f"Could not create the retire folder:\n{retire}\n\n{exc}",
                parent=self)
            self._relocator_queued(on_queued)
            return 0

        plan  = []          # [(old path, its Backup name in the retire folder)]
        codes = self._load_backup_codes()
        for src in files:
            name = os.path.basename(src)
            old  = os.path.join(dest, name)
            if not os.path.isfile(old):
                continue                     # nothing over there to retire
            key  = self._backup_base_key(name)
            code = self._next_backup_code(set(codes.get(key, [])))
            codes.setdefault(key, [])
            codes[key].append(code)
            plan.append((old, os.path.join(retire, f"Backup{code}-{key}"), src))
        if plan:
            self._save_backup_codes(codes)
        else:
            return self._relocator_enqueue(rule, files, quiet,
                                           collect, on_queued)

        if not quiet:
            self._flash_status(
                f"Relocator · retiring {len(plan)} old file(s) to {retire} …")

        def _worker():
            moved, failed = [], []
            for old, new, src in plan:
                try:
                    if os.path.exists(new):
                        new = _auto_rename_path(new)
                    shutil.move(old, new)
                    moved.append((old, new, src))
                except Exception as exc:
                    reason = (_friendly_oserror(exc) if isinstance(exc, OSError)
                              else str(exc))
                    failed.append((old, reason, src))
                    _log(f"Relocator: could not retire {old}: {exc}")
            _ui_call(self, lambda: self._relocator_retired(
                rule, list(files), moved, failed, quiet, collect, on_queued))

        threading.Thread(target=_worker, daemon=True).start()
        return len(files)

    def _relocator_retired(self, rule: dict, files: list, moved: list,
                           failed: list, quiet: bool, collect: list = None,
                           on_queued=None):
        """The old copies are out of the way — now queue the new ones."""
        if moved:
            try:
                self.oplog.record(
                    "move", [{"src": o, "dst": n} for o, n, _s in moved],
                    note=f"Relocator retired {len(moved)} file(s) to "
                         f"{rule.get('retire_dir','')}")
            except Exception as exc:
                _log(f"Relocator: could not write the undo log: {exc}")
            try:
                self.tagstore.remap([(o, n) for o, n, _s in moved])
            except Exception:
                pass

        # A file whose old copy could NOT be moved aside is left alone: better
        # one program not updated than one good copy quietly written over.
        blocked = {s for _o, _r, s in failed}
        keep    = [f for f in files if f not in blocked]
        self._relocator_enqueue(rule, keep, quiet, collect, on_queued)
        self.refresh_panels()

        if failed:
            lines = "\n".join(f"·  {os.path.basename(o)} — {r}"
                               for o, r, _s in failed[:12])
            if len(failed) > 12:
                lines += f"\n·  … and {len(failed) - 12} more"
            messagebox.showwarning(
                "Relocator",
                f"{len(failed)} old file(s) could not be moved aside, so their "
                f"replacements were NOT copied:\n\n{lines}\n\n"
                f"{len(keep)} other file(s) are on their way.",
                parent=self)
        elif not quiet and moved:
            self._flash_status(
                f"Relocator · {len(moved)} old file(s) retired to "
                f"{rule.get('retire_dir','')}, {len(keep)} on the way")

    def run_relocator_all(self, event=None):
        """⤴ right-click — every enabled rule, IN ORDER, one at a time.

        The scan happens in a thread: a rule can point at a network folder, and
        counting up a slow share is exactly the kind of thing that must never
        happen on the UI thread.  What comes back is only the OPENING picture —
        it is what the confirmation shows, and what a rule may still use as
        long as no rule before it has changed anything."""
        if getattr(self, "_reloc_chain", None):
            # One chain at a time: a second one would race the first through
            # the same folders.  Show the one that is going instead.
            win = self._reloc_chain.get("win")
            if win is not None and win.winfo_exists():
                win.present()
            else:
                self._flash_status(
                    "Relocator: already running — the rules are going through "
                    "one at a time.")
            return "break"
        rules = [r for r in _load_relocator_rules() if r.get("enabled", True)]
        if not rules:
            self._flash_status(
                "Relocator: no rules yet — left-click ⤴ to make one.")
            self.open_relocator()
            return "break"
        active_dir = getattr(self.get_active_panel(), "current_path", "")
        self._flash_status("Relocator: looking through the folders…")

        def _worker():
            found = []
            for r in rules:
                try:
                    found.append((r, _relocator_scan(r, active_dir)))
                except Exception as exc:
                    _log(f"Relocator: scan failed for {r.get('name','')}: {exc}")
                    found.append((r, []))
            _ui_call(self, lambda: self._relocator_all_scanned(found))

        threading.Thread(target=_worker, daemon=True).start()
        return "break"

    def _relocator_all_scanned(self, found: list):
        total = sum(len(f) for _r, f in found)
        if not total:
            # Every rule empty means nothing can change, so no rule can pick up
            # after another either — this really is the end of it.
            self._flash_status(
                "Relocator: nothing to move — every rule came back empty.")
            return
        if self.settings.get("relocator_confirm", True):
            lines = []
            for i, (r, f) in enumerate(found[:14], 1):
                what = f"{len(f)} file(s)" if f else "nothing yet"
                lines.append(f"{i:>2}.  {r.get('name') or '(rule)'}  —  {what}"
                             f"  →  {r.get('dest','')}")
            if len(found) > 14:
                lines.append(f"      …  and {len(found) - 14} more rule(s)")
            if not _ask_yes_no(
                    "Relocator",
                    f"Run {len(found)} rule(s), one after another, in this "
                    f"order?\n\n" + "\n".join(lines)
                    + "\n\nEach rule waits for the one before it to FINISH, so "
                      "a rule can pick up what the rule before it delivered — "
                      "a “nothing yet” may well not stay that way.\n\n"
                      "(Untick “Ask before running everything” in the ⤴ popup "
                      "to skip this question.)",
                    parent=self):
                return
        self._reloc_chain_start(found)

    # ── "Run all": the rules in order, one at a time ──────────────────────
    #
    # WHY A CHAIN AND NOT A LOOP.  The rules are meant to hand work to each
    # other —  dist → Exe-redo → 1---Blandat.  A loop that scans everything up
    # front and queues the lot shows every rule the folders as they were BEFORE
    # any rule ran, so the second link of the chain always looks into an empty
    # folder and the whole thing has to be done by hand, one rule at a time.
    #
    # Here each rule is started, the Task Queue is allowed to FINISH it, and
    # only then is the next rule looked at.  It is a chain of after() calls and
    # never a wait loop: the UI thread has to stay free, because the very queue
    # being waited for runs its progress — and its questions — on it.
    #
    # "dirty" is the small economy the whole thing turns on: a rule is only
    # re-scanned when a rule before it actually MOVED something.  Until then
    # the count taken at the start still stands, and no folder is read twice
    # for nothing.

    def _reloc_chain_start(self, found: list):
        if getattr(self, "_reloc_chain", None):
            return
        self._reloc_chain = {
            "rules": list(found),    # [(rule, the files it wanted a moment ago)]
            "i":     0,
            "dirty": False,          # has a rule before this one moved anything?
            "moved": 0,
            "stop":  False,
            "warn":  False,          # did any rule fail / get cancelled?
            "win":   None,
        }
        try:
            self._reloc_chain["win"] = RelocatorRunWindow(self, found)
        except Exception as exc:
            _log(f"Relocator: could not open the run window: {exc}")
        self._after_task_enqueued(
            f"Relocator · running {len(found)} rule(s), one at a time")
        self._reloc_chain_step()

    def _reloc_chain_row(self, idx: int, text: str, colour: str = None):
        """Say how one rule is getting on, if the window is still open."""
        ch = getattr(self, "_reloc_chain", None)
        if not ch:
            return
        win = ch.get("win")
        if win is None:
            return
        try:
            if win.winfo_exists():
                win.set_row(idx, text, colour)
        except Exception:
            pass

    def _reloc_chain_step(self):
        """Take on the rule at position i — scanning again first if need be."""
        ch = getattr(self, "_reloc_chain", None)
        if not ch:
            return
        i = ch["i"]
        if ch["stop"] or i >= len(ch["rules"]):
            self._reloc_chain_finish()
            return
        rule, files = ch["rules"][i]
        if not ch["dirty"]:
            self._reloc_chain_have(i, files)
            return
        self._reloc_chain_row(i, "looking again…", C_FG_DIM)
        active_dir = getattr(self.get_active_panel(), "current_path", "")
        r = dict(rule)

        def _worker():
            try:
                fresh = _relocator_scan(r, active_dir)
            except Exception as exc:
                _log(f"Relocator: re-scan failed for {r.get('name','')}: {exc}")
                fresh = []
            _ui_call(self, lambda: self._reloc_chain_have(i, fresh))

        threading.Thread(target=_worker, daemon=True).start()

    def _reloc_chain_have(self, idx: int, files: list):
        """The files this rule wants are known — hand them to the queue."""
        ch = getattr(self, "_reloc_chain", None)
        if not ch or ch["i"] != idx:
            return                  # stopped, or an old scan arriving too late
        if ch["stop"]:
            self._reloc_chain_finish()
            return
        rule = ch["rules"][idx][0]
        if not files:
            self._reloc_chain_row(idx, "—  nothing", C_FG_DIM)
            self._reloc_chain_next(0, dirty=False)
            return
        self._reloc_chain_row(idx, f"▶  {len(files)} file(s)…", C_ACCENT)
        collect = []
        started = []            # did the rule get as far as handing over?

        def _queued(i=idx, c=collect, n=len(files)):
            started.append(1)
            self._reloc_chain_wait(i, c, n)

        # One rule falling over must not take the chain with it.  Without this
        # the chain would sit on that rule for ever — and since only one chain
        # may run at a time, "Run all" would be dead until the program was
        # restarted.  The rule is marked ⚠ and the next one gets its turn.
        try:
            self.run_relocator_rule(rule, files=files, quiet=True,
                                    collect=collect, on_queued=_queued)
        except Exception as exc:
            _log(f"Relocator: rule “{rule.get('name','')}” fell over: {exc}")
            if not started:
                ch = getattr(self, "_reloc_chain", None)
                if ch:
                    ch["warn"] = True
                self._reloc_chain_row(idx, f"⚠  {str(exc)[:34]}", "#e8c84a")
                self._reloc_chain_next(0, dirty=True)

    def _reloc_chain_wait(self, idx: int, tasks: list, n: int):
        """Everything this rule will queue is queued — now watch it through.

        Deliberately does NOT look at the tasks yet: on_queued can fire from
        inside run_relocator_rule, and stepping straight on from there would
        start the next rule while still inside the previous one."""
        ch = getattr(self, "_reloc_chain", None)
        if not ch or ch["i"] != idx:
            return
        self.after(RELOCATOR_POLL_MS,
                   lambda: self._reloc_chain_check(idx, tasks, n, 1))

    def _reloc_chain_check(self, idx: int, tasks: list, n: int, ticks: int):
        ch = getattr(self, "_reloc_chain", None)
        if not ch or ch["i"] != idx:
            return
        busy = [t for t in tasks if not _reloc_task_finished(t)]
        if busy:
            # The label is only rewritten every couple of seconds.  Three times
            # a second is not information, it is a flicker.
            if ticks % 7 == 0:
                parked = any(_reloc_task_parked(t) for t in busy)
                secs   = int(ticks * RELOCATOR_POLL_MS / 1000)
                self._reloc_chain_row(
                    idx,
                    ("⏸  the queue is asking…" if parked
                     else f"▶  {n} file(s)  ·  {secs}s"),
                    ("#e8c84a" if parked else C_ACCENT))
            self.after(RELOCATOR_POLL_MS,
                       lambda: self._reloc_chain_check(idx, tasks, n, ticks + 1))
            return

        if not tasks:
            # Files were found but nothing reached the queue (a bad destination,
            # or every replacement blocked by a locked file).  Something may
            # still have moved — the retire step runs before the copy — so the
            # next rule looks again to be sure.
            ch["warn"] = True
            self._reloc_chain_row(idx, "—  nothing queued", C_FG_DIM)
            self._reloc_chain_next(0, dirty=True)
            return

        # Only a clean job is counted.  A job that failed or was cancelled may
        # still have moved some of its files — which is why the chain treats
        # the folders as changed either way, but does not claim a number it
        # cannot stand behind.
        failed = [t for t in tasks if t.status == TaskStatus.ERROR]
        gone   = [t for t in tasks if t.status == TaskStatus.CANCELLED]
        if failed or gone:
            ch["warn"] = True
        if failed:
            self._reloc_chain_row(
                idx, f"⚠  {(failed[0].error_msg or 'failed')[:34]}", "#e8c84a")
        elif gone:
            self._reloc_chain_row(idx, "✖  cancelled", C_FG_DIM)
        else:
            self._reloc_chain_row(idx, f"✓  {n} file(s)", "#55aa55")
        self._reloc_chain_next(0 if (failed or gone) else n, dirty=True)

    def _reloc_chain_next(self, moved: int, dirty: bool):
        ch = getattr(self, "_reloc_chain", None)
        if not ch:
            return
        ch["moved"] += moved
        # Once something has moved every later rule looks again — a rule that
        # took nothing changes nothing, and leaves the flag where it was.
        ch["dirty"]  = ch["dirty"] or dirty
        ch["i"]     += 1
        self.after(1, self._reloc_chain_step)

    def _reloc_chain_finish(self):
        ch = getattr(self, "_reloc_chain", None)
        self._reloc_chain = None
        if not ch:
            return
        moved, ran, stopped = ch["moved"], ch["i"], ch["stop"]
        win = ch.get("win")
        if win is not None:
            try:
                if win.winfo_exists():
                    win.finished(moved, ran, len(ch["rules"]), stopped,
                                 clean=not ch.get("warn"))
            except Exception:
                pass
        # "file move(s)", not "files": one file can be carried by several rules
        # in a row — dist → Exe-redo → 1---Blandat is one file and two moves —
        # and a total that called that two files would be a lie.
        self._flash_status(
            f"Relocator · stopped after {ran} rule(s) — {moved} file move(s)"
            if stopped else
            f"Relocator · {ran} rule(s) run in order — {moved} file move(s)")
        self.refresh_panels()

    def relocator_stop_chain(self):
        """The run window's ⏹ — let the rule that is going finish, then stop.

        Stopping mid-copy is what the Task Queue's own ✖ is for; this only
        stops the NEXT rule from starting, which is the safe half."""
        ch = getattr(self, "_reloc_chain", None)
        if ch:
            ch["stop"] = True

    def _after_task_enqueued(self, note: str = "", has_conflict: bool = False):
        """After adding a task: keep the queue in the background by default so
        the file manager stays usable.  Only pop the window open when the user
        has asked for it (Settings ▸ General).  Either way the ⚡N toolbar button
        shows the pending count and opens the window on click.

        *has_conflict*: the just-queued task is parked because the destination
        already has a file with that name.  In that case we pop the Task Queue
        window to the FRONT (always-on-top, no focus steal) — otherwise you
        would only see a "Copy queued" flash and wrongly assume everything went
        fine.  The window cannot be buried behind other programs until you deal
        with it, yet the arrow keys stay in the file manager the whole time."""
        self._update_queue_btn()
        if has_conflict:
            # HOW the question reaches you is Settings ▸ General ▸ "When a copy
            # hits a name clash".  All three ways are kept, because which one
            # is right depends on what you are doing at the time:
            #   bar    — a strip in THIS window, above the status bar.  Loud,
            #            never covers the panels, never takes the arrow keys.
            #   dialog — handled before we get here: the job is not parked at
            #            all, the per-file dialog stops the copy and asks.
            #   queue  — the old way: the ⚠ button and the status line only.
            mode = self._conflict_alert_mode()
            if mode == "bar":
                self._conflict_bar_sync()
                self._flash_status(
                    "⚠  File already exists — answer the red bar at the bottom "
                    "(Ctrl+Alt+1…5), the arrow keys stay in the list")
            else:
                if self.settings.get("queue_alert_front", False):
                    self.task_queue_mgr.alert_window()
                self._flash_status(
                    "⚠  File already exists — job is WAITING in the Task Queue "
                    "(click ⚠ to resolve the name clash)")
        else:
            # A clean copy/move NEVER pops the queue window open — it just runs
            # in the background and updates the ⚡ counter.  (The queue only ever
            # appears on its own when something needs your attention.)  This also
            # keeps the keyboard firmly in the file manager: creating/showing the
            # queue window is what used to steal the arrow keys after a move.
            pending = self.task_queue_mgr.pending_count()
            msg = note or "Task queued"
            self._flash_status(f"{msg}  —  running in background "
                               f"(⚡{pending} pending; click ⚡ to view)")

    # ══ Backup rename ═══════════════════════════════════════════════════
    # Prefix each selected file with  Backup<CODE>-  where <CODE> is a 3-char
    # code (000…ZZZ) that is unique PER original filename.  Used codes are
    # remembered in Helpfiles/redigerare/backup_codes.json so repeats never
    # collide — and each file keeps its OWN base name, so backing up several
    # different programs at once never bundles them under one name.

    _BACKUP_PREFIX_RE = _re.compile(r"^Backup[0-9A-Za-z]{3}-")
    _BACKUP_CHARS = _string.digits + _string.ascii_uppercase   # 0-9 A-Z (36)

    def _load_backup_codes(self) -> dict:
        try:
            with open(BACKUP_CODES_PATH, "r", encoding="utf-8") as fh:
                data = json.load(fh)
                return data if isinstance(data, dict) else {}
        except FileNotFoundError:
            return {}
        except Exception as exc:
            _log(f"Could not load backup codes: {exc}")
            return {}

    def _save_backup_codes(self, data: dict):
        try:
            with open(BACKUP_CODES_PATH, "w", encoding="utf-8") as fh:
                json.dump(data, fh, indent=2, ensure_ascii=False)
        except Exception as exc:
            _log(f"Could not save backup codes: {exc}")

    def _backup_base_key(self, name: str) -> str:
        """Strip any existing Backup<CODE>- prefix so repeated backups of the
        same program share one code pool (File_manager.py, not Backup001-…)."""
        return self._BACKUP_PREFIX_RE.sub("", name)

    def _next_backup_code(self, used: set) -> str:
        """A random 3-char code not already in *used*.  Falls back to a longer
        code only in the (astronomically unlikely) event the pool is full."""
        for _ in range(2000):
            code = "".join(_random.choice(self._BACKUP_CHARS) for _ in range(3))
            if code not in used:
                return code
        # Pool effectively exhausted — widen to 4 chars
        while True:
            code = "".join(_random.choice(self._BACKUP_CHARS) for _ in range(4))
            if code not in used:
                return code

    def backup_rename_selected(self):
        """Ctrl+Shift+B menu / right-click — Backup-rename the selection."""
        panel = self.get_active_panel()
        if getattr(panel, "is_remote", False):
            messagebox.showinfo("Backup rename",
                                "Backup rename works on local files only.",
                                parent=self)
            return

        # Gather ALL selected FILES — this honours both Insert-key marks (red)
        # and the ordinary tree selection, via get_all_selected().  Folders are
        # skipped (backups are of files).
        names = []
        for full in panel.get_all_selected():
            if os.path.isfile(full):
                names.append(os.path.basename(full))
        if not names:
            messagebox.showinfo(
                "Backup rename",
                "Mark or select one or more files first.\n"
                "(Folders are skipped — this renames files.)",
                parent=self)
            return

        # Plan a unique code per file.  Codes are reserved per base key WITHIN
        # this batch too, so two copies of the same name never clash.
        codes_db = self._load_backup_codes()
        batch_reserved: dict = {}   # key -> set reserved during this batch
        plan = []                   # (old_name, new_name, key, code)
        for name in names:
            key  = self._backup_base_key(name)
            used = set(codes_db.get(key, []))
            used |= batch_reserved.get(key, set())
            code = self._next_backup_code(used)
            batch_reserved.setdefault(key, set()).add(code)
            new_name = f"Backup{code}-{key}"
            plan.append((name, new_name, key, code))

        # Confirmation dialog: Yes / No / Yes + move
        choice = self._backup_confirm_dialog(plan)
        if choice not in ("yes", "yes-move"):
            return

        move_dir = ""
        if choice == "yes-move":
            move_dir = self._backup_get_move_dir()
            if not move_dir:
                return   # user cancelled the folder pick

        # Carry it out
        done = 0
        oplog_entries = []
        for old_name, new_name, key, code in plan:
            src = os.path.join(panel.current_path, old_name)
            dst = os.path.join(panel.current_path, new_name)
            try:
                if os.path.exists(dst):
                    # Extremely unlikely (code was unused) — skip rather than clobber
                    _log(f"Backup rename skipped, target exists: {dst}")
                    continue
                os.rename(src, dst)
                final = dst
                if move_dir:
                    moved = os.path.join(move_dir, new_name)
                    if os.path.exists(moved):
                        _log(f"Backup move skipped, target exists: {moved}")
                    else:
                        shutil.move(dst, moved)
                        final = moved
                oplog_entries.append({"src": src, "dst": final})
                # Reserve the code only once the rename actually happened
                codes_db.setdefault(key, [])
                if code not in codes_db[key]:
                    codes_db[key].append(code)
                self.tagstore.remap([(src, final)])
                done += 1
            except Exception as exc:
                messagebox.showerror(
                    "Backup rename",
                    f"Could not back up {old_name}:\n{exc}", parent=self)

        self._save_backup_codes(codes_db)
        if oplog_entries:
            self.oplog.record("rename", oplog_entries,
                              note=f"Backup rename × {done}"
                                   + (f"  (moved to {move_dir})" if move_dir else ""))
        self.refresh_panels()
        if done:
            where = f" and moved to {move_dir}" if move_dir else ""
            self._flash_status(f"Backup rename: {done} file(s) renamed{where}.")

    def _backup_get_move_dir(self) -> str:
        """Return the configured backup-move folder, asking (and saving) if it
        is not set yet or no longer exists."""
        cur = self.settings.get("backup_move_dir", "")
        if cur and os.path.isdir(cur):
            return cur
        chosen = filedialog.askdirectory(
            parent=self,
            title="Choose the folder to move backups into "
                  "(saved for next time)",
            initialdir=cur if cur else self.get_active_panel().current_path)
        if not chosen:
            return ""
        self.settings["backup_move_dir"] = chosen
        self.save_settings()
        return chosen

    def _backup_confirm_dialog(self, plan: list) -> str:
        """Show the rename plan; return 'yes', 'yes-move', or '' (cancel)."""
        result = {"choice": ""}

        dlg = tk.Toplevel(self)
        dlg.configure(bg=C_BG)
        _setup_toplevel(dlg, f"Backup rename — {len(plan)} file(s)", self)
        dlg.geometry("620x420")

        tk.Label(dlg, text="These files will be renamed:", bg=C_BG, fg=C_FG,
                 font=("Segoe UI", 10, "bold")).pack(anchor="w", padx=12, pady=(10, 4))

        # Scrollable preview list
        list_fr = tk.Frame(dlg, bg=C_BG)
        list_fr.pack(fill="both", expand=True, padx=12)
        cols = ("old", "new")
        tv = ttk.Treeview(list_fr, columns=cols, show="headings", height=10)
        tv.heading("old", text="From")
        tv.heading("new", text="To")
        tv.column("old", width=280, anchor="w")
        tv.column("new", width=300, anchor="w")
        tv.pack(side="left", fill="both", expand=True)
        sb = ttk.Scrollbar(list_fr, orient="vertical", command=tv.yview)
        sb.pack(side="right", fill="y")
        tv.configure(yscrollcommand=sb.set)
        for old_name, new_name, _k, _c in plan:
            tv.insert("", "end", values=(old_name, new_name))

        cur_dir = self.settings.get("backup_move_dir", "") or "(not set — you will be asked)"
        tk.Label(dlg,
                 text=f"“Yes + move” also moves them to:\n{cur_dir}",
                 bg=C_BG, fg=C_FG_DIM, font=("Segoe UI", 8), justify="left"
                 ).pack(anchor="w", padx=12, pady=(6, 4))

        btn_row = tk.Frame(dlg, bg=C_BG)
        btn_row.pack(fill="x", padx=12, pady=(2, 12))

        def _choose(val):
            result["choice"] = val
            dlg.destroy()

        # Button colours are written out plainly so they are easy to change.
        BTN_YES_BG      = "green"
        BTN_YESMOVE_BG  = "blue"
        BTN_NO_BG       = "grey"
        tk.Button(btn_row, text="Yes", width=10, bg=BTN_YES_BG, fg="white",
                  activebackground=BTN_YES_BG, activeforeground="white",
                  command=lambda: _choose("yes")).pack(side="left", padx=(0, 6))
        tk.Button(btn_row, text="Yes + move", width=12, bg=BTN_YESMOVE_BG, fg="white",
                  activebackground=BTN_YESMOVE_BG, activeforeground="white",
                  command=lambda: _choose("yes-move")).pack(side="left", padx=6)
        tk.Button(btn_row, text="No", width=10, bg=BTN_NO_BG, fg="white",
                  activebackground=BTN_NO_BG, activeforeground="white",
                  command=lambda: _choose("")).pack(side="right")

        # Enter = Yes, Escape = No
        dlg.bind("<Return>", lambda e: _choose("yes"))
        dlg.bind("<Escape>", lambda e: _choose(""))
        self.wait_window(dlg)
        return result["choice"]

    def _copy_move_local(self, sources, target, move=False):
        """Queue a copy/move immediately — no blocking dialogs.

        *target* is already the other panel's current path.  Conflicts and
        disk-space issues are detected silently and shown in the Task Queue
        window as banners the user can resolve at any time.
        """
        if isinstance(sources, str):
            sources = [sources]
        if not sources:
            return
        if not target:
            return
        # Remember this transfer's context so the Task Queue can offer a one-tick
        # "always auto-resolve THIS folder pair in THIS Workspace" checkbox.
        # The Workspace is taken from the active (source) panel, falling back to
        # the other panel — so a Workspace loaded on either side is captured
        # rather than silently becoming a blank (= any-workspace) rule.
        try:
            ws = self._ws_name.get(self.active_panel) or ""
            if not ws:
                other = "right" if self.active_panel == "left" else "left"
                ws = self._ws_name.get(other) or ""
            self._last_transfer = {
                "workspace": ws,
                "src": os.path.dirname(sources[0]) if sources else "",
                "dst": target,
            }
        except Exception:
            self._last_transfer = None

        # Smart-queue rule: a saved source→destination rule (optionally scoped to
        # a Workspace) can pick the clash policy automatically — e.g. "from this
        # folder to that one, always Overwrite older" — so no dialog is needed.
        rule = self._best_conflict_rule(sources, target)
        mode = ((rule.get("conflict", "") or None) if rule else None) or "ask"
        self.task_queue_mgr.add_copy_move(sources, target, move,
                                          conflict_mode=mode)
        # The clash scan runs in a thread now (that is what stopped the program
        # freezing while a copy to the network drive was queued), so whether the
        # job is PARKED on a name clash is not known yet.  _preflight_done()
        # raises the "waiting in the Task Queue" alert when the answer comes in.
        note = "Move queued" if move else "Copy queued"
        if mode != "ask":
            note += f"  ·  auto-rule: {_CONFLICT_LABEL.get(mode, mode)}"
            # WHICH rule, not just what it decided.  Without this a wrong rule
            # is invisible: the job simply behaves differently from what he
            # wrote down, with nothing on screen to say a broader rule spoke
            # first.  That is exactly how the {ROOT}→{ROOT} catch-all went
            # unnoticed (revBF).
            if rule:
                r_src = (rule.get("src") or "").strip() or "any"
                r_dst = (rule.get("dst") or "").strip() or "any"
                r_ws  = (rule.get("workspace") or "").strip()
                note += (f"   [{_shorten_mid(r_src, 34)} → "
                         f"{_shorten_mid(r_dst, 34)}"
                         + (f", {r_ws}]" if r_ws else "]"))
        self._after_task_enqueued(note, has_conflict=False)

    def _match_conflict_rule(self, sources, dest) -> "str | None":
        """The auto conflict-mode for this transfer, or None to ask."""
        rule = self._best_conflict_rule(sources, dest)
        return (rule.get("conflict", "") or None) if rule else None

    def _conflict_rule_scan(self, sources, dest) -> list:
        """The saved rules that cover this source→dest transfer, best first.

        A rule matches when the source's folder is at (or under) the rule's
        source path, the destination is at (or under) the rule's destination
        path, and — if the rule names a Workspace — that Workspace is
        currently loaded.  An empty source/dest in a rule is a wildcard.

        THE MOST SPECIFIC MATCH WINS, not the first one in the list (revBF).
        It used to be first-in-the-list, and that quietly cost him a backup:
        one rule said "0---Claude_work_dir → Py: Backup-rename old" in
        Workspace "Python", and another said "{ROOT} → {ROOT}: Overwrite all"
        in Workspace "Grund" — the whole tree to the whole tree.  Standing in
        Grund, the specific rule was filtered out by the Workspace test before
        the order was even looked at, so the catch-all decided, and the file
        he meant to keep was replaced instead of renamed.  Order can never
        express that: a rule naming both exact folders IS the more precise
        answer whatever date it was created.  Specificity is measured as how
        much of the two paths the rule actually pins down; a named Workspace
        breaks a tie, and the list order breaks what is left, so two equally
        precise rules behave exactly as they always did."""
        try:
            rules = _load_conflict_rules()
        except Exception:
            rules = []
        if not rules:
            return []
        src_dir = os.path.dirname(sources[0]) if sources else ""
        src_n = os.path.normcase(os.path.abspath(src_dir)) if src_dir else ""
        dst_n = os.path.normcase(os.path.abspath(dest)) if dest else ""
        active_ws = {v for v in getattr(self, "_ws_name", {}).values() if v}

        def _match(pattern: str, target: str):
            """(matches?, how specific) — the length of the path it pins down,
            0 for a wildcard, so a bare drive letter still scores less than a
            folder deep in the tree."""
            pattern = (pattern or "").strip()
            if not pattern:
                return True, 0                   # wildcard
            base = os.path.normcase(os.path.abspath(pattern))
            if target == base or target.startswith(base + os.sep):
                return True, len(base)
            return False, 0

        out = []
        for idx, r in enumerate(rules):
            if not r.get("enabled", True):
                continue
            ws = (r.get("workspace", "") or "").strip()
            ok_s, score_s = _match(r.get("src", ""), src_n)
            if not ok_s:
                continue
            ok_d, score_d = _match(r.get("dst", ""), dst_n)
            if not ok_d:
                continue
            ws_ok = (not ws) or (ws in active_ws)
            score = (score_s + score_d) * 2 + (1 if ws else 0)
            out.append({"index": idx, "rule": r, "score": score,
                        "ws_ok": ws_ok})
        # Best first; the list order settles a tie, so two equally precise
        # rules behave exactly as they always did.
        out.sort(key=lambda c: (-c["score"], c["index"]))
        return out

    def _conflict_rule_candidates(self, sources, dest) -> list:
        """Every enabled rule whose PATHS cover this transfer, best first —
        including the ones a Workspace is currently keeping out ("ws_ok":
        False).  Those are the interesting ones when a rule "does nothing":
        it matched the folders and was then filtered out."""
        return self._conflict_rule_scan(sources, dest)

    def _best_conflict_rule(self, sources, dest):
        for c in self._conflict_rule_scan(sources, dest):
            if c["ws_ok"]:
                self._last_rule_used  = dict(c["rule"])
                self._last_rule_index = c["index"]
                return c["rule"]
        return None

    def _copy_move_local_LEGACY_UNUSED(self, sources, target, move=False):
        """Original direct-execute version — kept for reference, not called."""
        if isinstance(sources, str):
            sources = [sources]
        if not sources:
            return
        dlg = _CopyMoveConfirmDlg(self, sources, target, move)
        self.wait_window(dlg)
        if not dlg.result:
            return
        conflict_mode = dlg.conflict_mode
        dest_dir      = dlg.dest_dir
        if not dest_dir:
            return
        os.makedirs(dest_dir, exist_ok=True)
        verb  = "Moving" if move else "Copying"
        total = _count_copy_items(sources)
        prog  = _ProgressDialog(self, f"{verb}…", total=total)
        def _worker():
            cm        = conflict_mode
            skip_identical = bool(
                self.settings.get("conflict_skip_identical", False))
            counter   = [0]
            abort     = [False]

            def _ask_conflict(src, dst) -> str:
                nonlocal cm
                # Same size, same date = the same file.  With the setting
                # on it is skipped without a question at all, so copying a
                # folder you already copied asks nothing.
                if skip_identical and _same_file_enough(src, dst):
                    return _ConflictDlg.SKIP
                if cm == "ask":
                    result_list = [None]
                    evt         = threading.Event()
                    prog.post("conflict", src, dst, result_list, evt)
                    evt.wait()
                    action = result_list[0]
                    if action == _ConflictDlg.OVERWRITE_ALL:
                        cm = "overwrite_all";  action = _ConflictDlg.OVERWRITE
                    elif action == _ConflictDlg.SKIP_ALL:
                        cm = "skip_all";       action = _ConflictDlg.SKIP
                    return action
                elif cm == "overwrite_all":
                    return _ConflictDlg.OVERWRITE
                elif cm == "skip_all":
                    return _ConflictDlg.SKIP
                elif cm == "auto_rename":
                    return _ConflictDlg.AUTO_RENAME
                elif cm == "overwrite_older":
                    try:
                        if os.path.getmtime(src) <= os.path.getmtime(dst):
                            return _ConflictDlg.SKIP
                    except Exception:
                        pass
                    return _ConflictDlg.OVERWRITE
                return _ConflictDlg.OVERWRITE

            def _copy_one(fsrc: str, fdst: str) -> bool:
                """Copy/move a single file; returns False if aborted."""
                if prog.cancelled:
                    return False
                counter[0] += 1
                prog.post("progress", counter[0], total, fsrc)

                if os.path.exists(fdst):
                    action = _ask_conflict(fsrc, fdst)
                    if action == _ConflictDlg.CANCEL:
                        abort[0] = True
                        return False
                    if action == _ConflictDlg.SKIP:
                        return True
                    if action == _ConflictDlg.AUTO_RENAME:
                        fdst = _auto_rename_path(fdst)
                    else:  # OVERWRITE
                        try:
                            if os.path.isdir(fdst):
                                shutil.rmtree(fdst)
                            else:
                                os.remove(fdst)
                        except Exception:
                            pass

                os.makedirs(os.path.dirname(fdst), exist_ok=True)
                if move:
                    shutil.move(fsrc, fdst)
                else:
                    shutil.copy2(fsrc, fdst)
                return True

            def _process(src: str):
                dst_root = os.path.join(dest_dir, os.path.basename(src))
                if os.path.isfile(src):
                    _copy_one(src, dst_root)
                elif os.path.isdir(src):
                    os.makedirs(dst_root, exist_ok=True)
                    for dirpath, dirnames, fnames in os.walk(src):
                        if prog.cancelled or abort[0]:
                            break
                        rel         = os.path.relpath(dirpath, src)
                        dst_dir_cur = os.path.join(dst_root, rel) if rel != "." else dst_root
                        os.makedirs(dst_dir_cur, exist_ok=True)
                        for fname in fnames:
                            if prog.cancelled or abort[0]:
                                break
                            _copy_one(os.path.join(dirpath, fname),
                                      os.path.join(dst_dir_cur, fname))
                    # For move: remove the (now-empty) source tree
                    if move and not prog.cancelled and not abort[0]:
                        try:
                            shutil.rmtree(src)
                        except Exception:
                            pass

            for src in sources:
                if prog.cancelled or abort[0]:
                    break
                try:
                    _process(src)
                except Exception as exc:
                    verb_l    = "move" if move else "copy"
                    err_msg   = f"Could not {verb_l} {os.path.basename(src)}:\n{exc}"
                    cont_list = [False]
                    evt       = threading.Event()
                    prog.post("error", err_msg, cont_list, evt)
                    evt.wait()
                    if not cont_list[0]:
                        break

            prog.post("done")
            self.after(100, self.refresh_panels)

        threading.Thread(target=_worker, daemon=True).start()

    @staticmethod
    def _send_to_recycle_bin(paths: list) -> list:
        """Send paths to the Windows Recycle Bin via SHFileOperationW.
        Returns a list of paths that could NOT be recycled."""
        import ctypes
        import ctypes.wintypes as _wt

        class _SHFILEOPSTRUCTW(ctypes.Structure):
            _fields_ = [
                ("hwnd",                  _wt.HWND),
                ("wFunc",                 _wt.UINT),
                ("pFrom",                 ctypes.c_wchar_p),
                ("pTo",                   ctypes.c_wchar_p),
                ("fFlags",                _wt.WORD),
                ("fAnyOperationsAborted", _wt.BOOL),
                ("hNameMappings",         ctypes.c_void_p),
                ("lpszProgressTitle",     ctypes.c_wchar_p),
            ]

        FO_DELETE          = 0x0003
        FOF_ALLOWUNDO      = 0x0040
        FOF_NOCONFIRMATION = 0x0010
        FOF_SILENT         = 0x0004

        errors = []
        for path in paths:
            try:
                pFrom = path + "\0\0"
                op = _SHFILEOPSTRUCTW()
                op.hwnd   = 0
                op.wFunc  = FO_DELETE
                op.pFrom  = pFrom
                op.fFlags = FOF_ALLOWUNDO | FOF_NOCONFIRMATION | FOF_SILENT
                ret = ctypes.windll.shell32.SHFileOperationW(ctypes.byref(op))
                if ret != 0:
                    errors.append(path)
            except Exception:
                errors.append(path)
        return errors

    def delete_files(self):
        # CRITICAL SAFETY: never delete while the keyboard is in a text field.
        # The Delete key is bound globally, so without this guard pressing Delete
        # to erase a character during an inline rename would trash the selected
        # file(s) — exactly the data-loss that must never happen.
        if self._focus_in_text_widget():
            return
        panel = self.get_active_panel()
        if getattr(panel, "archive_ctx", None):
            self._delete_from_archive(panel)
            return
        if getattr(panel, "is_remote", False):
            sel = panel.get_selected()
            if not sel:
                return
            path, is_dir = sel
            label = "folder" if is_dir else "file"
            if _ask_yes_no("Confirm", f"Delete {label}: {os.path.basename(path)}?"):
                try:
                    panel.delete_path(path, is_dir=is_dir)
                    self.refresh_panels()
                except Exception as exc:
                    messagebox.showerror("FTP error", f"Could not delete: {exc}")
            return

        # Local delete.
        sources = panel.get_all_selected()
        if not sources:
            return
        # Don't try to "delete" an item that is already trash
        sources = [p for p in sources
                   if not os.path.basename(p).startswith(TRASH_PREFIX)]
        if not sources:
            return

        # Remember which item to focus after deletion:
        # first item below the selection; fall back to item above.
        all_iids  = list(panel.tree.get_children())
        sel_iids  = list(panel.tree.selection())
        next_focus = None
        if sel_iids:
            last_idx = all_iids.index(sel_iids[-1]) if sel_iids[-1] in all_iids else -1
            for iid in all_iids[last_idx + 1:]:
                if iid not in sel_iids:
                    next_focus = panel._fullname(iid)
                    break
            if next_focus is None:
                first_idx = all_iids.index(sel_iids[0]) if sel_iids[0] in all_iids else 0
                for iid in reversed(all_iids[:first_idx]):
                    name = panel._fullname(iid)
                    if name != "..":
                        next_focus = name
                        break

        if self.settings.get("delete_use_trash", True):
            self.move_to_trash(sources)          # rename to ~deleted~, hide, purge later
        else:
            # Straight to the Windows Recycle Bin, no in-place trash
            failed = EditorFrame._send_to_recycle_bin(
                [p for p in sources if os.path.exists(p)])
            try:    self.tagstore.clear([p for p in sources if p not in failed])
            except Exception: pass
            if failed:
                messagebox.showerror(
                    "Delete",
                    "Could not delete:\n  " +
                    "\n  ".join(os.path.basename(p) for p in failed[:12]),
                    parent=self)
        self.refresh_panels()

        # Restore cursor to the remembered neighbour
        if next_focus:
            for iid in panel.tree.get_children():
                if panel._fullname(iid) == next_focus:
                    panel.tree.selection_set(iid)
                    panel.tree.focus(iid)
                    panel.tree.see(iid)
                    break

    def _delete_from_archive(self, panel):
        """Delete key while browsing inside an archive: permanently remove
        the marked entries from a writable archive (zip / 7z / tar family).
        Read-only containers (RAR / ISO / CAB) can't be rewritten and say so."""
        names = panel.archive_selected_inner_names()
        if not names:
            return
        ctx = panel.archive_ctx
        fmt = ctx.get("fmt", "")
        if fmt not in PACK_FORMATS:
            messagebox.showinfo(
                "Archive",
                f"{fmt.upper()} archives are read-only here — files can be "
                "copied out (F5) but not removed from this archive type.")
            return
        n = len(names)
        if not _ask_yes_no(
                "Confirm",
                f"Permanently remove {n} item(s) from\n"
                f"{os.path.basename(ctx['archive_path'])}?\n\n"
                "This rewrites the archive file and cannot be undone."):
            return
        self.config(cursor="watch")
        self.update_idletasks()
        try:
            archive_delete_members(ctx["archive_path"], names)
            ctx["entries"] = archive_list(ctx["archive_path"])
        except Exception as exc:
            _archive_error_box(self, exc)
        finally:
            self.config(cursor="")
        panel._refresh_archive_view()
        panel._clear_marks_and_selection()

    # ── Deletion → tiered in-place trash ─────────────────────────────────
    #
    # Delete does NOT leave the file under its own name and it does NOT vanish
    # into a parallel universe.  It RENAMES the item in place to
    #     ~deleted~<date>~<original name>
    # which frees the original name at once (reuse it immediately, here or in
    # any other program) and marks it clearly as trash.  The panels hide
    # ~deleted~ items.  A start-up sweep then PHYSICALLY removes old trash:
    # small files (< trash_small_max_mb) after trash_small_weeks weeks, larger
    # files after trash_large_hours hours (capped at 30) — a big file never
    # lingers, yet a mistake still gives you hours (or weeks) to put it back.
    # The 🗑 window can Restore, Purge selected, or Empty everything now.

    def _restore_task_queue(self):
        """Put back whatever the queue still had to do when the program last
        closed — PAUSED, and with the Task Queue in front so it cannot be
        missed.  Not one byte moves until ▶ Start is pressed."""
        try:
            n = self.task_queue_mgr.restore_state()
        except Exception as exc:
            _log(f"Task queue could not be restored: {exc}")
            return
        if not n:
            return
        _log(f"Task queue: {n} unfinished job(s) carried over, paused")
        try:
            self.task_queue_mgr.alert_window()
            self._update_queue_btn()
        except Exception as exc:
            _log(f"Task queue restored but could not be shown: {exc}")

    def _load_pending_delete(self):
        """Read the trash list; drop entries whose trash file is already gone."""
        data = _load_json_list(PENDING_DELETE_PATH)
        self._pending: list = []
        for item in data:
            if isinstance(item, str):                 # oldest format: bare path
                item = {"orig": item, "trash": item, "marked": "", "size": 0}
            elif "trash" not in item:                 # previous "hide in place"
                p = item.get("path", "")
                item = {"orig": p, "trash": p,
                        "marked": item.get("marked", ""), "size": 0}
            trash = item.get("trash", "")
            if trash and os.path.exists(trash):
                self._pending.append({
                    "orig":   item.get("orig", trash),
                    "trash":  trash,
                    "marked": item.get("marked", ""),
                    "size":   int(item.get("size", 0) or 0),
                })
        self._trash = [e["trash"] for e in self._pending]
        if len(self._pending) != len(data):
            self._save_pending_delete()

    def _save_pending_delete(self):
        self._trash = [e["trash"] for e in self._pending]
        _save_json_list(PENDING_DELETE_PATH, self._pending)

    def _is_pending(self, path: str) -> bool:
        n = os.path.normcase(path)
        return any(os.path.normcase(e["orig"]) == n
                   or os.path.normcase(e["trash"]) == n
                   for e in self._pending)

    def _reconcile_pending(self) -> bool:
        """Drop trash entries whose trash file is gone — purged, restored, or
        removed by another program — so the list can never hide something that
        no longer exists.  Returns True if the list changed."""
        if not self._pending:
            return False
        keep = [e for e in self._pending if os.path.exists(e.get("trash", ""))]
        if len(keep) != len(self._pending):
            self._pending = keep
            self._save_pending_delete()
            self._update_trash_btn()
            return True
        return False

    def _clear_pending_if_deleted(self, path: str) -> bool:
        """Legacy helper: if *path* is a still-in-place (old style) trash file,
        remove it so the name is free.  New-style trash already frees the name
        by renaming, so this rarely fires now."""
        matches = [e for e in self._pending
                   if os.path.normcase(e["trash"]) == os.path.normcase(path)]
        if not matches:
            return False
        for e in matches:
            t = e["trash"]
            try:
                if os.path.isdir(t):      shutil.rmtree(t)
                elif os.path.exists(t):   os.remove(t)
            except Exception as exc:
                _log(f"Could not remove trash {t}: {exc}")
                return False
        self._pending = [e for e in self._pending if e not in matches]
        self._save_pending_delete()
        self._update_trash_btn()
        return True

    @staticmethod
    def _path_size(path: str) -> int:
        try:
            if os.path.isdir(path):
                total = 0
                for root, _d, files in os.walk(path):
                    for f in files:
                        try:    total += os.path.getsize(os.path.join(root, f))
                        except OSError: pass
                    if total > (1 << 40):     # 1 TB — stop, it is clearly "large"
                        return total
                return total
            return os.path.getsize(path)
        except OSError:
            return 0

    def move_to_trash(self, paths: list) -> int:
        """Delete = rename each item in place to ~deleted~<date>~<name>, freeing
        the original name immediately.  Records a reversible move so Ctrl+Z (and
        the 🗑 window's Restore) can put it back.  Returns how many moved.

        A file another program holds open (or one Windows otherwise refuses to
        rename) asks what to do via _DeleteErrorDlg — Try again / Skip / Abort —
        with "do the same for every other file that fails", so a batch of files
        that are all locked by the same program only has to be answered once
        instead of clicking OK through each one in turn."""
        when      = datetime.now()
        stamp     = when.strftime("%Y%m%d-%H%M%S")
        moved, undo_items = 0, []
        fail_mode = [None]     # sticky choice once "apply to all" is ticked
        aborted   = [False]

        def _rename_with_retry(path, trash_path) -> bool:
            """True once the file has been moved to trash; False = give up."""
            while True:
                try:
                    os.rename(path, trash_path)
                    return True
                except Exception as exc:
                    _log(f"Could not move {path} to trash: {exc}")
                    reason = (_friendly_oserror(exc) if isinstance(exc, OSError)
                              else str(exc))
                    choice = fail_mode[0]
                    if choice is None:
                        dlg = _DeleteErrorDlg(self, path, reason)
                        self.wait_window(dlg)
                        choice = dlg.action
                        if dlg.all_var.get():
                            fail_mode[0] = choice

                    if choice == _DeleteErrorDlg.ABORT:
                        aborted[0] = True
                        return False
                    if choice == _DeleteErrorDlg.RETRY:
                        # One immediate retry; if it is still locked, ask again
                        # next time rather than looping silently for ever.
                        fail_mode[0] = None
                        continue
                    return False   # SKIP

        for path in paths:
            if aborted[0]:
                break
            if not os.path.exists(path):
                continue
            folder     = os.path.dirname(path)
            orig_name  = os.path.basename(path)
            size       = self._path_size(path)
            trash_path = os.path.join(folder, f"{TRASH_PREFIX}{stamp}~{orig_name}")
            n = 1
            while os.path.exists(trash_path):
                trash_path = os.path.join(
                    folder, f"{TRASH_PREFIX}{stamp}~{n}~{orig_name}")
                n += 1

            if not _rename_with_retry(path, trash_path):
                continue

            self._pending.append({
                "orig":   path, "trash": trash_path,
                "marked": when.isoformat(timespec="seconds"), "size": size})
            try:    self.tagstore.remap([(path, trash_path)])
            except Exception: pass
            undo_items.append({"src": path, "dst": trash_path})
            moved += 1
        if moved:
            self._save_pending_delete()
            self._update_trash_btn()
            try:
                self.oplog.record("move", undo_items,
                                  note=f"{moved} item(s) deleted (to trash)")
            except Exception as exc:
                _log(f"Could not log the deletion: {exc}")
        return moved

    # Back-compat alias — older code / undo entries may still use this name
    def mark_for_deletion(self, paths: list) -> int:
        return self.move_to_trash(paths)

    def restore_from_trash(self, entries: list) -> int:
        """Put trashed items back under their original name (skipping any whose
        name has been taken again)."""
        restored, blocked = 0, []
        for e in list(entries):
            trash = e.get("trash", "")
            orig  = e.get("orig", "")
            if not os.path.exists(trash):
                self._pending = [x for x in self._pending if x is not e]
                continue
            if os.path.exists(orig):
                blocked.append(os.path.basename(orig))
                continue
            try:
                os.makedirs(os.path.dirname(orig), exist_ok=True)
                os.rename(trash, orig)
                try:    self.tagstore.remap([(trash, orig)])
                except Exception: pass
                self._pending = [x for x in self._pending if x is not e]
                restored += 1
            except Exception as exc:
                _log(f"Could not restore {trash}: {exc}")
                blocked.append(os.path.basename(orig))
        if restored:
            self._save_pending_delete()
            self._update_trash_btn()
            self.refresh_panels()
        if blocked:
            messagebox.showinfo(
                "Restore",
                "Could not restore these — the name is in use again:\n  "
                + "\n  ".join(blocked[:12]), parent=self)
        return restored

    def unmark_deletion(self, paths: list):
        """Legacy undo hook (old 'delete_mark' log entries): restore by orig path."""
        wanted  = {os.path.normcase(p) for p in paths}
        entries = [e for e in self._pending
                   if os.path.normcase(e["orig"]) in wanted]
        if entries:
            self.restore_from_trash(entries)

    def trash_age_hours(self, entry: dict) -> float:
        try:
            marked = datetime.fromisoformat(entry.get("marked", ""))
        except (ValueError, TypeError):
            return 0.0
        return (datetime.now() - marked).total_seconds() / 3600.0

    def _trash_is_small(self, entry: dict) -> bool:
        try:    max_mb = float(self.settings.get("trash_small_max_mb", 5))
        except (TypeError, ValueError): max_mb = 5.0
        return entry.get("size", 0) < max_mb * 1024 * 1024

    def _trash_due_for_purge(self, entry: dict) -> bool:
        age_h = self.trash_age_hours(entry)
        if self._trash_is_small(entry):
            try:    weeks = float(self.settings.get("trash_small_weeks", 2))
            except (TypeError, ValueError): weeks = 2.0
            return age_h >= weeks * 7 * 24
        try:    hours = float(self.settings.get("trash_large_hours", 24))
        except (TypeError, ValueError): hours = 24.0
        hours = min(hours, 30.0)              # user cap: large files, max 30 h
        return age_h >= hours

    def purge_trash(self, entries: list) -> int:
        """Physically remove the given trash items (to the Recycle Bin) and drop
        them from the list.  Returns how many were removed."""
        entries = [e for e in entries]
        paths   = [e["trash"] for e in entries if os.path.exists(e.get("trash", ""))]
        failed  = set()
        if paths:
            failed = {os.path.normcase(p)
                      for p in EditorFrame._send_to_recycle_bin(paths)}
        removed = [e for e in entries
                   if not os.path.exists(e.get("trash", ""))
                   or os.path.normcase(e["trash"]) not in failed]
        if removed:
            try:    self.tagstore.clear([e["trash"] for e in removed])
            except Exception: pass
            rm_ids = {id(e) for e in removed}
            self._pending = [e for e in self._pending if id(e) not in rm_ids]
            self._save_pending_delete()
            self._update_trash_btn()
            self.refresh_panels()
        return len(removed)

    def empty_trash_all(self) -> int:
        """Purge EVERYTHING in the trash now, ignoring the age thresholds."""
        return self.purge_trash(list(self._pending))

    def purge_trash_by_age(self):
        """Start-up sweep: physically remove trash old enough for its tier."""
        self._reconcile_pending()
        due = [e for e in list(self._pending) if self._trash_due_for_purge(e)]
        if not due:
            return
        removed = self.purge_trash(due)
        if removed:
            _log(f"Trash sweep: purged {removed} item(s) past their retention")
            self._flash_status(f"Trash: purged {removed} old item(s)")

    # __init__ still calls this name at start-up
    def auto_purge_pending(self):
        """Schedule the trash sweep: once after the configured start-up delay
        (default 5 min so it never slows the launch), then once a day."""
        try:
            delay_ms = max(0, int(float(
                self.settings.get("trash_startup_delay_min", 5)) * 60_000))
        except (TypeError, ValueError):
            delay_ms = 300_000

        def _sweep():
            try:    self.purge_trash_by_age()
            except Exception as exc: _log(f"Trash sweep failed: {exc}")
            try:    self.after(24 * 3600 * 1000, _sweep)
            except Exception: pass

        try:
            self.after(delay_ms, _sweep)
        except Exception:
            pass

    # ══════════════════════════════════════════════════════════════════════
    #  DEL 49 — Delete-when-unlocked
    # ----------------------------------------------------------------------
    #  A MOVE cannot rename a file that another program holds open (Cubase on
    #  a .wav, a player on a video).  It can normally still READ it, so the
    #  file is COPIED across and the original is queued here to be removed the
    #  moment the lock goes.  The list is written to disk immediately, so it
    #  survives a crash or a reboot and is retried on the next start.
    #  Nothing is ever lost: until the delete succeeds the original stays put.
    # ══════════════════════════════════════════════════════════════════════

    UNLOCK_RETRY_MS = 30_000          # how often to poke the locked originals

    def _load_unlock_deletes(self):
        self._unlock_deletes = []
        try:
            if UNLOCK_DELETE_PATH.exists():
                data = json.loads(UNLOCK_DELETE_PATH.read_text(encoding="utf-8"))
                if isinstance(data, list):
                    self._unlock_deletes = [d for d in data
                                            if isinstance(d, dict) and d.get("src")]
        except Exception as exc:
            _log(f"Could not read {UNLOCK_DELETE_PATH.name}: {exc}")

    def _save_unlock_deletes(self):
        try:
            UNLOCK_DELETE_PATH.write_text(
                json.dumps(self._unlock_deletes, indent=2, ensure_ascii=False),
                encoding="utf-8")
        except Exception as exc:
            _log(f"Could not write {UNLOCK_DELETE_PATH.name}: {exc}")

    def schedule_delete_when_unlocked(self, src: str, dst: str = ""):
        """Remember an original that must go once its program lets go of it."""
        key = os.path.normcase(os.path.abspath(src))
        if not hasattr(self, "_unlock_deletes"):
            self._load_unlock_deletes()
        if any(os.path.normcase(d["src"]) == key for d in self._unlock_deletes):
            return
        self._unlock_deletes.append({
            "src": os.path.abspath(src),
            "dst": dst,
            "since": _time.time(),
        })
        self._save_unlock_deletes()      # written NOW, so a crash cannot lose it
        _log(f"Delete-when-unlocked scheduled: {src}")

    def _retry_unlock_deletes(self):
        """Periodic sweep: remove the originals whose lock has been released.

        A delete is only attempted when the copy really is at the destination —
        otherwise a failed copy plus a released lock would destroy the only
        remaining copy of the file."""
        try:
            if not getattr(self, "_unlock_deletes", None):
                return
            done, still = [], []
            for entry in self._unlock_deletes:
                src, dst = entry.get("src", ""), entry.get("dst", "")
                if not os.path.exists(src):
                    done.append(entry)                 # already gone
                    continue
                if dst and not os.path.exists(dst):
                    still.append(entry)                # the copy is missing — wait
                    continue
                try:
                    os.remove(src)
                    done.append(entry)
                    _log(f"Delete-when-unlocked succeeded: {src}")
                except OSError:
                    still.append(entry)                # still held — try again later
            if done:
                self._unlock_deletes = still
                self._save_unlock_deletes()
                names = ", ".join(os.path.basename(d["src"]) for d in done[:3])
                extra = f" +{len(done) - 3} more" if len(done) > 3 else ""
                self._flash_status(
                    f"🔓  Released and removed: {names}{extra}", 5000)
                self.refresh_panels()
        except Exception as exc:
            _log(f"Delete-when-unlocked sweep failed: {exc}")
        finally:
            try:
                self.after(self.UNLOCK_RETRY_MS, self._retry_unlock_deletes)
            except Exception:
                pass

    def show_transfer_report(self, failures: list, deferred: list,
                             verb: str, n_ok: int):
        """"Here is what did not go through" — deliberately NOT a crash.

        Non-modal on purpose (like the crash notice): you can keep working
        while you read it.  It lists every file that could not be handled and
        WHY, in plain language, plus anything that was copied and is waiting
        for its original to be released."""
        try:
            win = tk.Toplevel(self)
            _setup_toplevel(win, f"{verb} finished — with notes", self,
                            modal=False)
            win.geometry("860x430")
            head = "✔  " if not failures else "⚠  "
            tk.Label(win, text=f"{head}{verb} finished: {n_ok} file(s) done.",
                     font=("Segoe UI", 11, "bold")).pack(padx=14, pady=(14, 2),
                                                         anchor="w")
            note = []
            if failures:
                note.append(f"{len(failures)} could not be handled")
            if deferred:
                note.append(f"{len(deferred)} copied across, original waiting "
                            "for the other program to let go")
            if note:
                tk.Label(win, text=" · ".join(note), fg="#666666",
                         font=("Segoe UI", 9)).pack(padx=14, anchor="w")

            mid = ttk.Frame(win)
            mid.pack(fill="both", expand=True, padx=14, pady=8)
            tree = ttk.Treeview(mid, columns=("why",), selectmode="browse")
            tree.heading("#0",  text="File")
            tree.heading("why", text="What happened")
            tree.column("#0",  width=420, anchor="w")
            tree.column("why", width=380, anchor="w")
            sb = ttk.Scrollbar(mid, orient="vertical", command=tree.yview)
            tree.configure(yscrollcommand=sb.set)
            sb.pack(side="right", fill="y")
            tree.pack(side="left", fill="both", expand=True)
            tree.tag_configure("bad",  foreground=TC_BAD)
            tree.tag_configure("wait", foreground=TC_WARN)
            for path, reason in failures:
                tree.insert("", "end", text=os.path.basename(path),
                            values=(reason,), tags=("bad",))
            for path in deferred:
                tree.insert("", "end", text=os.path.basename(path),
                            values=("copied — the original goes as soon as the "
                                    "other program releases it",),
                            tags=("wait",))

            bar = ttk.Frame(win)
            bar.pack(fill="x", padx=14, pady=(0, 12))
            if deferred:
                ttk.Button(bar, text="🔒  Show what is waiting…",
                           command=self.show_unlock_pending).pack(side="left")
            ttk.Button(bar, text="Close", command=win.destroy,
                       width=10).pack(side="right")
        except Exception as exc:
            _log(f"Could not show the transfer report: {exc}")
            self._flash_status(
                f"⚠  {verb}: {len(failures)} file(s) could not be handled "
                f"(see the log).", 8000)

    def pending_unlock_count(self) -> int:
        return len(getattr(self, "_unlock_deletes", []))

    def show_unlock_pending(self):
        """List the originals still waiting for their program to let go."""
        items = list(getattr(self, "_unlock_deletes", []))
        if not items:
            _flash_ok(self, "Nothing is waiting to be removed.", "Locked files")
            return
        win = tk.Toplevel(self)
        _setup_toplevel(win, "Waiting for a program to release these", self)
        win.geometry("820x360")
        tk.Label(win, text="🔒  Copied across — the original goes as soon as "
                           "the other program lets go",
                 font=("Segoe UI", 10, "bold")).pack(padx=12, pady=(12, 2),
                                                     anchor="w")
        tk.Label(win, text=f"Rechecked automatically every "
                           f"{self.UNLOCK_RETRY_MS // 1000} seconds, and again "
                           f"on every start.  Nothing is lost meanwhile — the "
                           f"original simply stays where it is.",
                 fg="#666666", font=("Segoe UI", 8), justify="left"
                 ).pack(padx=12, anchor="w")
        mid = ttk.Frame(win)
        mid.pack(fill="both", expand=True, padx=12, pady=8)
        tree = ttk.Treeview(mid, columns=("waiting",), selectmode="browse")
        tree.heading("#0", text="Original still on disk")
        tree.heading("waiting", text="Waiting since")
        tree.column("#0", width=600, anchor="w")
        tree.column("waiting", width=150, anchor="w")
        sb = ttk.Scrollbar(mid, orient="vertical", command=tree.yview)
        tree.configure(yscrollcommand=sb.set)
        sb.pack(side="right", fill="y")
        tree.pack(side="left", fill="both", expand=True)
        for d in items:
            when = datetime.fromtimestamp(d.get("since", 0)).strftime("%Y-%m-%d %H:%M")
            tree.insert("", "end", text=d["src"], values=(when,))

        bar = ttk.Frame(win)
        bar.pack(fill="x", padx=12, pady=(0, 12))

        def _try_now():
            self._retry_unlock_deletes()
            win.destroy()
            self.show_unlock_pending() if self.pending_unlock_count() else None

        def _forget():
            sel = tree.selection()
            if not sel:
                return
            path = tree.item(sel[0], "text")
            self._unlock_deletes = [
                d for d in self._unlock_deletes
                if os.path.normcase(d["src"]) != os.path.normcase(path)]
            self._save_unlock_deletes()
            tree.delete(sel[0])

        ttk.Button(bar, text="🔄  Try now", command=_try_now,
                   width=14).pack(side="left")
        ttk.Button(bar, text="Forget the selected one (keep the original)",
                   command=_forget).pack(side="left", padx=6)
        ttk.Button(bar, text="Close", command=win.destroy,
                   width=10).pack(side="right")

    # ══════════════════════════════════════════════════════════════════════
    #  DEL 48 — "Which one is newest?"  (⚖ the scales, between ⚡ and 🗑)
    # ----------------------------------------------------------------------
    #  A toggle you can leave switched on.  While it is in, every file NAME
    #  that exists in BOTH panels is compared by its modified time:
    #
    #      GREEN   this side is the NEWER copy, and a different size
    #      RED     this side is the OLDER copy, and a different size
    #      BLUE    different moment but exactly the SAME size — almost always
    #              the same file copied into two folders, one written a moment
    #              later.  It is NOT called newer, because calling it newer is
    #              what sent you looking for a change that was never made.
    #      AMBER   same moment but a DIFFERENT size — worth a look
    #      normal  same moment and same size → unchanged, nothing to do
    #      VIOLET  (second stage only) this name is on THIS side only
    #
    #  Nothing is touched on disk; it is only colour, and it disappears the
    #  moment the button pops out again.  The button has three states: off,
    #  comparing, and comparing + flagging one-sided files.
    # ══════════════════════════════════════════════════════════════════════

    # Timestamps that differ by less than this count as "the same moment".
    # FAT stores 2-second resolution and copies across filesystems routinely
    # land a second apart, so a stricter test would paint half a folder red.
    # The copy dialogs use the same number — see SAME_MOMENT_S.
    CMP_TOLERANCE_S = SAME_MOMENT_S

    def toggle_compare_sides(self):
        """⚖ — step through the three states.

            off  →  comparing  →  comparing + one-sided files  →  off

        The middle one is the old behaviour: only names that exist in BOTH
        panels are coloured.  The third also marks the files that are on one
        side and not the other, which is the question you are really asking
        when you put two folders next to each other."""
        on      = getattr(self, "compare_sides_on", False)
        singles = getattr(self, "compare_sides_singles", False)
        if not on:
            on, singles = True, False
        elif not singles:
            singles = True
        else:
            on, singles = False, False
        self.compare_sides_on      = on
        self.compare_sides_singles = singles
        self.settings["compare_sides_on"]      = on
        self.settings["compare_sides_singles"] = singles
        self.save_settings()
        self._update_compare_btn()
        if on:
            self.apply_side_comparison()
            extra = ("  ·  VIOLET = only on this side"
                     if singles else "")
            self._flash_status(
                "⚖  Comparing the two panels: GREEN = newer, RED = older, "
                "BLUE = same size (just a different moment), "
                "AMBER = same moment but different size." + extra, 7000)
        else:
            self.clear_side_comparison()
            self._flash_status("⚖  Comparison off.", 2000)

    def _update_compare_btn(self):
        """Show the state on the button itself — in the character AND in the
        colour, so it reads at a glance and still reads if a Windows theme
        refuses to tint a ttk button."""
        on      = getattr(self, "compare_sides_on", False)
        singles = getattr(self, "compare_sides_singles", False)
        if not on:
            text, style = "⚖", "CmpOff.TButton"
        elif not singles:
            text, style = "⚖▪", "TButton"
        else:
            text, style = "⚖◆", "CmpSingles.TButton"
        try:
            self._compare_btn.configure(text=text, style=style)
        except Exception:
            try:
                self._compare_btn.configure(text=text)
            except Exception:
                pass

    def schedule_side_comparison(self):
        """Ask for a re-compare once the current burst of refreshes is over.

        Both panels refresh independently (navigation, the folder watcher, a
        finished copy), and comparing on each one would do the work twice for
        no reason — so it is coalesced onto one idle callback."""
        if not getattr(self, "compare_sides_on", False):
            return
        if getattr(self, "_cmp_pending", False):
            return
        self._cmp_pending = True

        def _run():
            self._cmp_pending = False
            try:
                self.apply_side_comparison()
            except Exception as exc:
                _log(f"Side comparison failed: {exc}")

        try:
            self.after_idle(_run)
        except Exception:
            self._cmp_pending = False

    def clear_side_comparison(self):
        """Strip the comparison colours from both panels."""
        for panel in (getattr(self, "left_panel", None),
                      getattr(self, "right_panel", None)):
            tree = getattr(panel, "tree", None)
            if tree is None:
                continue
            try:
                for iid in tree.get_children():
                    tags = [t for t in tree.item(iid, "tags")
                            if not t.startswith("cmp_")]
                    tree.item(iid, tags=tags)
            except Exception:
                pass

    def apply_side_comparison(self):
        """Colour every file name that appears in BOTH panels.

        Only real, local, non-branch panels take part — an FTP listing has no
        comparable local timestamps, and branch view shows relative paths from
        several folders at once, so a plain name match would be wrong there.
        """
        left, right = getattr(self, "left_panel", None), getattr(self, "right_panel", None)
        if left is None or right is None:
            return
        self.clear_side_comparison()
        if not getattr(self, "compare_sides_on", False):
            return
        for p in (left, right):
            if (getattr(p, "is_remote", False) or getattr(p, "branch_mode", False)
                    or not os.path.isdir(getattr(p, "current_path", ""))):
                return
        # Both panels showing the same folder would paint everything "equal" —
        # true, but pointless noise, so say so instead.
        if os.path.normcase(os.path.abspath(left.current_path)) == \
           os.path.normcase(os.path.abspath(right.current_path)):
            self._flash_status("⚖  Both panels show the same folder — "
                               "nothing to compare.", 3000)
            return

        lrows = self._cmp_rows(left)
        rrows = self._cmp_rows(right)
        common = set(lrows) & set(rrows)

        tol   = self.CMP_TOLERANCE_S
        pairs = 0
        for key in common:
            l_iid, l_stat = lrows[key]
            r_iid, r_stat = rrows[key]
            if l_stat is None or r_stat is None:
                continue
            l_mtime, l_size = l_stat
            r_mtime, r_size = r_stat
            diff = l_mtime - r_mtime
            if abs(diff) <= tol:
                # Same moment.  Same size too → genuinely unchanged, leave it
                # in its normal colour.  Different size → someone edited a copy
                # while keeping the date, which is exactly what you want to see.
                if l_size != r_size:
                    self._cmp_tag(left,  l_iid, "cmp_same_diff")
                    self._cmp_tag(right, r_iid, "cmp_same_diff")
                    pairs += 1
                continue
            if l_size == r_size:
                # Different moment, identical size.  Copy a file into two
                # folders and one of them lands a moment later; green here
                # would say "this one is newer" about a file nobody changed.
                self._cmp_tag(left,  l_iid, "cmp_restamp")
                self._cmp_tag(right, r_iid, "cmp_restamp")
                pairs += 1
                continue
            if diff > 0:
                self._cmp_tag(left,  l_iid, "cmp_newer")
                self._cmp_tag(right, r_iid, "cmp_older")
            else:
                self._cmp_tag(left,  l_iid, "cmp_older")
                self._cmp_tag(right, r_iid, "cmp_newer")
            pairs += 1
        self._cmp_last_pairs = pairs

        # Second stage: the files that are on one side and not the other.
        # Comparing two folders is usually as much about what is MISSING as
        # about which copy is newer, and those names used to be left plain.
        self._cmp_last_singles = 0
        if getattr(self, "compare_sides_singles", False):
            for panel, rows, others in ((left, lrows, rrows),
                                        (right, rrows, lrows)):
                for key, (iid, _stat) in rows.items():
                    if key not in others:
                        self._cmp_tag(panel, iid, "cmp_only")
                        self._cmp_last_singles += 1

    def _cmp_rows(self, panel) -> dict:
        """{lower-case filename: (row iid, (mtime, size))} for one panel.

        Folders are skipped — a folder's own timestamp says nothing about what
        is inside it, so colouring folders would be actively misleading."""
        out  = {}
        tree = panel.tree
        base = panel.current_path
        for iid in tree.get_children():
            try:
                if tree.set(iid, "type") == "Folder":
                    continue
                name = panel._fullname(iid)
                if not name or name == "..":
                    continue
                st = os.stat(os.path.join(base, name))
                out[name.lower()] = (iid, (st.st_mtime, st.st_size))
            except Exception:
                continue
        return out

    @staticmethod
    def _cmp_tag(panel, iid, tag: str):
        """Put a comparison tag FIRST on the row.

        ttk.Treeview resolves an option from the first tag in the item's list
        that defines it, so the comparison colour has to lead — otherwise the
        folder blue or a label colour would keep winning."""
        try:
            tags = [t for t in panel.tree.item(iid, "tags")
                    if not t.startswith("cmp_")]
            panel.tree.item(iid, tags=[tag] + tags)
        except Exception:
            pass

    def _update_trash_btn(self):
        """Update the trash toolbar button label to show how many items are pending."""
        count = len(self._trash)
        try:
            self._trash_btn.configure(text=f"🗑{count}" if count else "🗑")
        except Exception:
            pass

    def _build_ext_colour_section(self, parent, start_row: int):
        """The "File colours by extension" half of the Customization tab.

        Returns a function that hands back the edited group list, so the
        Settings Save button can store it without knowing how any of this is
        laid out."""
        ttk.Separator(parent, orient="horizontal").grid(
            row=start_row, column=0, columnspan=3, sticky="ew", pady=(4, 10))
        ttk.Label(parent, text="File colours by extension",
                  font=("", 0, "bold")).grid(
            row=start_row + 1, column=0, columnspan=3, sticky="w")
        ttk.Label(
            parent,
            text="Files are drawn in the standard colour unless a group below "
                 "is ticked.\n"
                 "A colour label (Ctrl+G) always wins over this, and folder "
                 "blue, the red marking colour and the grey cursor row are "
                 "never touched.",
            foreground="#888888", justify="left").grid(
            row=start_row + 2, column=0, columnspan=3, sticky="w", pady=(2, 6))

        groups = _load_ext_groups(self.settings)
        rows = []          # [{"on": BooleanVar, "name": …, "exts": …, …}]

        bar = ttk.Frame(parent)
        bar.grid(row=start_row + 3, column=0, columnspan=3, sticky="w",
                 pady=(0, 6))

        # White, because that is what the file list is: the preview has to lie
        # about nothing.
        LIST_BG = "#ffffff"
        wrap = ttk.Frame(parent)
        wrap.grid(row=start_row + 4, column=0, columnspan=3, sticky="nsew")
        canvas = tk.Canvas(wrap, height=230, highlightthickness=0, bg=LIST_BG)
        sb = ttk.Scrollbar(wrap, orient="vertical", command=canvas.yview)
        canvas.configure(yscrollcommand=sb.set)
        # Scrollbar packed FIRST or an expanding neighbour leaves it 1 px wide.
        sb.pack(side="right", fill="y")
        canvas.pack(side="left", fill="both", expand=True)
        inner = tk.Frame(canvas, bg=LIST_BG)
        inner_id = canvas.create_window((0, 0), window=inner, anchor="nw")
        inner.bind("<Configure>",
                   lambda e: canvas.configure(scrollregion=canvas.bbox("all")))
        canvas.bind("<Configure>",
                    lambda e: canvas.itemconfig(inner_id, width=e.width))
        canvas.bind("<MouseWheel>",
                    lambda e: canvas.yview_scroll(-1 * (e.delta // 120), "units"))

        def _sample_text(exts: str) -> str:
            first = ""
            for e in _re.split(r"[;,\s]+", exts or ""):
                e = e.strip().lstrip("*").lstrip(".")
                if e:
                    first = e
                    break
            return f"example.{first}" if first else "example"

        def _add_row(g: dict):
            row = tk.Frame(inner, bg=LIST_BG)
            row.pack(fill="x", padx=2, pady=1)
            v_on = tk.BooleanVar(value=bool(g.get("enabled", False)))
            state = {"colour": g.get("colour", "#444444")}

            sample = tk.Label(row, text=_sample_text(g.get("exts", "")),
                              bg=LIST_BG, fg=state["colour"], width=16,
                              anchor="w", font=("Segoe UI", 9))
            e_name = _mk_entry(row, width=20, bg=LIST_BG, fg="#000000",
                               relief="flat", highlightthickness=1,
                               highlightbackground="#d0d0d0")
            e_name.insert(0, g.get("name", ""))
            e_exts = _mk_entry(row, bg=LIST_BG, fg="#000000",
                               relief="flat", highlightthickness=1,
                               highlightbackground="#d0d0d0")
            e_exts.insert(0, g.get("exts", ""))

            def _repaint(*_a):
                sample.configure(text=_sample_text(e_exts.get()),
                                 fg=state["colour"] if v_on.get() else "#000000")
                swatch.configure(bg=state["colour"])

            def _pick():
                new = self._ask_ext_colour(state["colour"],
                                           row.winfo_toplevel())
                if new:
                    state["colour"] = new
                    v_on.set(True)
                    _repaint()

            def _drop(r=row):
                rows[:] = [x for x in rows if x["frame"] is not r]
                r.destroy()

            tk.Checkbutton(row, variable=v_on, bg=LIST_BG, fg="#000000",
                           activebackground=LIST_BG, selectcolor=LIST_BG,
                           command=_repaint).pack(side="left")
            swatch = tk.Button(row, text="  ", bg=state["colour"], width=2,
                               relief="ridge", command=_pick)
            swatch.pack(side="left", padx=(0, 6))
            e_name.pack(side="left", padx=(0, 6))
            e_exts.pack(side="left", fill="x", expand=True, padx=(0, 6))
            sample.pack(side="left", padx=(0, 4))
            tk.Button(row, text="✕", width=2, relief="flat", bg=LIST_BG,
                      fg="#888888", activebackground="#eeeeee",
                      command=_drop).pack(side="left")
            e_exts.bind("<KeyRelease>", _repaint)
            rows.append({"frame": row, "on": v_on, "name": e_name,
                         "exts": e_exts, "state": state, "repaint": _repaint})
            _repaint()

        def _rebuild(gs: list):
            for w in inner.winfo_children():
                w.destroy()
            rows.clear()
            for g in gs:
                _add_row(g)

        def _all(on: bool):
            for r in rows:
                r["on"].set(on)
                r["repaint"]()

        def _collect() -> list:
            out = []
            for r in rows:
                name = r["name"].get().strip()
                exts = r["exts"].get().strip()
                if not exts and not name:
                    continue
                out.append({"name": name or "(unnamed)", "exts": exts,
                            "colour": r["state"]["colour"],
                            "enabled": bool(r["on"].get())})
            return out

        ttk.Button(bar, text="Use the suggested colours",
                   command=lambda: _all(True)).pack(side="left")
        ttk.Button(bar, text="Turn all off",
                   command=lambda: _all(False)).pack(side="left", padx=6)
        ttk.Button(bar, text="＋  Add a group",
                   command=lambda: _add_row(
                       {"name": "", "exts": "", "colour": "#444444",
                        "enabled": True})).pack(side="left")
        ttk.Button(bar, text="↺  Back to the suggested list",
                   command=lambda: _rebuild(
                       [dict(g) for g in DEFAULT_EXT_GROUPS])).pack(side="left",
                                                                    padx=6)
        _rebuild(groups)
        parent.rowconfigure(start_row + 4, weight=1)
        parent.columnconfigure(2, weight=1)
        return _collect

    def _ask_ext_colour(self, initial: str, parent_win=None) -> str:
        """Colour picker for a file-colour group: the ready-made swatches
        first, the full Windows colour box one click further."""
        parent_win = parent_win or self
        win = tk.Toplevel(parent_win)
        _setup_toplevel(win, "File colour", parent_win)
        win.resizable(False, False)
        chosen = {"v": ""}

        ttk.Label(win, text="Pick a colour for these files:").pack(
            padx=14, pady=(12, 6), anchor="w")
        grid = tk.Frame(win, bg=C_BG)
        grid.pack(padx=14, pady=(0, 8))

        def _take(c):
            chosen["v"] = c
            win.destroy()

        for i, c in enumerate(EXT_COLOUR_SWATCHES):
            r, col = divmod(i, 5)
            b = tk.Button(grid, bg=c, width=4, height=2, relief="ridge",
                          command=lambda c=c: _take(c))
            b.grid(row=r, column=col, padx=3, pady=3)

        btns = ttk.Frame(win)
        btns.pack(padx=14, pady=(0, 12), fill="x")

        def _full():
            try:
                from tkinter import colorchooser
                _rgb, hexval = colorchooser.askcolor(
                    color=initial or "#444444", parent=win,
                    title="File colour")
                if hexval:
                    _take(hexval)
            except Exception as exc:
                _log(f"Colour chooser failed: {exc}")

        ttk.Button(btns, text="More colours…", command=_full).pack(side="left")
        ttk.Button(btns, text="Cancel", command=win.destroy).pack(side="right")
        win.wait_window()
        # Hand the grab back to whoever had it (the Settings window), or the
        # dialog underneath is left non-modal for the rest of its life.
        try:
            if parent_win is not self and parent_win.winfo_exists():
                parent_win.grab_set()
        except Exception:
            pass
        return chosen["v"]

    def reload_ext_colours(self):
        """Rebuild the extension → colour map from the settings.

        Called at start-up and again whenever Settings is saved, so a colour
        change shows on the next refresh instead of at the next start."""
        try:
            self.ext_colours = _ext_colour_map(_load_ext_groups(self.settings))
        except Exception as exc:
            _log(f"Could not read the file colours: {exc}")
            self.ext_colours = {}

    def _update_queue_btn(self):
        """Update the queue toolbar button with the number of pending tasks.

        A job that is WAITING for the user (a name clash, or no room on the
        destination) turns the bolt into a ⚠ — that is the whole signal now
        that the window no longer jumps in front by default."""
        try:
            count = self.task_queue_mgr.pending_count()
            waiting = self.task_queue_mgr.waiting_count()
            if waiting:
                # A grey ⚡ turning into a grey ⚠ was the "marked, but not
                # clearly" complaint.  The waiting button now says what it
                # wants and is drawn in bold red.  It does NOT blink — the
                # colour is simply on until the question is answered.
                self._queue_btn.configure(text=f"⚠{count or waiting} ANSWER")
                self._set_queue_btn_alert(True)
            else:
                self._queue_btn.configure(text=f"⚡{count}" if count else "⚡")
                self._set_queue_btn_alert(False)
                # …and then the state colour on top of the plain style, so the
                # bolt says where the window is even when nothing is pending.
                self._paint_queue_btn(self._queue_top_mode_effective())
        except Exception:
            pass
        # The inline conflict bar lives or dies with the same state, so it is
        # refreshed from the same place — the two can never disagree.
        try:
            self._conflict_bar_sync()
        except Exception:
            pass

    def open_trash(self):
        """The trash window: deleted items waiting to be physically purged."""
        self._reconcile_pending()
        if not self._pending:
            messagebox.showinfo(
                "Trash",
                "The trash is empty.\n\n"
                "Delete (F8) renames an item to a ~deleted~ name and hides it. "
                "Small files are purged after a few weeks, larger ones after a "
                "few hours — or purge them yourself here.", parent=self)
            return

        win = tk.Toplevel(self)
        win.configure(bg=C_BG)
        win.geometry("940x520")
        _setup_toplevel(win, f"Trash — {len(self._pending)} item(s)",
                        self, modal=False)

        head = tk.Frame(win, bg=C_BG3)
        head.pack(fill="x")
        tk.Label(head, text="🗑  Trash", bg=C_BG3, fg=C_ACCENT,
                 font=("Segoe UI", 12, "bold")).pack(side="left", padx=10, pady=7)
        tk.Label(head, text="Deleted (renamed ~deleted~ and hidden) — purged by age",
                 bg=C_BG3, fg=C_FG_DIM, font=("Segoe UI", 9)).pack(side="left")

        tree = ttk.Treeview(win, columns=("deleted", "tier", "purge", "size", "folder"),
                            selectmode="extended")
        tree.heading("#0",      text="Item",       anchor="w")
        tree.heading("deleted", text="Deleted",    anchor="w")
        tree.heading("tier",    text="Tier",       anchor="w")
        tree.heading("purge",   text="Purge in",   anchor="e")
        tree.heading("size",    text="Size",       anchor="e")
        tree.heading("folder",  text="Folder",     anchor="w")
        tree.column("#0", width=210, stretch=True)
        tree.column("deleted", width=150)
        tree.column("tier", width=110)
        tree.column("purge", width=95, anchor="e")
        tree.column("size", width=90, anchor="e")
        tree.column("folder", width=250)
        sb = ttk.Scrollbar(win, orient="vertical", command=tree.yview)
        tree.configure(yscrollcommand=sb.set)
        tree.tag_configure("due", foreground=TC_WARN)
        # NOTE: the tree is packed LAST (at the end of this method), AFTER the
        # status bar and the right-hand button column.  A widget packed with
        # expand=True claims all the leftover space, so if the tree were packed
        # first the Restore / Purge buttons would be squeezed to zero width —
        # which is exactly why they used to be impossible to reach.

        status = tk.Label(win, text="", bg=C_BG3, fg=C_FG_DIM, anchor="w",
                          font=("Segoe UI", 9))
        status.pack(fill="x", side="bottom")

        def _purge_in_text(e):
            age_h = self.trash_age_hours(e)
            if self._trash_is_small(e):
                try:    weeks = float(self.settings.get("trash_small_weeks", 2))
                except (TypeError, ValueError): weeks = 2.0
                left_h = weeks * 7 * 24 - age_h
                if left_h <= 0: return "now"
                return f"{left_h / 24:.1f} d"
            try:    hours = min(float(self.settings.get("trash_large_hours", 24)), 30.0)
            except (TypeError, ValueError): hours = 24.0
            left_h = hours - age_h
            return "now" if left_h <= 0 else f"{left_h:.1f} h"

        def _render():
            tree.delete(*tree.get_children())
            total = 0
            for i, e in enumerate(self._pending):
                size = e.get("size", 0)
                total += size
                small = self._trash_is_small(e)
                due   = self._trash_due_for_purge(e)
                tree.insert(
                    "", "end", iid=str(i),
                    text=("📁  " if os.path.isdir(e["trash"]) else "📄  ")
                         + os.path.basename(e["orig"]),
                    values=(e.get("marked", "").replace("T", "  "),
                            "small (weeks)" if small else "large (hours)",
                            _purge_in_text(e),
                            _human_size(size) if size else "",
                            os.path.dirname(e["orig"])),
                    tags=("due",) if due else ())
            status.configure(
                text=f"  {len(self._pending)} item(s) · {_human_size(total)} on disk"
                     f"  ·  small < {self.settings.get('trash_small_max_mb', 5)} MB "
                     f"kept {self.settings.get('trash_small_weeks', 2)} wk, "
                     f"larger kept {min(float(self.settings.get('trash_large_hours', 24)), 30):g} h")
            win.title(f"Trash — {len(self._pending)} item(s)")

        def _selected_entries():
            return [self._pending[int(i)] for i in tree.selection()
                    if i.isdigit() and int(i) < len(self._pending)]

        def _restore():
            entries = _selected_entries() or list(self._pending)
            self.restore_from_trash(entries)
            _render()
            if not self._pending:
                win.destroy()

        def _purge(which):
            entries = (_selected_entries() if which == "selected"
                       else list(self._pending))
            if not entries:
                messagebox.showinfo("Trash", "Select what to purge first.", parent=win)
                return
            summary = "\n".join("   " + os.path.basename(e["orig"]) for e in entries[:20])
            if len(entries) > 20:
                summary += f"\n   … and {len(entries) - 20} more"
            if not _ask_yes_no(
                    "Purge trash",
                    f"Physically remove these {len(entries)} item(s) now?\n\n"
                    f"{summary}\n\nThey go to the Windows Recycle Bin.",
                    parent=win):
                return
            removed = self.purge_trash(entries)
            _render()
            _flash_ok(win, f"Purged {removed} item(s).", "Trash")
            if not self._pending:
                win.destroy()

        btns = tk.Frame(win, bg=C_BG)
        btns.pack(side="right", fill="y", padx=10, pady=8)
        tk.Button(btns, text="↩  Restore", width=24, bg="lightgreen", fg="black",
                  command=_restore).pack(pady=3)
        tk.Label(btns, text="(rename it back to its\noriginal name)",
                 bg=C_BG, fg=C_FG_DIM, font=("Segoe UI", 8),
                 justify="left").pack(pady=(0, 14))
        tk.Button(btns, text="🗑  Purge selected", width=24, bg="#ff8888",
                  fg="black", command=lambda: _purge("selected")).pack(pady=3)
        tk.Button(btns, text="🗑  Empty ALL now", width=24, bg="red", fg="white",
                  command=lambda: _purge("all")).pack(pady=3)
        tk.Label(btns, text="(physically remove now,\nignoring the age limits —\nto the Recycle Bin)",
                 bg=C_BG, fg=C_FG_DIM, font=("Segoe UI", 8),
                 justify="left").pack(pady=(0, 14))
        tk.Button(btns, text="⚙  Deletion settings…", width=24, bg="white",
                  fg="black",
                  command=lambda: DatesDeleteSettingsWindow(self)).pack(pady=3)
        tk.Button(btns, text="Close", width=24, bg="grey", fg="white",
                  command=win.destroy).pack(pady=(14, 3))

        # Pack the scrollbar + tree LAST so the button column above keeps its
        # width (see the note where the tree is created).
        sb.pack(side="left", fill="y", pady=8, padx=(6, 0))
        tree.pack(side="left", fill="both", expand=True, padx=(10, 0), pady=8)

        _render()


    def new_folder(self):
        panel = self.get_active_panel()
        if getattr(panel, "archive_ctx", None):
            messagebox.showinfo("Archive",
                                "Can't create a new folder inside an archive view.\n\n"
                                "Exit the archive first, or copy files out with F5.")
            return
        name  = self._ask_folder_name(initial=self._folder_name_suggestion(panel))
        if not name:
            return
        if getattr(panel, "is_remote", False):
            try:
                panel.mkdir(name)
                self.refresh_panels()
            except Exception as exc:
                messagebox.showerror("FTP error", f"Could not create folder: {exc}")
            return
        try:
            new_path = os.path.join(panel.current_path, name)
            os.makedirs(new_path)
            self.oplog.record("new_folder", [{"src": "", "dst": new_path}],
                              note=name)
            panel.change_directory(new_path)   # navigate into the new folder
        except Exception as exc:
            messagebox.showerror("Error", f"Could not create folder: {exc}")

    def _folder_name_suggestion(self, panel) -> str:
        """Name to pre-fill the New-folder box with.

        Whatever the cursor stands on is the suggestion: a FOLDER contributes
        its whole name, a FILE contributes its name WITHOUT the extension
        (a folder called "movie.mkv" helps nobody).  ".." and an empty panel
        give no suggestion.  The text is pre-selected in the dialog, so typing
        replaces it and Enter accepts it — nothing extra to delete.
        """
        try:
            tree = panel.tree
            iid  = tree.focus() or (tree.selection()[0] if tree.selection() else "")
            if not iid or not tree.exists(iid):
                return ""
            name = panel._fullname(iid) if hasattr(panel, "_fullname") else tree.item(iid, "text")
            if not name or name == "..":
                return ""
            is_dir = False
            try:
                is_dir = tree.set(iid, "type") == "Folder"
            except Exception:
                pass
            if is_dir:
                return name
            base = os.path.splitext(name)[0]
            return base or name
        except Exception:
            return ""

    def _ask_folder_name(self, initial: str = "") -> str:
        """No-blink 'New folder' dialog using tk.Entry directly."""
        result = [""]
        win = tk.Toplevel(self)
        _setup_toplevel(win, "New folder", self)
        win.resizable(False, False)

        ttk.Label(win, text="Folder name:").pack(padx=12, pady=(12, 4))
        entry = tk.Entry(win, width=36, insertofftime=0, insertontime=9999999)
        entry.pack(padx=12, pady=(0, 8))
        if initial:
            entry.insert(0, initial)
            entry.select_range(0, "end")     # typing replaces the suggestion
            entry.icursor("end")
        entry.focus_set()

        def _ok(e=None):
            result[0] = entry.get().strip()
            win.destroy()
            return "break"  # prevent Enter from leaking to on_enter_key

        entry.bind("<Return>", _ok)
        btn_frame = ttk.Frame(win)
        btn_frame.pack(pady=(0, 10))
        ttk.Button(btn_frame, text="OK",     command=_ok,         width=10).pack(side="left",  padx=4)
        ttk.Button(btn_frame, text="Cancel", command=win.destroy, width=10).pack(side="left",  padx=4)
        win.wait_window()
        return result[0]

    def show_properties(self):
        panel = self.get_active_panel()
        if getattr(panel, "archive_ctx", None):
            self._show_archive_properties(panel)
            return
        if getattr(panel, "is_remote", False):
            sel = panel.get_selected()
            if not sel:
                return
            path, is_dir = sel
            info = (
                f"Name:        {os.path.basename(path)}\n"
                f"Remote path: {path}\n"
                f"Type:        {'Folder' if is_dir else 'File'}\n"
                f"Server:      {panel.host}:{panel.port}\n"
                f"Location:    {panel.current_path}"
            )
            messagebox.showinfo("Properties (FTP)", info)
            return

        # MORE THAN ONE thing marked?  Then a single message box is the wrong
        # answer.  Alt+Enter on a multi-selection gives ONE ROW PER ITEM with
        # that item's OWN size — which is the whole reason to mark several
        # folders and ask (revBD).
        try:
            many = panel.get_all_selected()
        except Exception:
            many = []
        if len(many) > 1:
            self._show_multi_properties(panel, many)
            return

        selected = panel.get_selected()
        if not selected:
            return
        try:
            size     = self._directory_size(selected) if os.path.isdir(selected) else os.path.getsize(selected)
            modified = datetime.fromtimestamp(os.path.getmtime(selected))
            created  = datetime.fromtimestamp(os.path.getctime(selected))
            info = (
                f"Name:     {os.path.basename(selected)}\n"
                f"Path:     {selected}\n"
                f"Type:     {'Folder' if os.path.isdir(selected) else 'File'}\n"
                f"Size:     {size:,} bytes  ({size // 1024:,} KB)\n"
                f"Created:  {created}\n"
                f"Modified: {modified}"
            )
            messagebox.showinfo("Properties", info)
        except Exception as exc:
            messagebox.showerror("Error", f"Could not read properties: {exc}")

    # ── Alt+Enter on SEVERAL items — a size per item ──────────────────────
    def _show_multi_properties(self, panel, paths):
        """One row per marked item, each with its OWN size, plus a total.

        Folders are measured in a background thread and the rows fill in as the
        numbers land, so marking twenty folders with a million files between
        them does not freeze the window.  The window is NOT modal — the numbers
        can take a while and he should be able to keep working meanwhile.

        after() is started from the MAIN thread only: a worker's after() only
        fires while mainloop happens to be running, which is exactly how the
        last update goes missing.
        """
        win = tk.Toplevel(self)
        _setup_toplevel(win, f"Properties — {len(paths)} items", self, modal=False)
        win.geometry("860x480")

        stop = threading.Event()
        done = []                       # worker → main thread hand-off
        sizes = {}                      # iid → bytes  (sort key + total)

        def _close(_e=None):
            stop.set()
            try:
                win.destroy()
            except Exception:
                pass

        # _setup_toplevel binds Escape to a bare destroy; rebind so closing
        # also STOPS the measuring thread instead of leaving it walking a disk.
        win.bind("<Escape>", _close)
        win.protocol("WM_DELETE_WINDOW", _close)

        body = ttk.Frame(win)
        cols = ("type", "size", "bytes", "contents", "modified")
        tree = ttk.Treeview(body, columns=cols, selectmode="extended")
        tree.heading("#0",       text="Name")
        tree.heading("type",     text="Type")
        tree.heading("size",     text="Size")
        tree.heading("bytes",    text="Bytes")
        tree.heading("contents", text="Contents")
        tree.heading("modified", text="Modified")
        tree.column("#0",       width=330, stretch=True)
        tree.column("type",     width=70,  anchor="w",  stretch=False)
        tree.column("size",     width=100, anchor="e",  stretch=False)
        tree.column("bytes",    width=140, anchor="e",  stretch=False)
        tree.column("contents", width=140, anchor="e",  stretch=False)
        tree.column("modified", width=130, anchor="w",  stretch=False)

        vsb = ttk.Scrollbar(body, orient="vertical", command=tree.yview)
        tree.configure(yscrollcommand=vsb.set)

        total_lbl = ttk.Label(win, text="")

        n_folders = n_files = 0
        pending   = []                  # (iid, path) folders still to measure
        for p in paths:
            try:
                is_dir = os.path.isdir(p)
                mtime  = datetime.fromtimestamp(os.path.getmtime(p)).strftime("%Y-%m-%d %H:%M")
            except Exception:
                is_dir, mtime = False, "?"
            if is_dir:
                n_folders += 1
                iid = tree.insert("", "end", text=f"📁  {os.path.basename(p) or p}",
                                  values=("Folder", "measuring…", "", "", mtime))
                pending.append((iid, p))
            else:
                n_files += 1
                try:
                    n = os.path.getsize(p)
                except Exception:
                    n = -1
                iid = tree.insert("", "end", text=f"📄  {os.path.basename(p) or p}",
                                  values=("File",
                                          _human_size(n) if n >= 0 else "?",
                                          _group_digits(n) if n >= 0 else "?",
                                          "", mtime))
                sizes[iid] = max(n, 0)

        def _totals(measuring: bool):
            got = sum(sizes.values())
            tail = "  (still measuring…)" if measuring else ""
            total_lbl.config(
                text=f"{n_folders} folder(s), {n_files} file(s)   —   total "
                     f"{_human_size(got)}   ({_group_digits(got)} bytes){tail}")

        _totals(bool(pending))

        # ── Sorting: seeing the sizes is the point, so let him ORDER by them ──
        sort_state = {"col": None, "desc": True}

        def _sort_by(col):
            desc = not sort_state["desc"] if sort_state["col"] == col else True
            sort_state.update(col=col, desc=desc)
            rows = list(tree.get_children())
            if col in ("size", "bytes"):
                key = lambda iid: sizes.get(iid, -1)
            elif col == "#0":
                key = lambda iid: tree.item(iid, "text").lower()
            else:
                key = lambda iid: tree.set(iid, col).lower()
            for pos, iid in enumerate(sorted(rows, key=key, reverse=desc)):
                tree.move(iid, "", pos)

        tree.heading("#0",       command=lambda: _sort_by("#0"))
        for c in cols:
            tree.heading(c, command=lambda c=c: _sort_by(c))

        # ── The measuring worker ──────────────────────────────────────────
        def work():
            cls = type(panel)
            for iid, p in pending:
                if stop.is_set():
                    break
                total = nfiles = ndirs = 0
                try:
                    for dirpath, dirnames, filenames in os.walk(p):
                        if stop.is_set():
                            break
                        # Skip junctions / symlinks, or a reparse point loops
                        # the walk back into a tree already counted.
                        dirnames[:] = [d for d in dirnames
                                       if not cls._is_reparse(os.path.join(dirpath, d))]
                        ndirs += len(dirnames)
                        for fn in filenames:
                            fp = os.path.join(dirpath, fn)
                            try:
                                if not cls._is_reparse(fp):
                                    total  += os.path.getsize(fp)
                                    nfiles += 1
                            except OSError:
                                pass
                except Exception:
                    total = -1
                done.append((iid, total, nfiles, ndirs))

        def drain():
            if stop.is_set():
                return
            try:
                if not win.winfo_exists():
                    return
            except Exception:
                return
            while done:
                iid, n, nf, nd = done.pop(0)
                try:
                    if n < 0:
                        tree.set(iid, "size", "?")
                    else:
                        sizes[iid] = n
                        tree.set(iid, "size",  _human_size(n))
                        tree.set(iid, "bytes", _group_digits(n))
                        tree.set(iid, "contents", f"{nf:,} files, {nd:,} folders")
                except Exception:
                    pass
            alive = th.is_alive()
            _totals(alive)
            if alive:
                win.after(150, drain)

        th = threading.Thread(target=work, daemon=True)
        th.start()
        win.after(150, drain)

        # ── Buttons ───────────────────────────────────────────────────────
        def _copy_list():
            lines = []
            for iid in tree.get_children():
                lines.append(f"{tree.item(iid, 'text')}\t"
                             f"{tree.set(iid, 'size')}\t"
                             f"{tree.set(iid, 'bytes')}\t"
                             f"{tree.set(iid, 'contents')}")
            try:
                win.clipboard_clear()
                win.clipboard_append("\n".join(lines) + "\n" + total_lbl.cget("text"))
            except Exception:
                pass

        frm = ttk.Frame(win)
        ttk.Button(frm, text="Copy list", command=_copy_list).pack(side="left")
        ttk.Button(frm, text="Close",     command=_close).pack(side="right")

        # LAYOUT ORDER MATTERS: pack() hands the leftover space to the first
        # widget that asks for it with expand=True, so the button row and the
        # total line must be placed BEFORE the tree — otherwise the tree eats
        # the whole window and they are squeezed to nothing.  Same reason the
        # scrollbar goes in before the tree inside its own frame.
        frm.pack(side="bottom", fill="x", padx=6, pady=(0, 6))
        total_lbl.pack(side="bottom", fill="x", padx=8, pady=(0, 4))
        body.pack(side="top", fill="both", expand=True, padx=6, pady=6)
        vsb.pack(side="right", fill="y")
        tree.pack(side="left", fill="both", expand=True)

    def _show_archive_properties(self, panel):
        names = panel.archive_selected_inner_names()
        if not names:
            return
        ctx = panel.archive_ctx
        by_name = {_norm_member(e.name): e for e in ctx["entries"]}
        lines, total_size, total_files = [], 0, 0
        for n in names:
            e = by_name.get(_norm_member(n))
            if e is None:
                continue
            if e.is_dir:
                lines.append(f"📁  {n}")
            else:
                total_size  += e.size
                total_files += 1
                lines.append(f"📄  {n}   ({_human_size(e.size)})")
        shown = lines[:20]
        more  = f"\n… and {len(lines) - 20} more" if len(lines) > 20 else ""
        info = (
            f"Archive:   {os.path.basename(ctx['archive_path'])}\n"
            f"Location:  /{ctx['subpath']}\n\n"
            + "\n".join(shown) + more +
            f"\n\n{total_files} file(s), total size: {_human_size(total_size)}"
        )
        messagebox.showinfo("Properties (in archive)", info)

    def change_attributes(self):
        """Change Windows attributes (R, H, S, A) and optionally the date.

        Works on the whole selection, not just one item.  Where the selected
        items disagree about a flag, the checkbox starts in a third
        "mixed" state and is left alone unless you actually click it — so
        setting Read-only on ten files cannot silently clear Hidden on three
        of them.
        """
        panel = self.get_active_panel()
        if getattr(panel, "is_remote", False):
            messagebox.showinfo("Info", "Attribute editing is only supported locally.")
            return
        targets = panel.get_all_selected()
        if not targets:
            return

        ATTR_READONLY = 0x01
        ATTR_HIDDEN   = 0x02
        ATTR_SYSTEM   = 0x04
        ATTR_ARCHIVE  = 0x20

        def _get_attrs(path):
            try:
                bits = ctypes.windll.kernel32.GetFileAttributesW(path)
                return 0 if bits == -1 else bits
            except Exception:
                return 0

        many = len(targets) > 1
        title = (f"{len(targets)} items" if many
                 else os.path.basename(targets[0]))

        dlg = tk.Toplevel(self)
        dlg.configure(bg=C_BG)
        dlg.resizable(False, False)
        _setup_toplevel(dlg, f"Change attributes — {title}", self)

        body = tk.Frame(dlg, bg=C_BG, padx=18, pady=14)
        body.pack(fill="both", expand=True)

        tk.Label(body, text=f"🔧  {title}", bg=C_BG, fg=C_ACCENT,
                 font=("Segoe UI", 12, "bold")).pack(anchor="w")
        if many:
            n_dirs = sum(1 for p in targets if os.path.isdir(p))
            tk.Label(body,
                     text=f"{len(targets) - n_dirs} file(s), {n_dirs} folder(s)",
                     bg=C_BG, fg=C_FG_DIM,
                     font=("Segoe UI", 9)).pack(anchor="w", pady=(0, 8))
        else:
            tk.Label(body, text=targets[0], bg=C_BG, fg=C_FG_DIM,
                     font=("Segoe UI", 8)).pack(anchor="w", pady=(0, 8))

        # ── Attribute checkboxes, tri-state when the selection disagrees ──
        FLAG_DEFS = [
            ("R — Read-only", ATTR_READONLY),
            ("H — Hidden",    ATTR_HIDDEN),
            ("S — System",    ATTR_SYSTEM),
            ("A — Archive",   ATTR_ARCHIVE),
        ]
        current = [_get_attrs(p) for p in targets]
        attr_vars, attr_mixed = {}, {}

        frame_attr = tk.Frame(body, bg=C_BG)
        frame_attr.pack(fill="x", pady=(0, 8))
        for label, bit in FLAG_DEFS:
            on = [bool(c & bit) for c in current]
            mixed = any(on) and not all(on)
            var = tk.BooleanVar(value=all(on) if on else False)
            attr_vars[bit] = var
            attr_mixed[bit] = tk.BooleanVar(value=mixed)

            row = tk.Frame(frame_attr, bg=C_BG)
            row.pack(fill="x")
            cb = tk.Checkbutton(row, text=label, variable=var, bg=C_BG, fg=C_FG,
                                selectcolor=C_BG2, activebackground=C_BG,
                                activeforeground=C_FG, anchor="w")
            cb.pack(side="left")
            if mixed:
                lbl = tk.Label(row, text="(mixed — left unchanged)", bg=C_BG,
                               fg=TC_WARN, font=("Segoe UI", 8, "italic"))
                lbl.pack(side="left", padx=6)

                # Touching the box means "I really do want this everywhere"
                def _claim(b=bit, l=lbl):
                    attr_mixed[b].set(False)
                    l.configure(text="(will be applied to all)", fg=TC_OK)
                cb.configure(command=_claim)

        # ── Date ──────────────────────────────────────────────────────────
        tk.Frame(body, bg=C_SEP, height=1).pack(fill="x", pady=6)
        v_setdate = tk.BooleanVar(value=False)
        tk.Checkbutton(body, text="Also set the modified date",
                       variable=v_setdate, bg=C_BG, fg=C_FG, selectcolor=C_BG2,
                       activebackground=C_BG, activeforeground=C_FG,
                       anchor="w").pack(fill="x", pady=(4, 2))

        drow = tk.Frame(body, bg=C_BG)
        drow.pack(fill="x", pady=(0, 4))
        try:
            seed = datetime.fromtimestamp(os.path.getmtime(targets[0]))
        except OSError:
            seed = datetime.now()
        v_date = tk.StringVar(value=f"{seed:%Y-%m-%d}")
        v_time = tk.StringVar(value=f"{seed:%H:%M:%S}")
        tk.Label(drow, text="Date:", bg=C_BG, fg=C_FG, width=6,
                 anchor="w").pack(side="left")
        tk.Entry(drow, textvariable=v_date, width=12, bg=C_BG2, fg=C_FG,
                 insertbackground=C_FG,
                 insertofftime=0, insertontime=9999999).pack(side="left")
        tk.Label(drow, text="Time:", bg=C_BG, fg=C_FG,
                 width=6, anchor="e").pack(side="left", padx=(8, 2))
        tk.Entry(drow, textvariable=v_time, width=10, bg=C_BG2, fg=C_FG,
                 insertbackground=C_FG,
                 insertofftime=0, insertontime=9999999).pack(side="left")
        tk.Button(drow, text="Now", bg="white", fg="black",
                  font=("Segoe UI", 8),
                  command=lambda: (v_date.set(f"{datetime.now():%Y-%m-%d}"),
                                   v_time.set(f"{datetime.now():%H:%M:%S}"),
                                   v_setdate.set(True))).pack(side="left", padx=6)
        tk.Label(body, text="       YYYY-MM-DD and HH:MM:SS",
                 bg=C_BG, fg=C_FG_DIM, font=("Segoe UI", 8),
                 anchor="w").pack(fill="x")

        # ── Recursive ─────────────────────────────────────────────────────
        var_recursive = tk.BooleanVar(value=False)
        has_dir = any(os.path.isdir(p) for p in targets)
        tk.Checkbutton(body, text="Also apply to everything inside selected folders",
                       variable=var_recursive, bg=C_BG, fg=C_FG,
                       selectcolor=C_BG2, activebackground=C_BG,
                       activeforeground=C_FG, anchor="w",
                       state="normal" if has_dir else "disabled").pack(
            fill="x", pady=(8, 4))

        result = tk.Label(body, text="", bg=C_BG, fg=C_FG_DIM,
                          font=("Segoe UI", 9), anchor="w")
        result.pack(fill="x", pady=(4, 0))

        def _apply(event=None):
            stamp = None
            if v_setdate.get():
                try:
                    stamp = datetime.strptime(
                        f"{v_date.get().strip()} {v_time.get().strip()}",
                        "%Y-%m-%d %H:%M:%S").timestamp()
                except ValueError:
                    messagebox.showerror(
                        "Change attributes",
                        "Date or time not understood.\n\n"
                        "Use YYYY-MM-DD and HH:MM:SS.", parent=dlg)
                    return

            # Only the flags that are not left in the "mixed" state
            set_bits, clear_bits = 0, 0
            for _label, bit in FLAG_DEFS:
                if attr_mixed[bit].get():
                    continue                       # disagreed and untouched
                if attr_vars[bit].get():
                    set_bits |= bit
                else:
                    clear_bits |= bit

            def _collect(path):
                yield path
                if var_recursive.get() and os.path.isdir(path):
                    for dirpath, dirs, files in os.walk(path):
                        for n in dirs + files:
                            yield os.path.join(dirpath, n)

            done, failed = 0, []
            for target in targets:
                for path in _collect(target):
                    try:
                        bits = _get_attrs(path)
                        new_bits = (bits | set_bits) & ~clear_bits
                        if new_bits != bits:
                            ok = ctypes.windll.kernel32.SetFileAttributesW(
                                path, new_bits)
                            if not ok:
                                raise OSError("SetFileAttributesW failed")
                        if stamp is not None:
                            os.utime(path, (stamp, stamp))
                        done += 1
                    except Exception as exc:
                        failed.append(f"{os.path.basename(path)}: {exc}")

            self.refresh_panels()
            if failed:
                messagebox.showerror(
                    "Change attributes",
                    f"Changed {done} item(s).\n\nFailed:\n"
                    + "\n".join(failed[:12]), parent=dlg)
            else:
                dlg.destroy()
                _flash_ok(self, f"Changed {done} item(s).", "Attributes")

        btns = tk.Frame(body, bg=C_BG)
        btns.pack(fill="x", pady=(12, 0))
        tk.Button(btns, text="Cancel", bg="grey", fg="white", width=10,
                  command=dlg.destroy).pack(side="right", padx=3)
        tk.Button(btns, text="✔  Apply", bg="lightgreen", fg="black", width=11,
                  command=_apply).pack(side="right", padx=3)
        dlg.bind("<Return>", _apply)


    def _directory_size(self, path):
        total = 0
        for dp, _, fnames in os.walk(path):
            for fn in fnames:
                try:
                    total += os.path.getsize(os.path.join(dp, fn))
                except Exception:
                    pass
        return total

    def pack_files(self):
        panel = self.get_active_panel()
        if getattr(panel, "is_remote", False):
            messagebox.showinfo("Info", "ZIP packing is only supported locally.")
            return
        selected = panel.get_selected()
        if not selected:
            return
        default  = f"{os.path.splitext(os.path.basename(selected))[0]}.zip"
        zip_name = _ask_text(self, "Pack to ZIP", "ZIP filename:", initial=default)
        if not zip_name:
            return

        target = self.choose_save_path(panel.current_path, zip_name)
        os.makedirs(target, exist_ok=True)

        self.task_queue_mgr.add_pack(selected, target, zip_name)
        self._after_task_enqueued("Pack queued")

    def unpack_files(self):
        panel = self.get_active_panel()
        if getattr(panel, "is_remote", False):
            messagebox.showinfo("Info", "Unpacking is only supported locally.")
            return
        selected = panel.get_selected()
        # Used to be ZIP-only — and so was the queue task behind it.  Both
        # handle every supported format now (DEL 20 / DEL 20b).
        if not selected or not is_archive(selected):
            messagebox.showinfo(
                "Info",
                "No supported archive selected.\n\n"
                "Supported: ZIP, RAR, 7z, TAR, GZ, BZ2, XZ, ISO, CAB, ARJ, "
                "LZH, ACE, Z — split sets included.")
            return
        # Unpack goes to the OTHER panel (a second drive unpacks far faster
        # than the one being read from, and "the same folder" is one click
        # away by pointing the other panel at it).  Falls back to this side
        # when the other panel is not showing a plain folder.
        other = self.get_inactive_panel()
        dest  = (other.current_path
                 if (not getattr(other, "is_remote", False)
                     and not getattr(other, "archive_ctx", None)
                     and self.settings.get("unpack_dest_other", True))
                 else panel.current_path)
        target = self.choose_save_path(dest, selected)

        self.task_queue_mgr.add_unpack(selected, target)
        self._after_task_enqueued("Unpack queued")

    def _process_archive_queue(self):
        """Legacy background worker kept for any external callers."""
        while True:
            archive, target_path = self.archive_queue.get()
            try:
                with zipfile.ZipFile(archive) as zf:
                    zf.extractall(target_path)
                self.after(100, self.refresh_panels)
                _log(f"Unpacked {archive} → {target_path}")
            except Exception as exc:
                self.after(100, lambda e=exc, a=archive: messagebox.showerror(
                    "Error", f"Could not unpack {os.path.basename(a)}: {e}"
                ))
            finally:
                self.archive_queue.task_done()

    def _toggle_hidden(self):
        self.settings["show_hidden"] = self._var_show_hidden.get()
        self.refresh_panels()

    def _toggle_system(self):
        self.settings["show_system"] = self._var_show_system.get()
        self.refresh_panels()

    def _toggle_icons(self):
        self.settings["show_icons"] = self._var_show_icons.get()
        self.refresh_panels()

    def _apply_filter(self):
        """Refresh both panels so the current filter text takes effect."""
        self._filter_after_id = None
        self.refresh_panels()

    def _clear_filter(self):
        """Clear the filter field and refresh immediately."""
        self._filter_var.set("")
        if self._filter_after_id:
            self.after_cancel(self._filter_after_id)
            self._filter_after_id = None
        self.refresh_panels()

    # ── Settings persistence ──────────────────────────────────────────────

    def save_settings(self):
        # Fold the live drive memory (a plain dict updated on every step) into
        # the settings first, so ANY save — including the one on close — keeps
        # where each panel was standing on each volume.
        try:
            store = getattr(self, "_drive_last", None)
            if isinstance(store, dict):
                self.settings["drive_last"] = {
                    "left":  dict(store.get("left",  {})),
                    "right": dict(store.get("right", {})),
                }
        except Exception as exc:
            _log(f"Could not fold in the drive memory: {exc}")
        data = {
            "last_positions": {
                "left":  getattr(self.left_panel,  "current_path", DEFAULT_START_DIR),
                "right": getattr(self.right_panel, "current_path", DEFAULT_START_DIR),
            },
            "settings": self.settings,
            "trash":    self._trash,
        }
        try:
            # Portable on the way out: my own paths as {HOME}\..., everyone
            # else's left absolute.  fm_pack_tree returns a copy, so the live
            # settings keep their absolute paths for the rest of the session.
            with open(SETTINGS_PATH, "w", encoding="utf-8") as fh:
                json.dump(fm_pack_tree(data), fh, indent=4, ensure_ascii=False)
        except Exception as exc:
            _log(f"Could not save settings: {exc}")

    def load_settings(self):
        try:
            with open(SETTINGS_PATH, "r", encoding="utf-8") as fh:
                data = fm_unpack_tree(json.load(fh))
                self.last_positions = data.get("last_positions", {})
                self.settings.update(data.get("settings", {}))
                # One-time migration: the first "background queue" version hid the
                # window completely.  That was too much — the window should be
                # visible but non-covering.  Flip the old hidden default ON once
                # (respecting any choice the user makes afterwards).
                if not self.settings.get("_queue_vis_migrated"):
                    self.settings["_queue_vis_migrated"] = True
                # One-time migration (revBS): 📌 On top / ⏱ Top in the queue
                # window, and the tick in Settings ▸ General, all became the
                # ⚡ button's four states.  A ticked "always on top" was
                # "above everything" = state 3; un-ticked was an ordinary
                # window = state 1.
                if not self.settings.get("_queue_mode_migrated"):
                    self.settings["_queue_mode_migrated"] = True
                    if "queue_top_mode" not in data.get("settings", {}):
                        self.settings["queue_top_mode"] = (
                            QUEUE_MODE_OVER_ALL
                            if self.settings.get("queue_always_on_top", True)
                            else QUEUE_MODE_FREE)
                    self.settings.pop("queue_always_on_top", None)
                # One-time migration: the copy throttle used to start after 5
                # seconds and hold a big file at 30 % of full speed for the
                # rest of its life.  A saved settings file still carries those
                # numbers, so raising the defaults alone would help nobody who
                # has ever run the program.  Lift them ONCE, to the "Polite"
                # preset; anything chosen afterwards is left alone.
                if not self.settings.get("_throttle_v2_migrated"):
                    self.settings["_throttle_v2_migrated"] = True
                    if int(self.settings.get("throttle_soft_after_s", 5)) <= 10:
                        self.settings.update(THROTTLE_PRESETS["polite"])
                        _log("Settings: copy throttle lifted to the Polite "
                             "preset (was 5s/60%, 15s/30%, 30s/50%)")
                    if int(self.settings.get("copy_chunk_kb", 1024)) <= 1024:
                        self.settings["copy_chunk_kb"] = 4096
                # One-time migration (revAZ): the percentage cap turned out to
                # be the wrong tool entirely — it never handed a disk request
                # back to anybody, it only made the copy last longer, so the
                # machine stayed clogged for longer the bigger the file was.
                # Background I/O priority + a bounded write cache replace it.
                # A saved settings file still has the cap switched ON, so turn
                # it off ONCE for anyone whose numbers are still the stock
                # Polite ones (custom numbers are somebody's decision — left
                # alone, and the new mechanisms are simply added alongside).
                if not self.settings.get("_throttle_v3_migrated"):
                    self.settings["_throttle_v3_migrated"] = True
                    self.settings.setdefault("io_background", True)
                    self.settings.setdefault("copy_flush_mb", 64)
                    _stock = (int(self.settings.get("throttle_soft_after_s", 0)) == 60
                              and int(self.settings.get("throttle_soft_pct", 0)) == 80
                              and int(self.settings.get("throttle_hard_after_s", 0)) == 300
                              and int(self.settings.get("throttle_hard_pct", 0)) == 60)
                    if _stock and self.settings.get("throttle_enabled"):
                        self.settings["throttle_enabled"] = False
                        self.settings["io_background"]    = True
                        self.settings["copy_flush_mb"]    = 64
                        _log("Settings: copy speed cap replaced by background "
                             "I/O priority + bounded write cache (Polite)")
                # One-time migration: the 0---Python layout. A saved settings
                # file still points the build watch at 1---Blandat and at B:,
                # so changing the defaults alone would help nobody who has ever
                # run the program. Only the exact old values move, and only
                # when the new folder is really there; anything chosen
                # afterwards is left alone.
                if not self.settings.get("_layout_migrated"):
                    self.settings["_layout_migrated"] = True
                    for key, old, new in (
                            ("watch_src_dirs",
                             r"C:\1---Python\1---Blandat", APP_ROOT / "Py"),
                            ("watch_build_dirs",
                             r"B:\0---Burn\0---Util\0---Mina_program",
                             APP_ROOT / "Folder-exe")):
                        cur = self.settings.get(key) or []
                        same = [os.path.normcase(str(x).rstrip("\\"))
                                for x in cur] == [os.path.normcase(old)]
                        if same and new.is_dir():
                            self.settings[key] = [str(new)]
                            _log("Settings: %s moved to %s" % (key, new))
                # Restore soft-delete trash; drop any paths that no longer exist on disk
                saved_trash = data.get("trash", [])
                self._trash = [p for p in saved_trash if os.path.exists(p)]
        except FileNotFoundError:
            # First run — start in the program's own folder
            self.last_positions = {
                "left":  self.settings["start_dir_left"],
                "right": self.settings["start_dir_right"],
            }
        except json.JSONDecodeError:
            messagebox.showerror("Error", "Settings file is corrupted — using defaults.")
            self.last_positions = {
                "left":  self.settings["start_dir_left"],
                "right": self.settings["start_dir_right"],
            }

    # ── Misc operations ───────────────────────────────────────────────────

    def _get_target_path(self, panel):
        """Return path to open terminal in.
        If cursor is on a folder, open inside it.
        If cursor is on a file (or nothing selected), open panel's current dir.
        """
        sel = panel.tree.selection()
        if sel:
            fname = panel._fullname(sel[0])
            if fname and fname != "..":
                candidate = os.path.join(panel.current_path, fname)
                if os.path.isdir(candidate):
                    return candidate
        return panel.current_path

    def open_palette(self):
        """Ctrl+Shift+P — fuzzy-searchable list of everything."""
        CommandPalette(self)

    def open_undo(self):
        """Ctrl+Z — the operation history, newest first."""
        UndoWindow(self)

    # ── "Send to" — hooks into your own programs ─────────────────────────

    def save_tools(self):
        save_tools(self.tools)

    def build_sendto_menu(self):
        """Fill the Send-to submenu with the tools that fit the selection."""
        menu = getattr(self, "_sendto_menu", None)
        if menu is None:
            return
        menu.delete(0, "end")

        panel = self.get_active_panel()
        if getattr(panel, "is_remote", False):
            menu.add_command(label="(not available for FTP panels)",
                             state="disabled")
            return
        try:
            paths = panel.get_all_selected()
        except Exception:
            paths = []

        matching = [t for t in self.tools if tool_matches(t, paths)]
        if matching:
            for tool in matching:
                menu.add_command(label=tool.get("name", ""),
                                 command=lambda t=tool: self.run_tool(t))
            menu.add_separator()
        else:
            menu.add_command(
                label="(no tool matches this file type)", state="disabled")
            menu.add_separator()
        menu.add_command(label="Configure my tools…", command=self.open_tools_config)

    def open_tools_config(self):
        ToolsConfigWindow(self)

    # ── File tags ────────────────────────────────────────────────────────

    def build_tags_menu(self):
        """Fill the Tags submenu, ticking the labels the selection already has."""
        menu = getattr(self, "_tags_menu", None)
        if menu is None:
            return
        menu.delete(0, "end")

        panel = self.get_active_panel()
        if getattr(panel, "is_remote", False):
            menu.add_command(label="(not available for FTP panels)",
                             state="disabled")
            return
        try:
            paths = panel.get_all_selected()
        except Exception:
            paths = []

        if not paths:
            menu.add_command(label="(nothing selected)", state="disabled")
        else:
            _flagged = sum(1 for p in paths if self.tagstore.is_flagged(p))
            _mark = ("✓" if _flagged == len(paths)
                     else ("–" if _flagged else "  "))
            menu.add_command(
                label=f"{_mark}  {FLAG_CHAR}  Flag / unflag  (the ★ column)",
                command=self.toggle_flag_selected)
            menu.add_separator()
            for label in self.tagstore.label_names():
                on_all = all(label in self.tagstore.get(p) for p in paths)
                on_some = any(label in self.tagstore.get(p) for p in paths)
                mark = "✓" if on_all else ("–" if on_some else "  ")
                menu.add_command(
                    label=f"{mark}  ● {label}",
                    foreground=self.tagstore.colour_of(label),
                    command=lambda l=label, p=list(paths): self.toggle_tag(p, l))
            menu.add_separator()
            menu.add_command(label="Clear tags from selection",
                             command=lambda p=list(paths): self.clear_tags(p))
        menu.add_separator()
        menu.add_command(label=f"Clear ALL {FLAG_CHAR} flags…",
                         command=self.clear_all_flags)
        menu.add_command(label="Manage tags…", command=self.open_tags)

    def toggle_tag(self, paths: list, label: str):
        added = self.tagstore.toggle(paths, label)
        self._refresh_and_refocus()
        self._flash_status(
            f"{'Tagged' if added else 'Untagged'} {len(paths)} item(s): {label}")

    def clear_tags(self, paths: list):
        self.tagstore.clear(paths)
        self._refresh_and_refocus()
        self._flash_status(f"Cleared tags from {len(paths)} item(s)")

    # ── The ★ flag (DEL 42b) ─────────────────────────────────────────────
    #
    # Deliberately the smallest possible feature: one button, one column, one
    # tick.  It exists for the working folder you empty a bit at a time — send
    # a file off somewhere, tick it when the answer comes back, and the column
    # shows what is still outstanding without you having to delete anything.

    def toggle_flag_selected(self):
        """Put ★ on the marked / selected rows, or take it off them all."""
        panel = self.get_active_panel()
        if getattr(panel, "is_remote", False):
            messagebox.showinfo(
                "Flag", "The ★ flag is for local files — this panel is on FTP.")
            return
        if getattr(panel, "archive_ctx", None) is not None:
            messagebox.showinfo(
                "Flag", "The ★ flag is for real files — you are inside an archive.")
            return
        try:
            paths = panel.get_all_selected()
        except Exception:
            paths = []
        paths = [p for p in paths if os.path.basename(p) != ".."]
        if not paths:
            self._flash_status("Nothing selected to flag")
            return
        added = self.tagstore.toggle_flags(paths)
        # _refresh_and_refocus, NOT refresh_panels: clicking a ttk.Button moves
        # the keyboard focus onto the button (ttk's own <Button-1> binding does
        # `focus %W`, so -takefocus cannot stop it).  The file list then loses
        # its focus ring, ttk repaints the active panel's selection in its
        # washed-out unfocused colour, and BOTH panels end up looking inactive
        # — with the other panel's grey inactive_sel row the loudest thing on
        # screen.  Handing the keyboard straight back keeps the active side
        # active, and its <FocusIn> re-demotes the other panel.
        self._refresh_and_refocus()
        self._flash_status(
            f"{FLAG_CHAR} {'set on' if added else 'cleared from'} "
            f"{len(paths)} item(s)")

    def clear_flags_selected(self, paths: list):
        self.tagstore.clear_flags(paths)
        self._refresh_and_refocus()
        self._flash_status(f"{FLAG_CHAR} cleared from {len(paths)} item(s)")

    def clear_all_flags(self):
        n = len(getattr(self.tagstore, "flags", ()))
        if not n:
            self._flash_status(f"No {FLAG_CHAR} flags set")
            return
        if not _ask_yes_no(
                "Clear all flags",
                f"Remove the {FLAG_CHAR} flag from all {n} item(s)?\n\n"
                "This only clears the ticks — no file is touched."):
            return
        self.tagstore.clear_all_flags()
        self._refresh_and_refocus()
        self._flash_status(f"Cleared all {n} {FLAG_CHAR} flag(s)")

    def open_tags(self):
        TagManagerWindow(self)

    def open_dates_delete(self):
        """What may change a file's date, and how Delete behaves."""
        DatesDeleteSettingsWindow(self)

    def run_tool(self, tool: dict):
        """Run one Send-to tool against the current selection."""
        panel = self.get_active_panel()
        cwd = panel.current_path
        if not os.path.isdir(cwd):
            cwd = str(APP_ROOT)
        command = expand_command(tool.get("command", ""), self)
        shell = tool.get("shell", "cmd")

        if tool.get("detach", True):
            # Fire and forget — the tool gets its own window
            try:
                subprocess.Popen(_shell_command(shell, command, cwd), cwd=cwd)
                self._flash_status(f"Sent to {tool.get('name', '')}")
            except Exception as exc:
                messagebox.showerror(
                    "Send to",
                    f"Could not start “{tool.get('name', '')}”:\n{exc}")
            return

        # Capture the output in the command bar instead
        self._toolbar_run_command(tool.get("command", ""), shell)

    def open_treemap(self):
        """Ctrl+Alt+D — see what is actually filling the folder."""
        panel = self.get_active_panel()
        if getattr(panel, "is_remote", False):
            messagebox.showinfo("Disk usage",
                                "Disk usage works on local folders only.")
            return
        TreemapWindow(self, panel.current_path)

    def _open_queue_window(self):
        """Open the Task Queue without cycling: lift it to at least state 1.

        The toolbar button does not use this — it cycles — but this is the
        one-line way for any other code to SHOW the queue: it never closes one
        that is already up, and never lowers a state that was chosen."""
        self._set_queue_top_mode(max(QUEUE_MODE_FREE,
                                     self._queue_top_mode_effective()))

    def open_shares(self, host: str = "", hosts: list = None):
        """Browse the SMB shares a machine offers (\\\\server\\Film …)."""
        SharesWindow(self, host=host, hosts=hosts)

    def open_network_window(self):
        """Open the Network window (Scanner tab)."""
        NetworkWindow(self, tab="scan")

    def open_network_locations(self):
        """DEL 46 — the ready-made list of network targets (+ scanning)."""
        NetworkDriveDialog(self, self.active_panel)

    def open_connect_pc(self, on_done=None):
        """DEL 52 — GET IN: pick a PC_connect.json, sign in, save, connect."""
        path = filedialog.askopenfilename(
            parent=self, title="Choose the connection file (PC_connect.json)",
            initialdir=str(HELP_DIR),
            filetypes=[("Connection file", "PC_connect*.json"),
                       ("JSON", "*.json"), ("All files", "*.*")])
        if not path:
            return
        try:
            info = _pcc_read(path)
        except ValueError as exc:
            messagebox.showerror("Connect to a PC", str(exc), parent=self)
            return
        _flash_ok(self, f"Connecting to {info['computer']} …\n"
                        "(up to a minute if the login is wrong)",
                  "Connect to a PC", ms=1800)

        def work():
            try:
                ok, text = _pcc_import(path, keep=True)
            except ValueError as exc:
                ok, text = False, str(exc)
            except Exception as exc:
                ok, text = False, f"Unexpected problem: {exc}"

            def done():
                (messagebox.showinfo if ok else messagebox.showwarning)(
                    "Connect to a PC", text, parent=self)
                if on_done:
                    try:
                        on_done()
                    except Exception:
                        pass
            _ui_call(self, done)

        threading.Thread(target=work, daemon=True).start()

    def open_share_this_pc(self):
        """DEL 52 — SHARE OUT: share this PC's drives for one hidden account."""
        SharePCDialog(self)

    def open_pc_relay(self):
        """DEL 52b — the server that carries the connection files."""
        PcRelayDialog(self)

    def open_portable_devices(self):
        """DEL 47 — phones / cameras that have no drive letter (MTP)."""
        PortableDeviceWindow(self, self.active_panel)

    def open_transfer_presets(self):
        """Open the Transfer Presets window — saved 1-click copy/move jobs."""
        TransferPresetsWindow(self)

    def open_conflict_rules(self):
        """Open the Smart-queue conflict rules window (auto clash policy)."""
        ConflictRulesWindow(self)

    def _net_activate_all_favorites(self):
        """Connect all saved network drive favorites in the background."""
        favs = _net_load_favorites()
        if not favs:
            messagebox.showinfo(
                "Network Favorites",
                "No network drive favorites saved yet.\n\n"
                "Open  NET ▾ → Favorites  to add some.")
            return
        for fav in favs:
            _net_connect_favorite(fav)
        messagebox.showinfo(
            "Activate All Favorites",
            f"Connecting {len(favs)} favorite(s) in the background.\n"
            "Open  NET ▾ → Favorites  to see status.")

    def _net_arp_quickscan(self):
        """Open Network window and immediately run an ARP quick-scan."""
        win = NetworkWindow(self, tab="scan")
        win.after(200, win._arp_scan)

    def open_cmd(self):
        panel = self.get_active_panel()
        if getattr(panel, "is_remote", False):
            messagebox.showinfo("Info", "Command Prompt is only available locally.")
            return
        try:
            path = self._get_target_path(panel)
            ctypes.windll.shell32.ShellExecuteW(
                None, "runas",
                os.environ.get("COMSPEC", r"C:\Windows\System32\cmd.exe"),
                f'/K cd /D "{path}"',
                path, 1
            )
        except Exception as exc:
            messagebox.showerror("Error", f"Could not open terminal: {exc}")

    def open_powershell(self):
        panel = self.get_active_panel()
        if getattr(panel, "is_remote", False):
            messagebox.showinfo("Info", "PowerShell is only available locally.")
            return
        try:
            path = self._get_target_path(panel)
            ctypes.windll.shell32.ShellExecuteW(
                None, "runas", "powershell.exe",
                f"-NoExit -Command Set-Location -LiteralPath '{path}'",
                path, 1
            )
        except Exception as exc:
            messagebox.showerror("Error", f"Could not open PowerShell: {exc}")

    def export_path(self):
        panel = self.get_active_panel()
        if getattr(panel, "is_remote", False):
            sel = panel.get_selected()
            if sel:
                self.clipboard_clear()
                self.clipboard_append(sel[0])
                messagebox.showinfo("Path exported", f"Remote path copied:\n{sel[0]}")
            return
        selected = panel.get_selected()
        if selected:
            self.clipboard_clear()
            self.clipboard_append(selected)
            messagebox.showinfo("Path exported", f"Path copied:\n{selected}")

    def save_selection_to_file(self):
        """Save names of all selected items to a .txt file with format options."""
        panel = self.get_active_panel()
        if getattr(panel, "is_remote", False):
            messagebox.showinfo("Info", "Save selection is only supported locally.")
            return
        paths = panel.get_all_selected()
        if not paths:
            messagebox.showinfo("Info", "No files or folders selected.")
            return

        has_files = any(os.path.isfile(p) for p in paths)
        has_dirs  = any(os.path.isdir(p)  for p in paths)

        dlg = tk.Toplevel(self)
        _setup_toplevel(dlg, "Save Selection to File", self)
        dlg.resizable(False, False)

        body = ttk.Frame(dlg, padding=12)
        body.pack(fill="x")

        ttk.Label(
            body,
            text=f"{len(paths)} item(s) selected.",
            anchor="w"
        ).pack(anchor="w", pady=(0, 8))

        var_ext       = tk.BooleanVar(value=True)
        var_recursive = tk.BooleanVar(value=False)

        if has_files:
            ttk.Label(body, text="Files:", font=("", 0, "bold"), anchor="w").pack(anchor="w")
            ttk.Checkbutton(
                body, text="Include file extensions", variable=var_ext
            ).pack(anchor="w", padx=14)

        if has_dirs:
            ttk.Label(body, text="Folders:", font=("", 0, "bold"), anchor="w").pack(
                anchor="w", pady=(8 if has_files else 0, 0))
            ttk.Checkbutton(
                body,
                text="Include all contents (recursive)",
                variable=var_recursive
            ).pack(anchor="w", padx=14)

        lbl_st = ttk.Label(dlg, text="", anchor="w")
        lbl_st.pack(fill="x", padx=12, pady=(0, 4))

        def _do_save():
            out_path = filedialog.asksaveasfilename(
                parent=dlg,
                title="Save selection list as…",
                defaultextension=".txt",
                filetypes=[("Text files", "*.txt"), ("All files", "*.*")],
                initialfile="selection.txt",
            )
            if not out_path:
                return
            lines = []
            for p in paths:
                if os.path.isfile(p):
                    name = os.path.basename(p)
                    if not var_ext.get():
                        name = os.path.splitext(name)[0]
                    lines.append(name)
                elif os.path.isdir(p):
                    lines.append(os.path.basename(p))
                    if var_recursive.get():
                        base_parent = os.path.dirname(p)
                        for root, subdirs, files in os.walk(p):
                            subdirs.sort(key=str.lower)
                            rel = os.path.relpath(root, base_parent)
                            for fn in sorted(files, key=str.lower):
                                lines.append(f"  {os.path.join(rel, fn)}")
            try:
                with open(out_path, "w", encoding="utf-8") as fh:
                    fh.write("\n".join(lines) + "\n")
                dlg.destroy()
                messagebox.showinfo("Saved", f"Selection saved to:\n{out_path}")
            except Exception as exc:
                lbl_st.configure(text=f"Error: {exc}")

        btn_row = ttk.Frame(dlg, padding=(12, 6))
        btn_row.pack(fill="x")
        ttk.Button(btn_row, text="Save…",  command=_do_save,      width=12).pack(side="left")
        ttk.Button(btn_row, text="Cancel", command=dlg.destroy,   width=10).pack(side="right")

    def copy_paths_to_clipboard(self):
        """Copy full paths of all selected items to the system clipboard."""
        panel = self.get_active_panel()
        if getattr(panel, "is_remote", False):
            sel = panel.get_selected()
            if sel:
                self.clipboard_clear()
                self.clipboard_append(sel[0])
                messagebox.showinfo("Copied", f"Path copied:\n{sel[0]}")
            return
        paths = panel.get_all_selected()
        if not paths:
            messagebox.showinfo("Info", "No files or folders selected.")
            return
        self.clipboard_clear()
        self.clipboard_append("\n".join(paths))
        n = len(paths)
        messagebox.showinfo(
            "Copied",
            f"{n} path{'s' if n != 1 else ''} copied to clipboard."
        )

    def copy_selection_to_clipboard(self, mode: str = "full"):
        """Right-click ▸ 📋 Copy to clipboard  (revBK).

        Every marked row, one per line, in one of five shapes.  All five menu
        entries come through here so they cannot drift apart later.
        """
        panel  = self.get_active_panel()
        remote = bool(getattr(panel, "is_remote", False))
        if remote:
            sel   = panel.get_selected()
            paths = [sel[0]] if sel else []
            sep   = "/"
        else:
            paths = panel.get_all_selected()
            sep   = os.sep

        if not paths:
            self._flash_status("Copy to clipboard — nothing is selected.")
            return

        def _split(p):
            """(folder, name) without os.path, so an FTP path splits on / too."""
            body = p.rstrip(sep) or p
            head, found, tail = body.rpartition(sep)
            if not found:
                return "", body
            return (head or sep), tail

        lines = []
        for p in paths:
            folder, name = _split(p)
            if mode == "name":
                lines.append(name)
            elif mode == "stem":
                # A folder called "My.Backup" has no extension to drop, and
                # ".gitignore" is a name, not an empty string.
                is_dir = (not remote) and os.path.isdir(p)
                if is_dir or "." not in name[1:]:
                    lines.append(name)
                else:
                    lines.append(name.rsplit(".", 1)[0])
            elif mode == "quoted":
                lines.append(f'"{p}"')
            elif mode == "folder":
                if folder and folder not in lines:   # one folder, not N copies
                    lines.append(folder)
            else:
                lines.append(p)

        text = "\n".join(lines)
        if not _to_clipboard(text):
            # Windows would not release the clipboard — Tk still works while
            # this program is open, which beats copying nothing at all.
            try:
                self.clipboard_clear()
                self.clipboard_append(text)
            except Exception as exc:
                messagebox.showerror("Copy to clipboard",
                                     f"Could not copy:\n{exc}")
                return

        what = {"name":   "file name",
                "stem":   "name",
                "quoted": "quoted path",
                "folder": "folder",
                "full":   "full path"}.get(mode, "path")
        n = len(lines)
        self._flash_status(
            f"📋  Copied {n} {what}{'s' if n != 1 else ''} "
            f"to the clipboard.")

    def copy_names_to_clipboard(self):
        """Names only, for the toolbar and the command palette — both call
        their action methods with no arguments, so the mode cannot be passed
        in from there."""
        self.copy_selection_to_clipboard("name")

    def copy_folders_to_clipboard(self):
        """The folder of each marked file, duplicates collapsed."""
        self.copy_selection_to_clipboard("folder")

    # ── Tab bar ───────────────────────────────────────────────────────────

    def _make_tab_scroller(self, holder, side: str):
        """Build a horizontally-scrollable strip for one panel's tabs and
        return the INNER frame that _render_tab_bar fills with tab widgets.

        A long row of tabs can be scrolled with the mouse wheel while the
        pointer is over the strip, and a thin scrollbar appears automatically
        only when the tabs are wider than the visible strip.
        """
        wrap = tk.Frame(holder, bg=C_BG2)
        wrap.pack(fill="x")

        canvas = tk.Canvas(wrap, bg=C_BG2, height=26, highlightthickness=0,
                           bd=0, takefocus=0)
        hbar = ttk.Scrollbar(wrap, orient="horizontal", command=canvas.xview)
        canvas.configure(xscrollcommand=lambda lo, hi, s=side: self._tab_scroll_set(s, lo, hi))
        canvas.pack(side="top", fill="x")
        # hbar is packed / unpacked on demand by _tab_scroll_set

        inner = tk.Frame(canvas, bg=C_BG2)
        win_id = canvas.create_window((0, 0), window=inner, anchor="nw")

        def _on_inner_config(_e=None):
            canvas.configure(scrollregion=canvas.bbox("all"))
            # Keep the strip exactly as tall as the tabs need
            h = max(24, inner.winfo_reqheight())
            canvas.configure(height=h)

        inner.bind("<Configure>", _on_inner_config)
        canvas.bind("<Configure>", lambda e: _on_inner_config())

        # Mouse-wheel = horizontal scroll while the pointer is over the strip
        def _wheel(e):
            if canvas.bbox("all") is None:
                return
            first, last = canvas.xview()
            if first <= 0.0 and last >= 1.0:
                return   # nothing to scroll
            canvas.xview_scroll(-1 if e.delta > 0 else 1, "units")
            return "break"

        for w in (canvas, inner):
            w.bind("<MouseWheel>", _wheel)

        # Stash references for scrollbar management + auto-scroll-to-active
        if side == "left":
            self._tabbar_left_canvas, self._tabbar_left_wrap, self._tabbar_left_hbar = canvas, wrap, hbar
        else:
            self._tabbar_right_canvas, self._tabbar_right_wrap, self._tabbar_right_hbar = canvas, wrap, hbar
        self._tab_wheel = _wheel   # reused for the tab widgets in _render_tab_bar
        return inner

    def _tab_scroll_set(self, side: str, lo, hi):
        """xscrollcommand: show the thin scrollbar only when the tabs overflow."""
        canvas = self._tabbar_left_canvas if side == "left" else self._tabbar_right_canvas
        hbar   = self._tabbar_left_hbar   if side == "left" else self._tabbar_right_hbar
        hbar.set(lo, hi)
        overflow = not (float(lo) <= 0.0 and float(hi) >= 1.0)
        mapped = bool(hbar.winfo_ismapped())
        if overflow and not mapped:
            hbar.pack(side="bottom", fill="x")
        elif not overflow and mapped:
            hbar.pack_forget()

    def _scroll_active_tab_into_view(self, side: str):
        """Make sure the active tab is visible in the (possibly scrolled) strip."""
        canvas = self._tabbar_left_canvas if side == "left" else self._tabbar_right_canvas
        frame  = self._tabbar_left_frame  if side == "left" else self._tabbar_right_frame
        idx    = self.left_tab_idx if side == "left" else self.right_tab_idx
        try:
            kids = [w for w in frame.winfo_children()]
            # tab frames are packed first, in order, before ＋ / ↩ buttons
            if idx < 0 or idx >= len(kids):
                return
            canvas.update_idletasks()
            total = frame.winfo_width() or 1
            tabw  = kids[idx]
            x0 = tabw.winfo_x()
            x1 = x0 + tabw.winfo_width()
            view0 = canvas.canvasx(0)
            view1 = view0 + canvas.winfo_width()
            if x0 < view0:
                canvas.xview_moveto(max(0.0, x0 / total))
            elif x1 > view1:
                canvas.xview_moveto(max(0.0, (x1 - canvas.winfo_width()) / total))
        except Exception:
            pass

    # ── per-tab metadata helpers ──────────────────────────────────────────

    def _tabs_meta(self, side: str) -> list:
        """The metadata list parallel to left_tabs / right_tabs."""
        return self.left_tab_meta if side == "left" else self.right_tab_meta

    def _sync_tab_meta(self, side: str, default_saved: bool = False):
        """Keep the metadata list the same length as its tab list.  New slots
        get {saved: default_saved, locked: False, sort: None} so a freshly
        opened tab is temporary and unprotected by default."""
        tabs = self.left_tabs if side == "left" else self.right_tabs
        meta = self._tabs_meta(side)
        while len(meta) < len(tabs):
            meta.append({"saved": default_saved, "locked": False,
                         "sort": None})
        while len(meta) > len(tabs):
            meta.pop()

    def _render_tab_bar(self, side: str):
        """Redraw the tab strip for one panel side."""
        frame = self._tabbar_left_frame if side == "left" else self._tabbar_right_frame
        tabs  = self.left_tabs    if side == "left" else self.right_tabs
        idx   = self.left_tab_idx if side == "left" else self.right_tab_idx
        self._sync_tab_meta(side)
        meta  = self._tabs_meta(side)
        ws_active = self._ws_active.get(side, False)

        for w in frame.winfo_children():
            w.destroy()

        for i, path in enumerate(tabs):
            label    = os.path.basename(path) or path
            is_active = (i == idx)
            # "Temporary" only means something once a Workspace is in play:
            # a tab that is not part of it.  Outside Workspace mode, tabs are
            # neutral and always closable.
            is_saved  = meta[i].get("saved", False)
            is_temp   = ws_active and not is_saved
            # Protection is YOUR choice, one tab at a time, set from the
            # right-click menu — no longer a side effect of which Workspace
            # the tab happens to belong to.
            is_locked = bool(meta[i].get("locked", False))
            # A tab that points somewhere on the NETWORK is teal and carries a
            # 🌐, active or not — the one thing you want to see BEFORE dropping
            # nine gigabytes on it.  Temporary (amber) still wins on an
            # inactive tab, because that marking is about losing the tab
            # itself; the globe is always in the label either way.
            is_net = _is_network_path(path)

            # Temporary (unsaved) tabs are tinted amber and carry a "○" marker.
            if is_active:
                bg = NET_TAB_ACTIVE_BG if is_net else C_ACCENT
                fg = C_BG
                border = ("#d08a00" if is_temp
                          else NET_TAB_BORDER if is_net else C_ACCENT)
            elif is_temp:
                bg = "#3a3020"      # muted amber for an inactive temporary tab
                fg = "#f0c060"
                border = "#d08a00"
            elif is_net:
                bg = NET_TAB_BG
                fg = NET_TAB_FG
                border = NET_TAB_BORDER
            else:
                bg = C_BG3
                fg = C_FG
                border = C_SEP
            # A locked tab keeps its own colours and takes a steady gold
            # border on top, so "protected" reads at a glance in every state.
            if is_locked:
                border = LOCK_TAB_BORDER

            tab_f = tk.Frame(frame, bg=bg, padx=0, pady=0,
                             highlightthickness=1,
                             highlightbackground=border)
            tab_f.pack(side="left", padx=1, pady=1)

            marker = ((LOCK_TAB_CHAR + " " if is_locked else "")
                      + ("○ " if is_temp else "")
                      + (NET_TAB_CHAR + " " if is_net else ""))
            name_lbl = tk.Label(tab_f, text=f" {marker}{label} ",
                                bg=bg, fg=fg,
                                font=("", 9, "bold" if is_active else "normal"),
                                cursor="hand2")
            name_lbl.pack(side="left")
            name_lbl.bind("<Button-1>",
                          lambda e, s=side, i_=i: self._switch_to_tab(s, i_))
            name_lbl.bind("<Button-3>",
                          lambda e, s=side, i_=i, p=path:
                              self._tab_context_menu(e, p, s, i_))
            # Hover the tab to read its full path
            tip = path
            if is_net:
                tip += "\n🌐  Network location — files travel over the wire"
            if is_temp:
                tip += "\n(temporary — re-save the Workspace to keep it)"
            if is_locked:
                tip += "\n🔒  Locked — right-click ▸ Unlock this tab first"
            tip += ("\nRight-click:  close / lock / duplicate / "
                    "move to the other side / pair")
            self._create_tooltip(name_lbl, tip)

            # There is NO ✕ on a tab any more.  It was an 8-pixel target one
            # millimetre from the tab you meant to click, and on a Workspace
            # tab it was hidden altogether — so the one thing you wanted (close
            # this) was the one thing you could not do.  Closing lives in the
            # right-click menu now, and on Ctrl+W.

        # ＋ new-tab button
        plus = tk.Label(frame, text=" ＋ ", bg=C_BG2, fg=C_FG_DIM,
                        font=("", 9), cursor="hand2")
        plus.pack(side="left", padx=(3, 1), pady=1)
        plus.bind("<Button-1>", lambda e, s=side: self._add_new_tab_side(s))

        # ↩ reopen-last-closed button (visible only when there is history)
        if self.closed_tabs:
            undo = tk.Label(frame, text=" ↩ ", bg=C_BG2, fg=C_FG_DIM,
                            font=("", 9), cursor="hand2")
            undo.pack(side="left", padx=1, pady=1)
            undo.bind("<Button-1>", lambda e: self._reopen_last_tab())
            self._create_tooltip(undo, "Reopen closed tab  (Ctrl+Shift+T)")

        # Let the mouse wheel scroll the strip even when the pointer is over a
        # tab (not just the empty gaps), and keep the active tab in view.
        wheel = getattr(self, "_tab_wheel", None)
        if wheel:
            def _bind_wheel(widget):
                widget.bind("<MouseWheel>", wheel)
                for child in widget.winfo_children():
                    _bind_wheel(child)
            for w in frame.winfo_children():
                _bind_wheel(w)
        self.after_idle(lambda s=side: self._scroll_active_tab_into_view(s))

    # ── internal helpers ──────────────────────────────────────────────────

    def _apply_tab_sort(self, side: str):
        """Push the active tab's remembered sort onto its panel (or the default)."""
        self._sync_tab_meta(side)
        meta  = self._tabs_meta(side)
        idx   = self.left_tab_idx if side == "left" else self.right_tab_idx
        panel = self.left_panel if side == "left" else self.right_panel
        if not hasattr(panel, "set_sort_state"):
            return   # e.g. an FTP panel
        if 0 <= idx < len(meta):
            panel.set_sort_state(meta[idx].get("sort"))

    def _on_panel_sort_changed(self, side: str):
        """A panel's sort was changed by the user — remember it on the active
        tab (session only; persisted when the Workspace is re-saved)."""
        self._sync_tab_meta(side)
        meta  = self._tabs_meta(side)
        idx   = self.left_tab_idx if side == "left" else self.right_tab_idx
        panel = self.left_panel if side == "left" else self.right_panel
        if 0 <= idx < len(meta) and hasattr(panel, "get_sort_state"):
            meta[idx]["sort"] = panel.get_sort_state()
        # An extra tab's sort is auto-remembered in the Workspace; a base tab's
        # sort still needs an explicit re-save.
        self._ws_autosave_extras(side)
        base_tab = 0 <= idx < len(meta) and meta[idx].get("saved", False)
        if base_tab and not getattr(self, "_sort_hint_shown", False):
            self._sort_hint_shown = True
            self._flash_status(
                "Sort remembered for this tab — re-save the Workspace to keep it.")

    def _switch_to_tab(self, side: str, idx: int):
        """Activate a specific tab on the given panel side."""
        tabs = self.left_tabs if side == "left" else self.right_tabs
        if idx < 0 or idx >= len(tabs):
            return
        if side == "left":
            self.left_tab_idx = idx
        else:
            self.right_tab_idx = idx
        panel = self.left_panel if side == "left" else self.right_panel
        self._apply_tab_sort(side)
        # The folder may have been deleted while this tab sat in the strip.
        # Land on the nearest one that still exists instead of making the panel
        # discover it the hard way (revBU).
        #
        # THE MUTATION THAT COST THE PATH (2026-09-18).  This used to read
        #     tabs[idx] = want = up
        # — it did not merely OPEN the nearest surviving parent, it wrote that
        # parent back into the live tab list.  The original path was then gone
        # from memory, and because tabs are half-saved as you work, the next
        # automatic save wrote the parent into workspaces.json for good.  A
        # folder that was only temporarily away — an unplugged disk, a share
        # that was down — took its saved path with it.
        # So: go to the parent, remember WHY, and leave the saved path alone.
        # _tab_missing is what makes "keep as importable" possible at all;
        # anything that writes tabs back out asks it first.
        want = tabs[idx]
        if not getattr(panel, "is_remote", False) and not _path_is_network(want):
            try:
                if not os.path.isdir(want):
                    up = _nearest_existing_dir(want)
                    if up:
                        _log(f"Tab {side}#{idx}: {want!r} is gone — "
                             f"opening {up!r}, saved path kept")
                        self._mark_tab_missing(side, idx, want)
                        want = up
                else:
                    self._clear_tab_missing(side, idx)
            except Exception:
                pass
        panel.change_directory(want)
        # _on_panel_navigate will re-render the bar
        # Flash the full path so it is easy to see (and to quote) where you are
        self._flash_status(want)

    # ── Tabs whose folder is not there  (2026-09-18) ──────────────────────
    #
    # A tab is "missing" when its SAVED path does not exist but the tab is
    # still worth keeping — an unplugged disk, a share that is down, a folder
    # you have not made yet.  The panel shows the nearest surviving parent so
    # you are not left staring at nothing, while the saved path stays exactly
    # as saved, so the Workspace can be re-imported the moment the folder is
    # back.  Keeping the two apart is the whole point: the old code conflated
    # them and lost the path.

    def _missing_map(self, side: str) -> dict:
        if not hasattr(self, "_tab_missing"):
            self._tab_missing = {"left": {}, "right": {}}
        return self._tab_missing.setdefault(side, {})

    def _mark_tab_missing(self, side: str, idx: int, saved_path: str):
        self._missing_map(side)[idx] = saved_path

    def _clear_tab_missing(self, side: str, idx: int):
        self._missing_map(side).pop(idx, None)

    def _tab_missing_path(self, side: str, idx: int) -> str:
        """The saved path of a tab whose folder is away, or "" if it is fine."""
        return self._missing_map(side).get(idx, "")

    def _missing_kind(self, path: str) -> str:
        """Why a path is unreachable — the answer decides what may be OFFERED.

        "offline" must never be offered a Create button.  Making D:\\Old\\Temp
        on whatever disk happens to hold the letter D: today is how a Workspace
        ends up quietly pointing at a stranger's drive, and making a folder on
        a share that is merely down is not ours to do either.
        """
        try:
            if _path_is_network(path):
                return "offline"
            root = os.path.splitdrive(os.path.abspath(path))[0]
            if root and not os.path.isdir(root + "\\"):
                return "offline"          # the drive letter itself is not there
        except Exception:
            return "offline"
        return "creatable"

    def _scan_missing_tabs(self) -> list:
        """[(side, idx, path, kind)] for every tab whose folder is not there."""
        out = []
        for side in ("left", "right"):
            panel = self.left_panel if side == "left" else self.right_panel
            if getattr(panel, "is_remote", False):
                continue
            tabs = self.left_tabs if side == "left" else self.right_tabs
            for idx, p in enumerate(list(tabs)):
                try:
                    if _path_is_network(p) or os.path.isdir(p):
                        continue
                except Exception:
                    continue
                out.append((side, idx, p, self._missing_kind(p)))
        return out

    def check_workspace_folders(self, ws_name: str = ""):
        """One dialog for ALL the folders a Workspace could not find.

        Asked for on 2026-09-18: if the folders do not exist when the program
        starts, be given the chance to create them, or to keep them as
        importable — instead of each panel silently landing somewhere else and
        only the log knowing.  One window for the lot, not one per tab.
        """
        gone = self._scan_missing_tabs()
        if not gone:
            return
        for side, idx, p, _k in gone:
            self._mark_tab_missing(side, idx, p)

        dlg = tk.Toplevel(self)
        title = (f'Workspace "{ws_name}" — {len(gone)} folder(s) not there'
                 if ws_name else f"{len(gone)} tab folder(s) not there")
        _setup_toplevel(dlg, title, self, modal=True)
        dlg.resizable(True, True)
        dlg.minsize(640, 260)

        tk.Label(dlg, text=title, bg=dlg["bg"], fg=C_FG, anchor="w",
                 font=("Segoe UI", 10, "bold")).pack(fill="x", padx=12, pady=(12, 2))
        tk.Label(dlg,
                 text="Nothing has been changed yet — the saved paths are "
                      "still exactly as saved.",
                 bg=dlg["bg"], fg="#9a9a9a", anchor="w",
                 font=("Segoe UI", 9)).pack(fill="x", padx=12, pady=(0, 8))

        frm = ttk.Frame(dlg)
        frm.pack(fill="both", expand=True, padx=10)
        cols = ("side", "path", "why")
        tree = ttk.Treeview(frm, columns=cols, show="headings", height=8)
        tree.heading("side", text="Panel")
        tree.heading("path", text="Saved folder")
        tree.heading("why",  text="Why")
        tree.column("side", width=60,  stretch=False, anchor="w")
        tree.column("path", width=420, stretch=True,  anchor="w")
        tree.column("why",  width=180, stretch=False, anchor="w")
        vsb = ttk.Scrollbar(frm, orient="vertical", command=tree.yview)
        tree.configure(yscrollcommand=vsb.set)
        vsb.pack(side="right", fill="y")
        tree.pack(fill="both", expand=True)

        creatable = 0
        for side, idx, p, kind in gone:
            why = ("drive or share not reachable" if kind == "offline"
                   else "folder does not exist")
            if kind == "creatable":
                creatable += 1
            tree.insert("", "end", values=(side.upper(), p, why))

        ttk.Separator(dlg, orient="horizontal").pack(fill="x", padx=10, pady=8)
        btns = ttk.Frame(dlg)
        btns.pack(padx=12, pady=(0, 12), anchor="w")

        def _finish(what):
            dlg.destroy()
            if what == "create":
                made, failed = [], []
                for side, idx, p, kind in gone:
                    if kind != "creatable":
                        continue
                    try:
                        os.makedirs(p, exist_ok=True)
                        made.append(p)
                        self._clear_tab_missing(side, idx)
                    except Exception as exc:
                        failed.append(f"{p}  —  {exc}")
                msg = f"Created {len(made)} folder(s)."
                if failed:
                    msg += "\n\nCould not create:\n" + "\n".join(failed)
                messagebox.showinfo("Workspace folders", msg, parent=self)
                self._render_tab_bar("left"); self._render_tab_bar("right")
            elif what == "remove":
                # Drop them from the END backwards so the earlier indices in
                # this list stay valid while we go.
                for side, idx, _p, _k in sorted(gone, key=lambda g: -g[1]):
                    try:
                        self._close_tab(side, idx)
                    except Exception:
                        pass
                self._render_tab_bar("left"); self._render_tab_bar("right")
            else:
                # "keep" — the tabs stay, showing the nearest surviving parent,
                # with their saved paths untouched and importable.
                self._render_tab_bar("left"); self._render_tab_bar("right")

        b_create = ttk.Button(btns, text="Create the missing folders",
                              width=26, command=lambda: _finish("create"))
        b_create.grid(row=0, column=0, padx=4)
        if not creatable:
            b_create.state(["disabled"])
            tk.Label(btns, text="nothing here is ours to create",
                     bg=dlg["bg"], fg="#9a9a9a", font=("Segoe UI", 8)
                     ).grid(row=1, column=0, padx=4, sticky="w")
        ttk.Button(btns, text="Keep as importable", width=22,
                   command=lambda: _finish("keep")).grid(row=0, column=1, padx=4)
        ttk.Button(btns, text="Remove these tabs", width=20,
                   command=lambda: _finish("remove")).grid(row=0, column=2, padx=4)

        dlg.protocol("WM_DELETE_WINDOW", lambda: _finish("keep"))
        dlg.wait_window()

    def _add_new_tab_side(self, side: str):
        """Clone the current tab on the given side and switch to the clone.

        The clone is TEMPORARY (unsaved) — it carries the amber "○" marker
        until the Workspace is (re-)saved."""
        panel = self.left_panel if side == "left" else self.right_panel
        path  = panel.current_path
        tabs  = self.left_tabs if side == "left" else self.right_tabs
        meta  = self._tabs_meta(side)
        sort_now = panel.get_sort_state() if hasattr(panel, "get_sort_state") else None
        tabs.append(path)
        meta.append({"saved": False, "sort": sort_now})
        new_idx = len(tabs) - 1
        if side == "left":
            self.left_tab_idx = new_idx
        else:
            self.right_tab_idx = new_idx
        # Navigate to the same path so the tab bar re-renders via the hook
        panel.change_directory(path)

    def _close_tab(self, side: str, idx: int):
        """Close tab at idx; push its path onto the closed-tab history."""
        tabs = self.left_tabs if side == "left" else self.right_tabs
        meta = self._tabs_meta(side)
        if len(tabs) <= 1:
            return   # keep at least one tab open
        # What protects a tab is its own LOCK (right-click ▸ 🔒 Lock this
        # tab) — not membership of a Workspace.  Closing a Workspace tab never
        # rewrote the saved profile anyway; only an explicit Save / Update
        # does that.  "Ignore tab locks" overrides the lock for a one-off
        # clear-out without unlocking anything.
        if (0 <= idx < len(meta) and meta[idx].get("locked", False)
                and not self._ws_unlock.get()):
            self._flash_status(
                "This tab is locked 🔒 — right-click it and choose "
                "“Unlock this tab”, or tick “Ignore tab locks”.")
            return
        # If a tab pair links this tab's folder AND no other tab on this side
        # shows the same folder, warn before breaking the pair (see the method).
        if not self._confirm_close_linked_tab(side, idx):
            return
        closed_path = tabs[idx]
        # Add to history (most recent last; max 30 entries)
        self.closed_tabs.append(closed_path)
        if len(self.closed_tabs) > 30:
            self.closed_tabs.pop(0)
        tabs.pop(idx)
        if idx < len(meta):
            meta.pop(idx)
        cur = self.left_tab_idx if side == "left" else self.right_tab_idx
        if cur >= len(tabs):
            cur = len(tabs) - 1
        elif cur > idx:
            cur -= 1
        if side == "left":
            self.left_tab_idx = cur
        else:
            self.right_tab_idx = cur
        panel = self.left_panel if side == "left" else self.right_panel
        self._apply_tab_sort(side)
        panel.change_directory(tabs[cur])

    def _toggle_tab_lock(self, side: str, idx: int):
        """Right-click ▸ lock / unlock ONE tab.  A locked tab carries a 🔒 and
        a gold border and refuses to close — by Ctrl+W, by the context menu or
        by a bulk close — until you unlock it (or tick "Ignore tab locks").
        The lock is remembered with the Workspace, so a profile can pin the
        folders you never want to lose while its other tabs stay disposable."""
        self._sync_tab_meta(side)
        meta = self._tabs_meta(side)
        if not (0 <= idx < len(meta)):
            return
        now = not bool(meta[idx].get("locked", False))
        meta[idx]["locked"] = now
        tabs = self.left_tabs if side == "left" else self.right_tabs
        name = os.path.basename(tabs[idx]) or tabs[idx]
        self._render_tab_bar(side)
        # Persist it AT ONCE.  Locking is a deliberate, rare act, so it must
        # not wait out the 60 s reorder debounce — _ws_save_order writes the
        # whole side (paths + sorts + locks) and returns immediately when no
        # Workspace is loaded, and _ws_autosave_extras covers the extra tabs.
        self._ws_autosave_extras(side)
        self._ws_save_order(side)
        self._flash_status(
            f"Tab '{name}' {'locked 🔒' if now else 'unlocked 🔓'}")

    def _close_tabs_bulk(self, side: str, idx: int, which: str):
        """Close several tabs at once — "others" (everything except the one you
        right-clicked) or "right" (everything after it).  Locked tabs are kept
        and counted in the question, because this is the one tab action that
        can throw away a lot of work in a single click."""
        self._sync_tab_meta(side)
        tabs = self.left_tabs if side == "left" else self.right_tabs
        meta = self._tabs_meta(side)
        override = self._ws_unlock.get()
        candidates = ([j for j in range(idx + 1, len(tabs))] if which == "right"
                      else [j for j in range(len(tabs)) if j != idx])
        victims = [j for j in candidates
                   if override or not meta[j].get("locked", False)]
        if not victims:
            return
        kept = len(candidates) - len(victims)
        note = f"\n\n{kept} locked tab(s) will be kept." if kept else ""
        if not _ask_yes_no(
                "Close tabs",
                f"Close {len(victims)} tab(s) on the {side} panel?{note}",
                parent=self):
            return
        # Highest index first, so the lower indices stay valid as we go.
        for j in sorted(victims, reverse=True):
            self._close_tab(side, j)

    # ── Duplicate / move to the other side (rev BL) ───────────────────────

    def _tab_meta_copy(self, side: str, idx: int) -> dict:
        """The settings a copied or moved tab takes along: its lock and its
        sort (the LIVE sort when it is the active tab — the remembered one can
        be a click behind).  Never "saved": only Save / Update makes a
        Workspace BASE tab, so a new tab is an extra wherever it lands."""
        import copy as _copy
        self._sync_tab_meta(side)
        meta  = self._tabs_meta(side)
        sorts = self._current_tab_sorts(side)
        m = _copy.deepcopy(meta[idx]) if 0 <= idx < len(meta) else {}
        m["saved"]  = False
        m["locked"] = bool(m.get("locked", False))
        m["sort"]   = _copy.deepcopy(sorts[idx]) if 0 <= idx < len(sorts) else None
        return m

    def _other_side_takes_tab(self, side: str) -> tuple:
        """(True, "") when a tab on *side* can be shown on the other side;
        otherwise (False, reason) for the greyed menu line.  Deliberately no
        disk access here — the menu must open at once even when the tab
        points at a network share that has gone away."""
        other = "right" if side == "left" else "left"
        this_panel  = self.left_panel if side == "left" else self.right_panel
        other_panel = self.right_panel if side == "left" else self.left_panel
        if not isinstance(this_panel, FilePanel):
            return False, "this side is an FTP site"
        if not isinstance(other_panel, FilePanel):
            return False, f"the {other} side is an FTP site"
        return True, ""

    def _duplicate_tab(self, side: str, idx: int):
        """Right-click ▸ Duplicate: one more copy of THIS tab, added LAST on
        the same side — same folder, same sort, same lock.  You stay on the
        tab you were on; the copy just appears at the end of the strip."""
        self._sync_tab_meta(side)
        tabs = self.left_tabs if side == "left" else self.right_tabs
        meta = self._tabs_meta(side)
        if not (0 <= idx < len(tabs)):
            return
        m = self._tab_meta_copy(side, idx)
        tabs.append(tabs[idx])
        meta.append(m)
        self._render_tab_bar(side)
        self._ws_autosave_extras(side)
        name = os.path.basename(tabs[idx]) or tabs[idx]
        self._flash_status(
            f"Tab '{name}' duplicated — the copy is last on the {side} side"
            + ("  (locked 🔒, like the original)" if m["locked"] else ""))

    def _move_tab_to_other_side(self, side: str, idx: int):
        """Right-click ▸ Move to the other panel.  The tab leaves this strip
        and is added LAST on the other one, which switches to it.

        A LOCKED tab is COPIED instead.  The lock means "this tab stays here",
        so moving it would break that promise without a word; the other side
        gets a copy (locked too — same settings) and the original stays.
        Unlock it first to really move it.  The last tab on a side is copied
        the same way, because a side always keeps one tab (Close refuses it
        too).  "Ignore tab locks" is NOT consulted: it is for clearing tabs
        out, not for moving them around."""
        self._sync_tab_meta(side)
        other = "right" if side == "left" else "left"
        tabs  = self.left_tabs if side == "left" else self.right_tabs
        meta  = self._tabs_meta(side)
        if not (0 <= idx < len(tabs)):
            return
        ok, why = self._other_side_takes_tab(side)
        if not ok:
            self._flash_status(f"This tab cannot go to the {other} side — {why}.")
            return
        path = tabs[idx]
        name = os.path.basename(path) or path
        if not os.path.isdir(path):
            self._flash_status(
                f"Folder not found — nothing to show on the {other} side:  {path}")
            return
        locked    = bool(meta[idx].get("locked", False))
        copy_only = locked or len(tabs) <= 1
        # A real move takes the folder off this side, which is exactly what
        # Close does to an F8 pair — so it asks the same question.
        if not copy_only and not self._confirm_close_linked_tab(side, idx):
            return
        m = self._tab_meta_copy(side, idx)

        if not copy_only:
            cur = self.left_tab_idx if side == "left" else self.right_tab_idx
            was_active = (cur == idx)
            tabs.pop(idx)
            meta.pop(idx)
            if cur >= len(tabs):
                cur = len(tabs) - 1
            elif cur > idx:
                cur -= 1
            if side == "left":
                self.left_tab_idx = cur
            else:
                self.right_tab_idx = cur
            if was_active:
                panel = self.left_panel if side == "left" else self.right_panel
                self._apply_tab_sort(side)
                panel.change_directory(tabs[cur])   # re-renders the strip
            else:
                self._render_tab_bar(side)          # same folder, new strip
            self._ws_autosave_extras(side)

        # ── arrive on the other side, last in the row, and show it ─────────
        self._sync_tab_meta(other)
        o_tabs  = self.left_tabs if other == "left" else self.right_tabs
        o_meta  = self._tabs_meta(other)
        o_panel = self.left_panel if other == "left" else self.right_panel
        o_tabs.append(path)
        o_meta.append(m)
        if other == "left":
            self.left_tab_idx = len(o_tabs) - 1
        else:
            self.right_tab_idx = len(o_tabs) - 1
        self._apply_tab_sort(other)
        o_panel.change_directory(path)              # re-renders that strip
        self._ws_autosave_extras(other)

        if locked:
            self._flash_status(
                f"Tab '{name}' is locked 🔒 — COPIED to the {other} panel, the "
                f"original stays.  Unlock it to move it.")
        elif copy_only:
            self._flash_status(
                f"'{name}' is the last tab on the {side} side, so it stays — "
                f"COPIED to the {other} panel.")
        else:
            self._flash_status(f"Tab '{name}' moved to the {other} panel")

    def _on_panel_navigate(self, side: str, path: str):
        """Called by FilePanel.change_directory to sync the tab path label."""
        # Where this panel stands on this volume — so switching away and back
        # returns here instead of to the drive root.  Dictionary write only;
        # the settings file is written when you actually change drive.
        try:
            self._remember_drive_dir(side, path)
        except Exception:
            pass
        if side == "left":
            if 0 <= self.left_tab_idx < len(self.left_tabs):
                self.left_tabs[self.left_tab_idx] = path
            self._render_tab_bar("left")
        else:
            if 0 <= self.right_tab_idx < len(self.right_tabs):
                self.right_tabs[self.right_tab_idx] = path
            self._render_tab_bar("right")
        # Keep the Workspace's remembered extra tabs current (half-save)
        self._ws_autosave_extras(side)

    def _tab_context_menu(self, event, path: str, side: str = None, idx: int = -1):
        """Right-click a tab — close it, lock it, copy its path, move it."""
        menu = tk.Menu(self, tearoff=0)

        # ── Lock / close ──────────────────────────────────────────────────
        # The tab strip has no ✕ any more, so this is where a tab is closed —
        # and a tab you want to keep is protected by its own lock.
        if side in ("left", "right") and idx >= 0:
            self._sync_tab_meta(side)
            tabs_now = self.left_tabs if side == "left" else self.right_tabs
            meta_now = self._tabs_meta(side)
            locked   = (idx < len(meta_now)
                        and bool(meta_now[idx].get("locked", False)))
            override = self._ws_unlock.get()

            def _closable(j):
                return override or not meta_now[j].get("locked", False)

            n_right = sum(1 for j in range(idx + 1, len(tabs_now))
                          if _closable(j))
            n_other = sum(1 for j in range(len(tabs_now))
                          if j != idx and _closable(j))

            menu.add_command(
                label=("🔓  Unlock this tab" if locked
                       else "🔒  Lock this tab   (protect it from closing)"),
                command=lambda: self._toggle_tab_lock(side, idx))
            menu.add_separator()

        menu.add_command(
            label="Copy full path",
            command=lambda: (self.clipboard_clear(),
                             self.clipboard_append(path),
                             self._flash_status(f"Copied:  {path}")))
        menu.add_command(
            label="Show full path",
            command=lambda: messagebox.showinfo("Tab path", path, parent=self))

        # ── 🖴 The disk behind this tab (revision BO) ──────────────────────
        # The file system goes in the MENU LINE, not only in the window: "which
        # format" is the question that gets asked, and this way it is answered
        # before anything is even clicked.
        menu.add_separator()
        try:
            drv = os.path.splitdrive(os.path.abspath(path))[0]
        except Exception:
            drv = ""
        letter = drv[:1].upper()
        if letter:
            root = letter + ":\\"
            vi   = _volume_info(root)
            try:
                cap = _fmt_size(shutil.disk_usage(root).total)
            except Exception:
                cap = "?"
            bits = [b for b in (vi["fs"] or "unreadable",
                                vi["label"], cap) if b]
            menu.add_command(
                label=f"🖴  Disk information   ({letter}:  "
                      + "  ·  ".join(bits) + ")",
                command=lambda p=path: _DiskInfoDlg(self, p))
            why = _format_is_forbidden(letter)
            menu.add_command(
                label=(f"🧨  Format {letter}: …   (two warnings first)"
                       if not why else f"🧨  Format {letter}:   — refused: {why}"),
                state=("normal" if not why else "disabled"),
                command=lambda L=letter: _FormatStep1Dlg(self, L))
        else:
            menu.add_command(label="🖴  Disk information   (not a local drive)",
                             state="disabled")

        # ── Move left / right / to the ends ───────────────────────────────
        # Reorders the tab within its own panel.  Disabled at the ends.
        if side in ("left", "right") and idx >= 0:
            tabs = self.left_tabs if side == "left" else self.right_tabs
            at_start = idx <= 0
            at_end   = idx >= len(tabs) - 1
            menu.add_separator()

            # ── Duplicate / to the other side (rev BL) ────────────────────
            # The line says what will REALLY happen before the click: a
            # locked tab (or the last one on this side) is copied, not moved.
            self._sync_tab_meta(side)
            other_side = "right" if side == "left" else "left"
            meta_t   = self._tabs_meta(side)
            locked_t = idx < len(meta_t) and bool(meta_t[idx].get("locked", False))
            ok_other, why_not = self._other_side_takes_tab(side)
            menu.add_command(
                label="⧉  Duplicate this tab   (added last — same folder, sort and lock)",
                command=lambda: self._duplicate_tab(side, idx))
            if not ok_other:
                verb, note = "Move", f"   ({why_not})"
            elif locked_t:
                verb, note = "Copy", "   (locked 🔒 — this tab stays here)"
            elif len(tabs) <= 1:
                verb, note = "Copy", "   (the last tab stays here)"
            else:
                verb, note = "Move", ""
            # The arrow points the way the tab goes — leading for ◀, right
            # after the panel name for ▶, never in the middle of the sentence
            # ("Copy to ◀  the LEFT panel" is what the first draft said).
            pre, post = ("", "  ▶") if side == "left" else ("◀  ", "")
            move_lbl = f"{pre}{verb} to the {other_side.upper()} panel{post}{note}"
            menu.add_command(
                label=move_lbl,
                state=("normal" if ok_other else "disabled"),
                command=lambda: self._move_tab_to_other_side(side, idx))
            menu.add_separator()
            menu.add_command(
                label="⏮  Move to leftmost",
                state=("normal" if not at_start else "disabled"),
                command=lambda: self._move_tab_to_end(side, idx, "start"))
            menu.add_command(
                label="◀  Move left",
                state=("normal" if not at_start else "disabled"),
                command=lambda: self._move_tab(side, idx, -1))
            menu.add_command(
                label="Move right  ▶",
                state=("normal" if not at_end else "disabled"),
                command=lambda: self._move_tab(side, idx, +1))
            menu.add_command(
                label="Move to rightmost  ⏭",
                state=("normal" if not at_end else "disabled"),
                command=lambda: self._move_tab_to_end(side, idx, "end"))

            # ── Tab pairs (F8 cycle) ──────────────────────────────────────
            menu.add_separator()
            other = "right" if side == "left" else "left"
            pair_menu = tk.Menu(menu, tearoff=0)

            add_menu = tk.Menu(pair_menu, tearoff=0)
            add_menu.add_command(
                label=f"New pair  (this {side} tab + current {other} tab)",
                command=lambda: self._pair_add_this_tab(side, idx, None))
            for n in range(2, len(self._tab_pairs) + 2):
                add_menu.add_command(
                    label=f"Pair {n}   (set its {side} side to this tab)",
                    command=lambda nn=n: self._pair_add_this_tab(side, idx, nn))
            pair_menu.add_cascade(label=f"Add THIS tab to a pair  (as {side})",
                                  menu=add_menu)
            pair_menu.add_command(
                label="Save current Left + Right tabs as a new pair",
                command=self._pair_new_from_current)
            pair_menu.add_separator()
            state_txt = "✓ " if self._pair1_in_cycle else "    "
            pair_menu.add_command(
                label=f"{state_txt}Start pair (1) is in the cycle  — toggle",
                command=self._pair_toggle_start)
            pair_menu.add_command(label="Manage / clear pairs…",
                                  command=self._manage_tab_pairs)
            menu.add_cascade(label="🔗  Tab pairs  (F8 cycles them)",
                             menu=pair_menu)

            # ── Close — LAST, away from Copy / Move ───────────────────────
            # Close is clicked far more often than Copy, and used to sit right
            # next to it at the top, so it was easy to hit the wrong one.  It
            # now has the bottom of the menu to itself.
            # (tabs_now / locked / override / n_other / n_right come from the
            # Lock block at the top of this method.)
            menu.add_separator()
            last_one = len(tabs_now) <= 1
            if last_one:
                close_lbl = "✕  Close this tab   (the last tab stays)"
            elif locked and not override:
                close_lbl = "✕  Close this tab   (locked 🔒)"
            else:
                close_lbl = "✕  Close this tab   (Ctrl+W)"
            menu.add_command(
                label=close_lbl,
                state=("disabled" if (last_one or (locked and not override))
                       else "normal"),
                command=lambda: self._close_tab(side, idx))
            menu.add_command(
                label=f"✕  Close the OTHER tabs on this side   ({n_other})",
                state=("normal" if n_other else "disabled"),
                command=lambda: self._close_tabs_bulk(side, idx, "others"))
            menu.add_command(
                label=f"✕  Close the tabs to the RIGHT   ({n_right})",
                state=("normal" if n_right else "disabled"),
                command=lambda: self._close_tabs_bulk(side, idx, "right"))

        try:
            menu.tk_popup(event.x_root, event.y_root)
        finally:
            menu.grab_release()

    def _move_tab_to_end(self, side: str, idx: int, where: str):
        """Move the tab at *idx* all the way to the leftmost ('start') or
        rightmost ('end') position on its panel side, keeping metadata and the
        active-tab index in sync, then persist the reorder (Workspace autosave)."""
        tabs = self.left_tabs if side == "left" else self.right_tabs
        meta = self._tabs_meta(side)
        if idx < 0 or idx >= len(tabs):
            return
        target = 0 if where == "start" else len(tabs) - 1
        if target == idx:
            return
        path = tabs.pop(idx)
        m    = meta.pop(idx) if idx < len(meta) else {"saved": False, "sort": None}
        tabs.insert(target, path)
        meta.insert(target, m)

        # Keep the active tab pointing at the same tab it was on
        cur = self.left_tab_idx if side == "left" else self.right_tab_idx
        if cur == idx:
            cur = target
        elif idx < cur <= target:
            cur -= 1
        elif target <= cur < idx:
            cur += 1
        if side == "left":
            self.left_tab_idx = cur
        else:
            self.right_tab_idx = cur

        self._render_tab_bar(side)
        self._schedule_ws_reorder_save(side)

    def _move_tab(self, side: str, idx: int, direction: int):
        """Swap the tab at *idx* with its neighbour (direction -1 = left,
        +1 = right) on the given panel side.  Keeps the active-tab index and
        the parallel metadata list in sync, re-renders the strip, and — if the
        side is part of a Workspace — schedules a debounced autosave so the new
        tab order is remembered ~1 minute after the last move."""
        tabs = self.left_tabs if side == "left" else self.right_tabs
        meta = self._tabs_meta(side)
        j = idx + direction
        if idx < 0 or idx >= len(tabs) or j < 0 or j >= len(tabs):
            return

        tabs[idx], tabs[j] = tabs[j], tabs[idx]
        if idx < len(meta) and j < len(meta):
            meta[idx], meta[j] = meta[j], meta[idx]

        # Follow the active tab if it was one of the two swapped
        cur = self.left_tab_idx if side == "left" else self.right_tab_idx
        if cur == idx:
            cur = j
        elif cur == j:
            cur = idx
        if side == "left":
            self.left_tab_idx = cur
        else:
            self.right_tab_idx = cur

        self._render_tab_bar(side)
        # Persist the reorder into the Workspace after a quiet period.
        self._schedule_ws_reorder_save(side)

    def _schedule_ws_reorder_save(self, side: str):
        """Debounced Workspace save after tab reordering.  Waits ~60 s after the
        LAST move, then writes the current tab order back to the loaded
        Workspace — so a burst of moves triggers only one save, not one per
        move.  Does nothing when the side is not in a Workspace."""
        if not self._ws_active.get(side, False):
            return
        if not hasattr(self, "_ws_reorder_after"):
            self._ws_reorder_after = {"left": None, "right": None}
        prev = self._ws_reorder_after.get(side)
        if prev is not None:
            try:
                self.after_cancel(prev)
            except Exception:
                pass
        self._ws_reorder_after[side] = self.after(
            60_000, lambda s=side: self._ws_save_order(s))

    def _ws_save_order(self, side: str):
        """Write the current tab order of *side* back to its loaded Workspace,
        preserving the base/extra split (base tabs and extra tabs each keep
        their new relative order).  Called by the debounced reorder timer."""
        if hasattr(self, "_ws_reorder_after"):
            self._ws_reorder_after[side] = None
        name = self._ws_name.get(side)
        if not name or name not in self.workspaces:
            return
        self._sync_tab_meta(side)
        tabs  = self.left_tabs if side == "left" else self.right_tabs
        meta  = self._tabs_meta(side)
        sorts = self._current_tab_sorts(side)

        base_paths,  base_sorts,  base_locks  = [], [], []
        extra_paths, extra_sorts, extra_locks = [], [], []
        for i, m in enumerate(meta):
            s  = sorts[i] if i < len(sorts) else None
            lk = bool(m.get("locked", False))
            if m.get("saved", False):
                base_paths.append(tabs[i]);  base_sorts.append(s)
                base_locks.append(lk)
            else:
                extra_paths.append(tabs[i]); extra_sorts.append(s)
                extra_locks.append(lk)

        ws = self.workspaces[name]
        ws[f"{side}"]            = base_paths
        ws[f"{side}_sort"]       = base_sorts
        ws[f"{side}_lock"]       = base_locks
        ws[f"{side}_extra"]      = extra_paths
        ws[f"{side}_extra_sort"] = extra_sorts
        ws[f"{side}_extra_lock"] = extra_locks
        self._store_pairs_into(ws)             # tab pairs may have been remapped
        self._save_workspaces()
        self._flash_status(f"Workspace '{name}' tab order saved")

    # ── public shortcuts ──────────────────────────────────────────────────

    def _add_new_tab(self):
        """Ctrl+T – duplicate the active panel's current tab."""
        self._add_new_tab_side(self.active_panel)

    def _close_current_tab(self):
        """Ctrl+W – close the active tab in the active panel."""
        side = self.active_panel
        idx  = self.left_tab_idx if side == "left" else self.right_tab_idx
        self._close_tab(side, idx)

    def _reopen_last_tab(self):
        """Ctrl+Shift+T – reopen the most recently closed tab."""
        while self.closed_tabs:
            path = self.closed_tabs.pop()
            if os.path.isdir(path):
                side  = self.active_panel
                tabs  = self.left_tabs if side == "left" else self.right_tabs
                meta  = self._tabs_meta(side)
                tabs.append(path)
                meta.append({"saved": False, "sort": None})   # reopened = temporary
                new_idx = len(tabs) - 1
                if side == "left":
                    self.left_tab_idx = new_idx
                else:
                    self.right_tab_idx = new_idx
                panel = self.left_panel if side == "left" else self.right_panel
                self._apply_tab_sort(side)
                panel.change_directory(path)
                return

    # ══ Workspace (named tab groups) ════════════════════════════════════

    # ── persistence ───────────────────────────────────────────────────────

    def _load_workspaces(self) -> dict:
        try:
            with open(WORKSPACES_PATH, "r", encoding="utf-8") as fh:
                data = fm_unpack_tree(json.load(fh))
                return data if isinstance(data, dict) else {}
        except FileNotFoundError:
            return {}
        except Exception as exc:
            _log(f"Could not load workspaces: {exc}")
            return {}

    def _save_workspaces(self):
        try:
            with open(WORKSPACES_PATH, "w", encoding="utf-8") as fh:
                json.dump(fm_pack_tree(self.workspaces), fh,
                          indent=2, ensure_ascii=False)
        except Exception as exc:
            _log(f"Could not save workspaces: {exc}")

    # ── workspace bar ─────────────────────────────────────────────────────

    def _render_workspace_bar(self):
        """Redraw the workspace bar contents."""
        for w in self._ws_bar.winfo_children():
            w.destroy()

        # Label
        tk.Label(
            self._ws_bar, text=" Workspaces:", bg=C_BG3, fg=C_FG_DIM,
            font=("", 8)
        ).pack(side="left", padx=(4, 2), pady=2)

        # One button per saved workspace
        for name in self.workspaces:
            self._ws_make_button(name)

        # ＋ Save button
        save_btn = tk.Label(
            self._ws_bar, text=" ＋ Save ", bg=C_BG2, fg=C_FG_DIM,
            font=("", 8), cursor="hand2",
            relief="flat",
        )
        save_btn.pack(side="left", padx=(6, 1), pady=2)
        save_btn.bind("<Button-1>", lambda e: self._ws_save_dialog())
        self._create_tooltip(save_btn, "Save current tabs as workspace")

        # Separator
        tk.Frame(self._ws_bar, bg=C_SEP, width=1).pack(
            side="left", fill="y", padx=6, pady=3)

        # Right side: checkboxes for which panel(s) to affect on load
        tk.Label(
            self._ws_bar, text="Apply to:", bg=C_BG3, fg=C_FG_DIM,
            font=("", 8)
        ).pack(side="left", padx=(0, 4), pady=2)

        chk_style = dict(bg=C_BG3, fg=C_FG, activebackground=C_BG3,
                         selectcolor=C_BG2, font=("", 8))
        tk.Checkbutton(
            self._ws_bar, text="Left", variable=self._ws_apply_left,
            **chk_style
        ).pack(side="left", padx=2, pady=2)
        tk.Checkbutton(
            self._ws_bar, text="Right", variable=self._ws_apply_right,
            **chk_style
        ).pack(side="left", padx=2, pady=2)

        # Separator
        tk.Frame(self._ws_bar, bg=C_SEP, width=1).pack(
            side="left", fill="y", padx=6, pady=3)

        # "Ignore tab locks" — off by default.  When on, a 🔒 tab closes
        # anyway, which is what you want when clearing a side out in one go;
        # the lock itself is left alone.  The tab strips are redrawn on a
        # toggle only to keep both sides in step — the 🔒 marker shows the
        # LOCK, not this override, so a ticked box never hides a padlock.
        unlock_chk = tk.Checkbutton(
            self._ws_bar, text="Ignore tab locks",
            variable=self._ws_unlock,
            command=lambda: (self._render_tab_bar("left"),
                             self._render_tab_bar("right")),
            **chk_style
        )
        unlock_chk.pack(side="left", padx=2, pady=2)
        self._create_tooltip(
            unlock_chk,
            "Off: a tab you locked (right-click ▸ 🔒) refuses to close.\n"
            "On:  locked tabs close too — the lock is kept, just ignored.")

        # "Folders sort like files" — off by default.  The panel keeps TWO
        # sort orders, one for files (solid arrow) and one for folders (the
        # hollow ▵), which is easy to forget you ever set.  Ticked, the folders
        # simply follow whatever the FILE column is sorted by — they still stay
        # above the files, they are just no longer on an order of their own.
        # Pair it with Alt+Shift+Enter: measure the folders first, sort by Size,
        # and the biggest folder is at the top.
        self._dirs_follow_files = tk.BooleanVar(
            value=bool(self.settings.get("folders_follow_file_sort", False)))

        def _toggle_dirs_follow():
            self.settings["folders_follow_file_sort"] = \
                bool(self._dirs_follow_files.get())
            self.save_settings()
            for side in ("left", "right"):
                try:
                    getattr(self, f"{side}_panel")._reapply_sort()
                except Exception:
                    pass

        dirsort_chk = tk.Checkbutton(
            self._ws_bar, text="Folders sort like files",
            variable=self._dirs_follow_files,
            command=_toggle_dirs_follow,
            **chk_style
        )
        dirsort_chk.pack(side="left", padx=2, pady=2)
        self._create_tooltip(
            dirsort_chk,
            "Off: folders keep their own sort order (the hollow ▵ arrow).\n"
            "On:  folders follow the FILE sort — still listed above the files.\n"
            "Sorting folders by Size needs their sizes first: Alt+Shift+Enter.")

        # "⚖ Rules" — the conflict rules for the two folders standing in the
        # panels RIGHT NOW (DEL 52).  Asked for straight after "Folders sort
        # like files", and that is where it is.
        self._rules_btn = tk.Button(
            self._ws_bar, text=self._RULES_BTN_IDLE,
            font=("Segoe UI", 8), relief="flat", bd=0,
            bg=C_BG2, fg=C_FG_DIM, activebackground=C_BG3,
            activeforeground=C_FG, padx=6,
            command=self.open_pair_rules)
        self._rules_btn.pack(side="left", padx=(8, 2), pady=2)
        self._create_tooltip(
            self._rules_btn,
            "The clash rules for THIS left→right pair of folders.\n"
            "Lit up = a rule already covers the two folders you are standing in.\n"
            "Click to see them — or to make one for this pair without going\n"
            "through the Task Queue first.")
        # Force the first paint: the bar has just been rebuilt, so whatever the
        # button looked like a moment ago is gone with it.
        self._rules_btn_pair = None
        self._rules_btn_sync()

        # "Go to:" — type or paste a path and land there (DEL 51).  Built LAST
        # so it sits after "Folders sort like files", and packed side="right"
        # inside its own frame so a long row of Workspace buttons can never
        # push it off the end of the bar.
        self._goto_build(self._ws_bar)

    # ══ DEL 52 — "⚖ Rules" button (Workspace bar) ═════════════════════════
    #
    # ASKED FOR: "Efter Folders sort like... så kan du lägga in en knapp:
    # Rules.  Om både vänster och höger fönster är del av en Rule, så kan
    # knappens namn bli lite lysande... tydlig.  Då kan man klicka på den och
    # få upp alla regler som gäller för just denna kombination (och ÄVEN om
    # det inte finns rule redan; då kan man skapa en där)."
    #
    # The point is that a rule is invisible until it has already done something
    # you did not want.  This button stands over the two folders it is about:
    # dim when nothing governs them, LIT when something does, and one click
    # either way — to see what governs them, or to write the rule down while
    # you are standing in the very pair it is for.

    _RULES_BTN_IDLE = "⚖ Rules"

    def _rules_btn_sync(self, force: bool = False):
        """Light the button when a rule covers the folders in the panels.

        Cheap on purpose: the folder pair is remembered and the work is skipped
        while it has not changed.  The panels rebuild themselves every 1.5 s,
        and a button that recoloured itself on every one of those would be a
        light flickering in the corner of his eye all day."""
        btn = getattr(self, "_rules_btn", None)
        if btn is None:
            return
        try:
            if not btn.winfo_exists():
                return
            left  = self.left_panel.current_path
            right = self.right_panel.current_path
        except Exception:
            return
        pair = (left, right)
        if not force and getattr(self, "_rules_btn_pair", None) == pair:
            return
        self._rules_btn_pair = pair
        n = 0
        try:
            n = len(self._pair_rule_hits(left, right))
        except Exception:
            n = 0
        try:
            if n:
                btn.config(text=f"⚖ Rules · {n}", fg=C_ACCENT,
                           bg=C_BG3, font=("Segoe UI", 8, "bold"))
            else:
                btn.config(text=self._RULES_BTN_IDLE, fg=C_FG_DIM,
                           bg=C_BG2, font=("Segoe UI", 8))
        except Exception:
            pass

    def _pair_rule_hits(self, left: str, right: str) -> list:
        """Every enabled rule covering this pair, EITHER WAY round.

        Both directions on purpose: the panels are a pair, and a rule for
        right→left is just as much "about these two folders" as one for
        left→right — being told only about the direction you happen to be
        copying in is how the other one stays invisible.  Each hit carries
        which way it points and whether the Workspace lets it act now."""
        hits = []
        for a, b, arrow in ((left, right, "→"), (right, left, "←")):
            if not a or not b:
                continue
            try:
                for c in self._conflict_rule_candidates(
                        [os.path.join(a, "any-file")], b):
                    c = dict(c)
                    c["arrow"] = arrow
                    c["from"], c["to"] = a, b
                    hits.append(c)
            except Exception:
                pass
        return hits

    def make_image(self):
        """💿 Create an ISO / IMG image from what is marked (DEL 53)."""
        panel = self.get_active_panel()
        if getattr(panel, "is_remote", False) or getattr(panel, "archive_ctx", None):
            messagebox.showinfo("Create image",
                                "Images are built from local files.",
                                parent=self)
            return
        try:
            sources = panel.get_all_selected()
        except Exception:
            sources = []
        if not sources:
            messagebox.showinfo(
                "Create image",
                "Mark the files and folders that should go on the image "
                "first.\n\n(Insert marks, or select them the ordinary way.)",
                parent=self)
            return
        MakeImageWindow(self, sources)

    def open_pair_rules(self):
        """The ⚖ Rules button, and Tools ▸ — rules for the current pair."""
        try:
            PairRulesWindow(self)
        except Exception as exc:
            _log(f"pair rules window failed: {exc}")

    # ══ DEL 51 — "Go to:" path box (Workspace bar, far right) ═════════════
    #
    # ASKED FOR: "en ruta för att mata in t.ex. C:/Program Files/Common Files/
    # VST3/Psylus Audio för att komma direkt dit".  Paste a path, press Enter,
    # and you are there — no walking down five folders, no drive menu, no
    # dialog to open and close.  It sits at the FAR RIGHT of the Workspace bar,
    # which is exactly why it belongs to the RIGHT panel: the box points at the
    # panel it stands over.  (Ctrl+Shift+G puts the keyboard in it from
    # anywhere, and it is re-mappable like every other shortcut.)
    #
    # It takes whatever Windows put on the clipboard, so pasting just works:
    #   • "C:/path with spaces"   — Explorer's "Copy as path" wraps the whole
    #     thing in double quotes; single quotes are stripped too.
    #   • forward slashes         — C:/Program Files works as well as C:\...
    #   • %ProgramFiles%\...  ~   — environment variables and the home folder
    #     are expanded.
    #   • file:///C:/...          — a path dragged out of a browser.
    #   • //server/share/...      — UNC.
    #   • D:                      — a bare drive letter means that drive's root.
    #   • ..  or  Subfolder       — anything that is not absolute is read
    #     relative to where the right panel stands NOW, like a shell.
    #   • a FILE rather than a folder — lands in its folder with the cursor
    #     already on the file.
    #
    # Keys inside the box:
    #   Enter        go
    #   Ctrl+Enter   go, but in a NEW tab on the right (the current one stays)
    #   Tab          complete the name being typed (no popup, no blinking)
    #   ↓  or  ▾     the last places it was sent to
    #   Esc          clear the box; on an already-empty box, hand the keyboard
    #                back to the file list
    #
    # A path that does not exist NEVER opens a dialog: the box goes a steady
    # dark red and the status line says why, and the red is gone the moment you
    # type again.  Nothing flashes and nothing has to be clicked away.

    _GOTO_HISTORY_MAX = 20
    _GOTO_BAD_BG      = "#5a2a34"    # steady, not a flash
    _GOTO_BAD_FG      = "#ffd7d7"

    def _goto_build(self, bar):
        """Build the Go-to box at the right-hand end of the Workspace bar."""
        # The bar is destroyed and rebuilt whenever a Workspace changes, so the
        # typed text lives in a StringVar owned by the FRAME, not in the widget
        # — a half-typed path survives clicking a Workspace button.
        if not hasattr(self, "_goto_var"):
            self._goto_var = tk.StringVar()

        box = tk.Frame(bar, bg=C_BG3)
        box.pack(side="right", padx=(8, 4), pady=1)

        tk.Label(box, text="Go to:", bg=C_BG3, fg=C_FG_DIM,
                 font=("", 8)).pack(side="left", padx=(0, 3))

        # tk.Entry, never ttk: only the classic widget has -insertofftime, and
        # the caret must not blink.
        entry = tk.Entry(
            box, textvariable=self._goto_var, width=44,
            bg=C_BG2, fg=C_FG, insertbackground=C_FG,
            relief="flat", font=("", 8),
            highlightthickness=1, highlightbackground=C_SEP,
            highlightcolor=C_ACCENT,
            insertofftime=0, insertontime=9999999,
        )
        entry.pack(side="left", ipady=1)
        self._goto_entry = entry

        entry.bind("<Return>",         lambda e: self._goto_run(new_tab=False))
        entry.bind("<KP_Enter>",       lambda e: self._goto_run(new_tab=False))
        entry.bind("<Control-Return>", lambda e: self._goto_run(new_tab=True))
        # Tab completes INSIDE the box.  The window-level <Tab> binding lets
        # Entry widgets through, and a widget binding runs before it anyway, so
        # returning "break" here keeps both the panel switch and Tk's own
        # focus-traversal out of the way.
        entry.bind("<Tab>",            self._goto_complete)
        entry.bind("<Down>",           self._goto_history_menu)
        entry.bind("<Escape>",         lambda e: self._goto_escape())
        entry.bind("<Control-a>",      self._goto_select_all)
        entry.bind("<Control-A>",      self._goto_select_all)
        # Any keystroke takes the red off again — no timer, no flashing.
        entry.bind("<Key>",            self._goto_clear_error, add="+")

        self._create_tooltip(
            entry,
            "Type or paste a folder and press Enter — the RIGHT panel goes "
            "there.\n"
            "Takes quoted paths, forward slashes, %ProgramFiles%, ~, "
            "file:/// and UNC.\n"
            "A file lands in its folder with the cursor on it; a relative name "
            "or .. is\n"
            "read from where the right panel stands now.\n"
            "Enter = go   Ctrl+Enter = go in a NEW right tab   Tab = complete\n"
            "↓ = the last places it went   Esc = clear / back to the list\n"
            "Ctrl+Shift+G jumps here from anywhere.")

        go_btn = tk.Label(box, text=" → ", bg=C_BG2, fg=C_ACCENT,
                          font=("", 8, "bold"), cursor="hand2")
        go_btn.pack(side="left", padx=(2, 0))
        go_btn.bind("<Button-1>", lambda e: self._goto_run(new_tab=False))
        self._create_tooltip(go_btn, "Go there (same as Enter)")

        hist_btn = tk.Label(box, text=" ▾ ", bg=C_BG2, fg=C_ACCENT,
                            font=("", 8), cursor="hand2")
        hist_btn.pack(side="left", padx=(1, 0))
        hist_btn.bind("<Button-1>", self._goto_history_menu)
        self._create_tooltip(hist_btn, "The last places this box went to")

    # ── reading what was typed ────────────────────────────────────────────

    @staticmethod
    def _goto_clean(raw: str) -> str:
        """Whatever was typed or pasted → a plain Windows path.

        Everything that a copied path can arrive wrapped in is peeled off here
        and nowhere else, so the resolver below only ever sees a real path."""
        text = (raw or "").strip()
        # Explorer's "Copy as path" wraps it in double quotes; some apps use
        # single ones.  Only a MATCHING pair is stripped — a quote that is part
        # of a name is left alone.
        for quote in ('"', "'"):
            if len(text) >= 2 and text.startswith(quote) and text.endswith(quote):
                text = text[1:-1].strip()
                break
        # A path dragged out of a browser or copied from a Markdown link
        low = text.lower()
        if low.startswith("file:///") or low.startswith("file://"):
            try:
                from urllib.parse import unquote as _urlunquote
            except Exception:
                def _urlunquote(s):
                    return s
            if low.startswith("file:///"):
                text = _urlunquote(text[8:])
            else:
                text = "\\\\" + _urlunquote(text[7:])
        text = text.replace("/", "\\")
        # ~ first, then %VAR% — an unknown variable is simply left standing and
        # turns into a plain "no such folder", which says more than a crash.
        try:
            text = os.path.expandvars(os.path.expanduser(text))
        except Exception:
            pass
        return text.strip()

    def _goto_resolve(self, raw: str, base: str):
        """(folder, name_to_put_the_cursor_on) — or ValueError with the reason."""
        text = self._goto_clean(raw)
        if not text:
            raise ValueError("type or paste a path first.")
        # A bare drive letter means its root: "D:" → "D:\"
        if _re.fullmatch(r"[A-Za-z]:", text):
            text += "\\"
        # A leading single backslash is root-relative.  os.path.abspath would
        # attach the PROCESS's drive, which is not the drive you are looking
        # at, so take the right panel's drive instead.
        if text.startswith("\\") and not text.startswith("\\\\"):
            drive = os.path.splitdrive(base)[0]
            if drive:
                text = drive + text
        # Anything not absolute is read from where the panel stands now, so
        # ".." and a bare sub-folder name work the way they do in a shell.
        if not os.path.isabs(text):
            text = os.path.join(base or "", text)
        try:
            full = os.path.abspath(text)
        except Exception:
            raise ValueError(f"that is not a path: {text}")
        if os.path.isdir(full):
            return full, None
        if os.path.isfile(full):
            return os.path.dirname(full), os.path.basename(full)
        hint   = ""
        parent = os.path.dirname(full.rstrip("\\"))
        if "%" in full:
            hint = "   (an environment variable did not expand)"
        elif parent and parent != full and os.path.isdir(parent):
            hint = f"   —  but {parent} does exist"
        raise ValueError(f"no such folder or file: {full}{hint}")

    # ── going there ───────────────────────────────────────────────────────

    def _goto_run(self, new_tab: bool = False):
        """Enter / the → button."""
        self._goto_go(self._goto_var.get(), new_tab=new_tab)
        return "break"

    def _goto_go(self, raw: str, new_tab: bool = False):
        """Send the RIGHT panel to *raw*.  Never opens a dialog."""
        panel = self.right_panel
        if getattr(panel, "is_remote", False):
            self._goto_bad("the right panel is FTP-mounted — disconnect it first.")
            return
        base = getattr(panel, "current_path", "") or os.getcwd()
        try:
            folder, select_name = self._goto_resolve(raw, base)
        except ValueError as exc:
            self._goto_bad(str(exc))
            return

        # Record where this panel stood on the volume it is LEAVING before it
        # goes, exactly as the drive menu does — otherwise drive memory would
        # forget every folder reached through this box.
        try:
            self._remember_drive_dir("right", panel.current_path)
        except Exception:
            pass

        if new_tab:
            try:
                self._add_new_tab_side("right")
                panel = self.right_panel
            except Exception as exc:
                _log(f"Go-to box: could not open a new tab: {exc}")

        try:
            panel.change_directory(folder, select_name=select_name)
        except Exception as exc:
            _log(f"Go-to box: {folder!r} failed: {exc}")
            self._goto_bad(f"could not open it — {exc}")
            return

        try:
            self._remember_net_path(folder)
            self._save_drive_mem()
        except Exception:
            pass
        self._update_disk_info()
        self._goto_remember(os.path.join(folder, select_name)
                            if select_name else folder)
        self._goto_clear_error()
        # Cleared, so the next paste needs no select-all first.  Where it went
        # is on the status line and in the ▾ list.
        self._goto_var.set("")
        self._flash_status(
            ("＋ new tab — " if new_tab else "→ ")
            + f"Right panel: {folder}"
            + (f"   (cursor on {select_name})" if select_name else ""))

    def _goto_escape(self):
        """Esc — clear the box; on an empty box, hand the keyboard back."""
        if self._goto_var.get():
            self._goto_var.set("")
            self._goto_clear_error()
        else:
            try:
                self.right_panel.tree.focus_set()
            except Exception:
                pass
        return "break"

    def _goto_focus_box(self):
        """Ctrl+Shift+G — put the keyboard in the box, ready for a paste."""
        entry = getattr(self, "_goto_entry", None)
        try:
            if entry is None or not entry.winfo_exists():
                return
            entry.focus_set()
            entry.select_range(0, "end")
            entry.icursor("end")
        except Exception:
            pass

    def _goto_select_all(self, event=None):
        try:
            self._goto_entry.select_range(0, "end")
            self._goto_entry.icursor("end")
        except Exception:
            pass
        return "break"

    # ── Tab completion (no popup — the box itself is completed) ───────────

    def _goto_complete(self, event=None):
        """Tab — finish the name being typed, as far as it is unambiguous."""
        base = getattr(self.right_panel, "current_path", "") or ""
        text = self._goto_clean(self._goto_var.get())
        head, sep, stub = text.rpartition("\\")
        if not sep:
            folder, stub = base, text          # nothing typed but a name
        elif _re.fullmatch(r"[A-Za-z]:", head):
            folder = head + "\\"               # "C:" → "C:\"
        elif head == "":
            folder = os.path.splitdrive(base)[0] + "\\"
        else:
            folder = head
        if not os.path.isabs(folder):
            folder = os.path.join(base, folder)
        folder = os.path.abspath(folder)

        if not os.path.isdir(folder):
            self._goto_bad(f"nothing to complete — {folder} is not a folder.")
            return "break"
        try:
            names = os.listdir(folder)
        except OSError as exc:
            self._goto_bad(f"cannot read {folder} — {exc}")
            return "break"

        low   = stub.lower()
        dirs  = [n for n in names if n.lower().startswith(low)
                 and os.path.isdir(os.path.join(folder, n))]
        # Folders first — that is what you are usually typing towards.  Only
        # when no folder matches do files get a say.
        cand  = dirs or [n for n in names if n.lower().startswith(low)]
        if not cand:
            self._goto_bad(f"no name in {folder} starts with “{stub}”.")
            return "break"

        # As far as every candidate agrees, in the real case of the first one.
        common = cand[0]
        for name in cand[1:]:
            i = 0
            while (i < min(len(common), len(name))
                   and common[i].lower() == name[i].lower()):
                i += 1
            common = common[:i]
        if len(common) < len(stub):
            common = stub                       # nothing shared beyond typing

        done = os.path.join(folder, common)
        if len(cand) == 1 and os.path.isdir(done):
            done += "\\"                        # ready for the next level
        self._goto_var.set(done)
        try:
            self._goto_entry.icursor("end")
            self._goto_entry.xview_moveto(1.0)
        except Exception:
            pass
        if len(cand) > 1:
            shown = ", ".join(sorted(cand)[:8])
            more  = f"   …+{len(cand) - 8} more" if len(cand) > 8 else ""
            self._flash_status(f"Go to — {len(cand)} matches: {shown}{more}")
        self._goto_clear_error()
        return "break"

    # ── the ▾ list of places it has been ─────────────────────────────────

    def _goto_history_menu(self, event=None):
        hist = [p for p in self.settings.get("goto_history", [])
                if isinstance(p, str) and p]
        menu = tk.Menu(self, tearoff=0)
        if not hist:
            menu.add_command(
                label="(nothing yet — type a path and press Enter)",
                state="disabled")
        else:
            for path in hist[:self._GOTO_HISTORY_MAX]:
                label = path if len(path) <= 90 else "…" + path[-89:]
                menu.add_command(label=label,
                                 command=lambda p=path: self._goto_go(p))
            menu.add_separator()
            menu.add_command(label="Clear this list",
                             command=self._goto_history_clear)
        try:
            anchor = getattr(self, "_goto_entry", None) or self
            menu.tk_popup(anchor.winfo_rootx(),
                          anchor.winfo_rooty() + anchor.winfo_height())
        finally:
            try:
                menu.grab_release()
            except Exception:
                pass
        return "break"

    def _goto_remember(self, path: str):
        hist = [p for p in self.settings.get("goto_history", [])
                if isinstance(p, str) and p]
        low  = os.path.normcase(path)
        hist = [p for p in hist if os.path.normcase(p) != low]
        hist.insert(0, path)
        self.settings["goto_history"] = hist[:self._GOTO_HISTORY_MAX]
        try:
            self.save_settings()
        except Exception as exc:
            _log(f"Go-to box: could not save the history: {exc}")

    def _goto_history_clear(self):
        self.settings["goto_history"] = []
        try:
            self.save_settings()
        except Exception as exc:
            _log(f"Go-to box: could not clear the history: {exc}")
        self._flash_status("Go to — the list of places is empty again.")

    # ── saying no without a dialog ───────────────────────────────────────

    def _goto_bad(self, message: str):
        """A steady red box + the reason on the status line.  No popup, no
        flashing: the red simply stays until the next keystroke."""
        try:
            self._goto_entry.configure(bg=self._GOTO_BAD_BG,
                                       fg=self._GOTO_BAD_FG)
        except Exception:
            pass
        self._flash_status(f"Go to — {message}", 6000)
        _log(f"Go-to box: {message}")

    def _goto_clear_error(self, event=None):
        try:
            self._goto_entry.configure(bg=C_BG2, fg=C_FG)
        except Exception:
            pass

    def _ws_make_button(self, name: str):
        """Create one workspace button with context menu.  The CURRENTLY LOADED
        workspace is highlighted (inverted colours + a ● marker and the panel
        side it is on) so it is obvious at a glance which one is active."""
        ws = self.workspaces.get(name, {})
        left_count  = len(ws.get("left",  []))
        right_count = len(ws.get("right", []))
        lx = len(ws.get("left_extra",  []))
        rx = len(ws.get("right_extra", []))
        tip = (f"Left: {left_count} base"  + (f" + {lx} extra" if lx else "") + " tab(s)   "
               f"Right: {right_count} base" + (f" + {rx} extra" if rx else "") + " tab(s)")

        # Which panel side(s) currently have this workspace loaded?
        active_sides = [s for s in ("left", "right")
                        if self._ws_name.get(s) == name]
        is_active = bool(active_sides)

        # A ★ marks the Workspace that loads automatically on program start.
        is_startup = (self.settings.get("startup_workspace", "") == name)
        star = "★ " if is_startup else ""
        if is_startup:
            tip += "\n★ Loads automatically on start"

        if is_active:
            side_mark = {"left": "L", "right": "R"}
            marks = "".join(side_mark[s] for s in active_sides)   # "L", "R" or "LR"
            label = f" ● {star}{name} · {marks} "
            bg, fg = C_ACCENT, C_BG           # inverted = clearly "on"
            tip += "\n(ACTIVE — loaded now)"
        else:
            label = f" {star}{name} "
            bg, fg = C_BG2, C_ACCENT

        btn = tk.Label(
            self._ws_bar,
            text=label,
            bg=bg, fg=fg,
            font=("", 8, "bold"),
            cursor="hand2",
            relief=("solid" if is_active else "flat"),
            bd=(1 if is_active else 0),
            padx=2,
        )
        btn.pack(side="left", padx=1, pady=2)
        btn.bind("<Button-1>", lambda e, n=name: self._ws_load(n))
        btn.bind("<Button-3>", lambda e, n=name: self._ws_context_menu(e, n))
        self._create_tooltip(btn, f"{tip}\nLeft-click: load   Right-click: rename / delete")

    # ── actions ───────────────────────────────────────────────────────────

    def _current_tab_sorts(self, side: str) -> list:
        """Sort snapshot for every tab on *side* — the live panel state for the
        active tab, the remembered state for the rest."""
        self._sync_tab_meta(side)
        meta  = self._tabs_meta(side)
        idx   = self.left_tab_idx if side == "left" else self.right_tab_idx
        panel = self.left_panel if side == "left" else self.right_panel
        out = []
        for i, m in enumerate(meta):
            s = m.get("sort")
            if i == idx and hasattr(panel, "get_sort_state"):
                s = panel.get_sort_state()
            out.append(s)
        return out

    def _current_tab_locks(self, side: str) -> list:
        """Lock flag for every tab on *side*, parallel to _current_tab_sorts —
        so a Workspace remembers which of its tabs you protected."""
        self._sync_tab_meta(side)
        return [bool(m.get("locked", False)) for m in self._tabs_meta(side)]

    def _ws_autosave_extras(self, side: str):
        """Half-save: while a Workspace is loaded on *side*, keep its remembered
        EXTRA (temporary) tabs up to date on disk — so the extra tabs you open
        while working come back next time you load the Workspace.  The base
        (protected) tabs are NOT touched here; those change only on an explicit
        Save / Update."""
        name = getattr(self, "_ws_name", {}).get(side)
        if not name or name not in self.workspaces:
            return
        self._sync_tab_meta(side)
        tabs  = self.left_tabs if side == "left" else self.right_tabs
        meta  = self._tabs_meta(side)
        sorts = self._current_tab_sorts(side)
        locks = self._current_tab_locks(side)
        extra_paths, extra_sorts, extra_locks = [], [], []
        for i, m in enumerate(meta):
            if not m.get("saved", False):          # an extra (temporary) tab
                extra_paths.append(tabs[i])
                extra_sorts.append(sorts[i] if i < len(sorts) else None)
                extra_locks.append(locks[i] if i < len(locks) else False)
        ws = self.workspaces[name]
        ws[f"{side}_extra"]      = extra_paths
        ws[f"{side}_extra_sort"] = extra_sorts
        ws[f"{side}_extra_lock"] = extra_locks
        self._save_workspaces()

    def _ws_remember_spot(self, side: str):
        """Note which tab *side* is standing on, for the Workspace loaded there."""
        name = self._ws_name.get(side)
        if not name:
            return
        tabs = self.left_tabs if side == "left" else self.right_tabs
        idx  = self.left_tab_idx if side == "left" else self.right_tab_idx
        if 0 <= idx < len(tabs):
            self._ws_spot[(name, side)] = (idx, tabs[idx])

    def _ws_spot_for(self, name: str, side: str, valid: list) -> int:
        """Which tab to land on when *name* is loaded into *side*.

        The folder is trusted before the number: a Workspace whose tab strip
        has changed since you left it (an extra tab opened or closed) should
        still bring you back to the FOLDER you were in, not to whatever now
        happens to sit at that position."""
        spot = getattr(self, "_ws_spot", {}).get((name, side))
        if not spot:
            return 0                       # never been here this session
        idx, path = spot
        if 0 <= idx < len(valid) and valid[idx] == path:
            return idx
        if path in valid:
            return valid.index(path)
        return idx if 0 <= idx < len(valid) else 0

    def _ws_load(self, name: str, base_only: bool = False):
        """Load a saved workspace into the checked panel(s).

        By default this restores the base (protected) tabs AND the extra tabs
        that were auto-remembered while you last worked in this Workspace.
        Pass base_only=True (context menu ▸ "Load base tabs only") to reopen
        just the base set and drop the remembered extras."""
        ws = self.workspaces.get(name)
        if not ws:
            return
        apply_left  = self._ws_apply_left.get()
        apply_right = self._ws_apply_right.get()
        if not apply_left and not apply_right:
            messagebox.showinfo(
                "Workspace", "Check at least one panel (Left / Right).",
                parent=self)
            return

        # Leaving a Workspace: note where each side stood.  Both sides, not
        # just the ones being replaced — the other panel's Workspace may be
        # the one you switch back to next.
        self._ws_remember_spot("left")
        self._ws_remember_spot("right")

        def _load_side(side: str, paths: list, sorts: list,
                       extras: list, extra_sorts: list,
                       locks: list = (), extra_locks: list = ()):
            if not paths:
                return
            # base tabs → Workspace tabs; extra tabs → temporary (amber).  The
            # 4th field is the per-tab LOCK, remembered with the Workspace; an
            # older workspaces.json has no lock lists and loads all-unlocked.
            base_pairs = [(p, (sorts[i] if i < len(sorts) else None), True,
                           bool(locks[i]) if i < len(locks) else False)
                          for i, p in enumerate(paths) if os.path.isdir(p)]
            if not base_pairs:
                messagebox.showwarning(
                    "Workspace",
                    f"No valid folders for the {side} panel in '{name}'.\n"
                    "(Paths may have been moved or deleted.)",
                    parent=self)
                return
            extra_pairs = []
            if not base_only:
                extra_pairs = [(p, (extra_sorts[i] if i < len(extra_sorts) else None), False,
                                bool(extra_locks[i]) if i < len(extra_locks) else False)
                               for i, p in enumerate(extras) if os.path.isdir(p)]
            all_pairs = base_pairs + extra_pairs
            valid    = [p for p, _s, _sv, _lk in all_pairs]
            new_meta = [{"saved": sv, "sort": s, "locked": lk}
                        for _p, s, sv, lk in all_pairs]
            # Come back to the tab this Workspace was left on (index 0 the
            # first time it is loaded in a session).
            start = self._ws_spot_for(name, side, valid)
            if side == "left":
                self.left_tabs     = list(valid)
                self.left_tab_idx  = start
                self.left_tab_meta = new_meta
            else:
                self.right_tabs     = list(valid)
                self.right_tab_idx  = start
                self.right_tab_meta = new_meta
            self._ws_active[side] = True   # this side is now Workspace-backed
            self._ws_name[side]   = name
            panel = self.left_panel if side == "left" else self.right_panel
            self._apply_tab_sort(side)
            panel.change_directory(valid[start])

        if apply_left:
            _load_side("left",  ws.get("left",  []), ws.get("left_sort",  []),
                       ws.get("left_extra",  []), ws.get("left_extra_sort",  []),
                       ws.get("left_lock",   []), ws.get("left_extra_lock",  []))
        if apply_right:
            _load_side("right", ws.get("right", []), ws.get("right_sort", []),
                       ws.get("right_extra", []), ws.get("right_extra_sort", []),
                       ws.get("right_lock",  []), ws.get("right_extra_lock", []))
        # If we loaded base-only, forget the previously remembered extras
        if base_only:
            if apply_left:
                ws["left_extra"] = []; ws["left_extra_sort"] = []
                ws["left_extra_lock"] = []
            if apply_right:
                ws["right_extra"] = []; ws["right_extra_sort"] = []
                ws["right_extra_lock"] = []
            self._save_workspaces()
        # Restore this Workspace's F8 tab pairs (whole-profile property)
        self._load_pairs_from(ws)
        # Redraw the workspace bar so the just-loaded workspace shows as active
        self._render_workspace_bar()
        # …and only now, with everything in place, say which of its folders are
        # not there and ask what to do about them — once for the whole
        # Workspace rather than a surprise per tab (2026-09-18).  It runs after
        # the redraw so the dialog sits over a finished window, and it is the
        # LAST thing, so a Workspace still loads normally if it is dismissed.
        try:
            self.after_idle(lambda: self.check_workspace_folders(name))
        except Exception:
            pass

    def _ws_save_dialog(self):
        """Dialog for naming (or overwriting) a workspace."""
        existing = sorted(self.workspaces.keys())

        dlg = tk.Toplevel(self)
        _setup_toplevel(dlg, "Save workspace", self)
        dlg.resizable(False, False)

        body = ttk.Frame(dlg, padding=14)
        body.pack(fill="x")

        ttk.Label(body, text="Workspace name:").grid(
            row=0, column=0, sticky="w", pady=(0, 4))
        name_var = tk.StringVar()
        name_ent = tk.Entry(body, textvariable=name_var, width=28,
                            insertofftime=0, insertontime=9999999)
        name_ent.grid(row=0, column=1, sticky="we", padx=(6, 0), pady=(0, 4))
        name_ent.focus_set()
        body.columnconfigure(1, weight=1)

        if existing:
            ttk.Label(body, text="Or pick existing:").grid(
                row=1, column=0, sticky="w", pady=(6, 2))
            lb_frame = ttk.Frame(body)
            lb_frame.grid(row=2, column=0, columnspan=2, sticky="we")
            lb = tk.Listbox(lb_frame, height=min(len(existing), 6),
                            selectmode="single", exportselection=False)
            for e in existing:
                lb.insert("end", e)
            lb.pack(side="left", fill="both", expand=True)
            sb = ttk.Scrollbar(lb_frame, orient="vertical", command=lb.yview)
            sb.pack(side="right", fill="y")
            lb.configure(yscrollcommand=sb.set)
            lb.bind("<<ListboxSelect>>",
                    lambda e: name_var.set(lb.get(lb.curselection()[0]))
                    if lb.curselection() else None)

        # Which sides to include in the saved snapshot
        ttk.Separator(body).grid(row=3, column=0, columnspan=2,
                                  sticky="we", pady=(10, 6))
        ttk.Label(body, text="Include:").grid(
            row=4, column=0, sticky="w")
        inc_frame = ttk.Frame(body)
        inc_frame.grid(row=4, column=1, sticky="w")
        inc_left  = tk.BooleanVar(value=True)
        inc_right = tk.BooleanVar(value=True)
        ttk.Checkbutton(inc_frame, text="Left", variable=inc_left).pack(
            side="left", padx=(0, 8))
        ttk.Checkbutton(inc_frame, text="Right",  variable=inc_right).pack(
            side="left")

        lbl_st = ttk.Label(dlg, text="", foreground="red", anchor="w")
        lbl_st.pack(fill="x", padx=14, pady=(0, 2))

        def _do_save(e=None):
            n = name_var.get().strip()
            if not n:
                lbl_st.configure(text="⚠  Please enter a name.")
                return
            if not inc_left.get() and not inc_right.get():
                lbl_st.configure(text="⚠  Select at least one panel to include.")
                return
            snap: dict = {}
            # Saving bakes ALL current tabs (base + extra) into the base set and
            # clears the remembered extras, so nothing is left half-saved.
            if inc_left.get():
                snap["left"]       = list(self.left_tabs)
                snap["left_sort"]  = self._current_tab_sorts("left")
                snap["left_lock"]  = self._current_tab_locks("left")
                snap["left_extra"] = []
                snap["left_extra_sort"] = []
                snap["left_extra_lock"] = []
            if inc_right.get():
                snap["right"]       = list(self.right_tabs)
                snap["right_sort"]  = self._current_tab_sorts("right")
                snap["right_lock"]  = self._current_tab_locks("right")
                snap["right_extra"] = []
                snap["right_extra_sort"] = []
                snap["right_extra_lock"] = []
            # Preserve existing side if not included in this save
            if n in self.workspaces:
                existing_snap = self.workspaces[n]
                for key in ("left",  "left_sort",  "left_lock",
                            "left_extra",  "left_extra_sort",  "left_extra_lock",
                            "right", "right_sort", "right_lock",
                            "right_extra", "right_extra_sort", "right_extra_lock"):
                    if key not in snap and key in existing_snap:
                        snap[key] = existing_snap[key]
            self._store_pairs_into(snap)       # keep the F8 tab pairs with it
            self.workspaces[n] = snap
            self._save_workspaces()
            # The saved tabs are now "baked in": drop their temporary marker
            if inc_left.get():
                for m in self.left_tab_meta:
                    m["saved"] = True
                self._ws_active["left"] = True
                self._ws_name["left"]   = n
            if inc_right.get():
                for m in self.right_tab_meta:
                    m["saved"] = True
                self._ws_active["right"] = True
                self._ws_name["right"]   = n
            self._render_workspace_bar()
            self._render_tab_bar("left")
            self._render_tab_bar("right")
            dlg.destroy()

        name_ent.bind("<Return>", _do_save)

        btn_row = ttk.Frame(dlg, padding=(14, 4, 14, 12))
        btn_row.pack(fill="x")
        ttk.Button(btn_row, text="Save",   command=_do_save,      width=12).pack(side="left")
        ttk.Button(btn_row, text="Cancel", command=dlg.destroy,   width=10).pack(side="right")

    def _ws_context_menu(self, event, name: str):
        """Right-click menu on a workspace button."""
        menu = tk.Menu(self, tearoff=0)
        menu.add_command(
            label=f"Load '{name}'  (base + extra tabs)",
            command=lambda: self._ws_load(name))
        menu.add_command(
            label="Load base tabs only  (drop remembered extras)",
            command=lambda: self._ws_load(name, base_only=True))
        menu.add_separator()
        # Update the saved tabs from what is open now — no popup, three choices.
        menu.add_command(
            label="Update BOTH panels with current tabs",
            command=lambda: self._ws_update_apply(name, True, True))
        menu.add_command(
            label="Update LEFT panel with current tabs",
            command=lambda: self._ws_update_apply(name, True, False))
        menu.add_command(
            label="Update RIGHT panel with current tabs",
            command=lambda: self._ws_update_apply(name, False, True))
        menu.add_separator()
        menu.add_command(
            label="Rename…",
            command=lambda: self._ws_rename_dialog(name))
        menu.add_command(
            label="Duplicate…   (copy to a new name)",
            command=lambda: self._ws_duplicate_dialog(name))
        is_startup = (self.settings.get("startup_workspace", "") == name)
        menu.add_command(
            label=("★  Start with this workspace   (ON — click to turn off)"
                   if is_startup else "☆  Start with this workspace"),
            command=lambda: self._ws_toggle_startup(name))
        menu.add_separator()
        menu.add_command(
            label=f"Delete '{name}'",
            command=lambda: self._ws_delete(name))
        menu.tk_popup(event.x_root, event.y_root)

    def _ws_rename_dialog(self, old_name: str):
        new_name = _ask_text(self, "Rename", "New name:", initial=old_name)
        if not new_name or new_name == old_name:
            return
        new_name = new_name.strip()
        if new_name in self.workspaces:
            messagebox.showwarning(
                "Rename",
                f"A workspace named '{new_name}' already exists.",
                parent=self)
            return
        self.workspaces[new_name] = self.workspaces.pop(old_name)
        for side in ("left", "right"):
            if self._ws_name.get(side) == old_name:
                self._ws_name[side] = new_name
        self._save_workspaces()
        self._render_workspace_bar()

    def _ws_duplicate_dialog(self, old_name: str):
        """Copy a whole Workspace under a new name.

        The safe way to SPLIT one that has grown too many tabs: duplicate it,
        then delete the Cubase tabs from one copy and the VST tabs from the
        other.  Nothing is loaded or changed — the copy is written straight to
        workspaces.json, tabs, sorts, tab-pairs and all."""
        if old_name not in self.workspaces:
            return
        # Suggest "<name> 2", "<name> 3", … — the first one not taken.
        i = 2
        while f"{old_name} {i}" in self.workspaces:
            i += 1
        new_name = _ask_text(
            self, "Duplicate workspace",
            f"Copy '{old_name}' to a new workspace named:",
            initial=f"{old_name} {i}")
        if not new_name:
            return
        new_name = new_name.strip()
        if new_name == old_name:
            return
        if new_name in self.workspaces:
            messagebox.showwarning(
                "Duplicate",
                f"A workspace named '{new_name}' already exists.",
                parent=self)
            return
        try:
            # A deep copy through JSON — the snapshot is plain data, and this
            # way the two workspaces can never end up sharing a tab list.
            snap = json.loads(json.dumps(self.workspaces[old_name]))
        except Exception:
            snap = dict(self.workspaces[old_name])
        self.workspaces[new_name] = snap
        self._save_workspaces()
        self._render_workspace_bar()
        self._flash_status(f"Workspace '{old_name}' copied to '{new_name}'.")

    def _ws_update_apply(self, name: str, do_left: bool, do_right: bool):
        """Overwrite the given side(s) of a saved Workspace with the tabs open
        now — straight away, no popup.  Wired to the three context-menu items
        ("Update BOTH / LEFT / RIGHT panels with current tabs")."""
        if name not in self.workspaces:
            return
        snap = dict(self.workspaces.get(name, {}))
        if do_left:
            snap["left"]            = list(self.left_tabs)
            snap["left_sort"]       = self._current_tab_sorts("left")
            snap["left_lock"]       = self._current_tab_locks("left")
            snap["left_extra"]      = []
            snap["left_extra_sort"] = []
            snap["left_extra_lock"] = []
            for m in self.left_tab_meta:
                m["saved"] = True
            self._ws_active["left"] = True
            self._ws_name["left"]   = name
        if do_right:
            snap["right"]            = list(self.right_tabs)
            snap["right_sort"]       = self._current_tab_sorts("right")
            snap["right_lock"]       = self._current_tab_locks("right")
            snap["right_extra"]      = []
            snap["right_extra_sort"] = []
            snap["right_extra_lock"] = []
            for m in self.right_tab_meta:
                m["saved"] = True
            self._ws_active["right"] = True
            self._ws_name["right"]   = name
        self._store_pairs_into(snap)           # keep the tab pairs with it
        self.workspaces[name] = snap
        self._save_workspaces()
        self._render_workspace_bar()
        self._render_tab_bar("left")
        self._render_tab_bar("right")
        which = ("both panels" if (do_left and do_right)
                 else "left panel" if do_left else "right panel")
        self._flash_status(f"Workspace '{name}' updated ({which}).")

    def _ws_toggle_startup(self, name: str):
        """Right-click ▸ choose which Workspace loads automatically on start.
        Clicking the one already set turns start-up loading off again."""
        cur = self.settings.get("startup_workspace", "")
        self.settings["startup_workspace"] = "" if cur == name else name
        try:
            self.save_settings()
        except Exception:
            pass
        self._render_workspace_bar()
        if self.settings["startup_workspace"]:
            self._flash_status(f"'{name}' will load automatically on start.")
        else:
            self._flash_status("No workspace will load on start.")

    def _apply_window_title(self):
        """Title bar: "File Manager", plus the build stamp only when the
        setting "show_build_in_title" is on (Settings > General > Display)."""
        try:
            t = "File Manager"
            if self.settings.get("show_build_in_title", False):
                t += f"    \u00b7    build {_build_stamp()}"
            self.master.title(t)
        except Exception:
            pass

    def _apply_startup_workspace(self):
        """Load the chosen start-up Workspace (into BOTH panels) once at start."""
        name = self.settings.get("startup_workspace", "")
        if not name or name not in self.workspaces:
            return
        keep_l, keep_r = self._ws_apply_left.get(), self._ws_apply_right.get()
        self._ws_apply_left.set(True)
        self._ws_apply_right.set(True)
        try:
            self._ws_load(name)
        except Exception as exc:
            _log(f"Startup workspace '{name}' failed to load: {exc}")
        finally:
            self._ws_apply_left.set(keep_l)
            self._ws_apply_right.set(keep_r)

    def _ws_delete(self, name: str):
        if _ask_yes_no(
                "Delete workspace",
                f"Delete workspace '{name}'?",
                parent=self):
            self.workspaces.pop(name, None)
            for side in ("left", "right"):
                if self._ws_name.get(side) == name:
                    self._ws_name[side] = None
                    self._ws_active[side] = False
            self._save_workspaces()
            self._render_workspace_bar()
            self._render_tab_bar("left")
            self._render_tab_bar("right")

    # ── FTP mount / unmount ───────────────────────────────────────────────

    def mount_ftp_panel(self, side: str, site: dict):
        holder    = self.left_holder  if side == "left" else self.right_holder
        old_panel = self.left_panel   if side == "left" else self.right_panel
        try:
            old_panel.destroy()
        except Exception:
            pass
        panel = FTPPanel(holder, side, self, site)
        panel.pack(fill="both", expand=True)
        if side == "left":
            self.left_panel   = panel
            self.active_panel = "left"
        else:
            self.right_panel  = panel
            self.active_panel = "right"
        self.bind_panel_jumps(panel)     # a new tree needs its own jump keys
        self._update_disk_info()

    def unmount_ftp_panel(self, side: str):
        holder    = self.left_holder  if side == "left" else self.right_holder
        old_panel = self.left_panel   if side == "left" else self.right_panel
        try:
            old_panel.destroy()
        except Exception:
            pass
        panel = FilePanel(holder, side, self)
        panel.pack(fill="both", expand=True)
        if side == "left":
            self.left_panel  = panel
        else:
            self.right_panel = panel
        self.bind_panel_jumps(panel)     # a new tree needs its own jump keys
        self._update_disk_info()

    def _download_to_help(self, ftp_panel, remote_path: str) -> str:
        local_dir = self.choose_save_path(str(HELP_DIR), os.path.basename(remote_path))
        os.makedirs(local_dir, exist_ok=True)
        dest = os.path.join(local_dir, os.path.basename(remote_path))
        ftp_panel.download_file(remote_path, dest)
        self.refresh_panels()
        return dest

    def open_ftp_client(self):
        FTPClientWindow(self)

    def open_search(self):
        """Open the (non-blocking) Search window."""
        SearchWindow(self)

    # ══════════════════════════════════════════════════════════════════════
    #  DEL 34 — Tools:  actions for every Total Commander parity feature
    # ══════════════════════════════════════════════════════════════════════

    # ── Side-file persistence ─────────────────────────────────────────────

    def save_hotlist(self):
        _save_json_list(HOTLIST_PATH, self.hotlist)

    def save_command_lib(self):
        _save_json_list(COMMANDS_PATH, self.command_lib)

    # ── Selection helpers ─────────────────────────────────────────────────

    def _selected_local_paths(self, need: str = "any") -> list:
        """Selected paths in the active panel, with a friendly error if none.

        need: 'any' | 'file' | 'dir'
        """
        panel = self.get_active_panel()
        if getattr(panel, "is_remote", False):
            messagebox.showinfo("Not available",
                                "This works on local folders only — "
                                "the active panel is mounted on FTP.")
            return []
        paths = panel.get_all_selected()
        if need == "file":
            paths = [p for p in paths if os.path.isfile(p)]
        elif need == "dir":
            paths = [p for p in paths if os.path.isdir(p)]
        if not paths:
            what = {"file": "file", "dir": "folder", "any": "item"}[need]
            messagebox.showinfo("Nothing selected",
                                f"Select at least one {what} first.")
        return paths

    # ── Multi-Rename (Ctrl+M) ─────────────────────────────────────────────

    def open_multi_rename(self):
        paths = self._selected_local_paths()
        if paths:
            MultiRenameWindow(self, paths)

    # ── Quick View (Ctrl+Q) ───────────────────────────────────────────────

    def toggle_quick_view(self):
        self.quickview.toggle()

    # ── Branch view (Ctrl+B / Ctrl+Shift+B) ───────────────────────────────

    def toggle_branch_view(self, with_dirs: bool = False):
        panel = self.get_active_panel()
        if getattr(panel, "is_remote", False):
            messagebox.showinfo("Branch view",
                                "Branch view works on local folders only.")
            return
        on = panel.toggle_branch_view(with_dirs)
        if on:
            n = len(panel.tree.get_children())
            self._flash_status(
                f"Branch view: {n} item(s) from {panel.current_path} and "
                f"everything below it")
        else:
            self._flash_status("Branch view off")

    def toggle_branch_view_dirs(self):
        self.toggle_branch_view(with_dirs=True)

    def _flash_status(self, text: str, ms: int = 4000):
        """Show a short message in the status bar, then restore the disk info."""
        try:
            self._left_disk.configure(text=text)
            self.after(ms, self._update_disk_info)
        except Exception:
            pass

    # ── Directory hotlist (Ctrl+D) ────────────────────────────────────────

    def open_hotlist(self):
        HotlistWindow(self)

    def add_current_to_hotlist(self):
        path = self.get_active_panel().current_path
        name = _ask_text(self, "Add to hotlist", "Name for this folder:",
                         initial=os.path.basename(path.rstrip("\\/")) or path)
        if name:
            self.hotlist.append({"name": name, "path": path})
            self.save_hotlist()
            _flash_ok(self, f"Added “{name}” to the hotlist.", "Hotlist")

    # ── Compare files ─────────────────────────────────────────────────────

    def open_compare(self):
        """Compare the selected file with its counterpart in the other panel."""
        left_p, right_p = self.get_active_panel(), self.get_inactive_panel()
        if getattr(left_p, "is_remote", False) or getattr(right_p, "is_remote", False):
            messagebox.showinfo("Compare", "Compare works on local files only.")
            return

        selected = [p for p in left_p.get_all_selected() if os.path.isfile(p)]
        other    = [p for p in right_p.get_all_selected() if os.path.isfile(p)]

        if len(selected) >= 2:
            CompareFilesWindow(self, selected[0], selected[1])
            return
        if len(selected) == 1 and other:
            CompareFilesWindow(self, selected[0], other[0])
            return
        if len(selected) == 1:
            # Same name in the other panel is the common case
            candidate = os.path.join(right_p.current_path,
                                     os.path.basename(selected[0]))
            if os.path.isfile(candidate):
                CompareFilesWindow(self, selected[0], candidate)
                return
            picked = filedialog.askopenfilename(
                title="Compare with…", parent=self,
                initialdir=right_p.current_path)
            if picked:
                CompareFilesWindow(self, selected[0], picked)
            return
        messagebox.showinfo(
            "Compare",
            "Select two files in one panel, or one file in each panel.")

    # ── Synchronize directories ───────────────────────────────────────────

    def open_sync(self):
        left, right = self.left_panel, self.right_panel
        if getattr(left, "is_remote", False) or getattr(right, "is_remote", False):
            messagebox.showinfo("Synchronize",
                                "Synchronize works on local folders only.")
            return
        SyncWindow(self, left.current_path, right.current_path)

    # ── Duplicate finder ──────────────────────────────────────────────────

    def open_duplicates(self):
        panel = self.get_active_panel()
        if getattr(panel, "is_remote", False):
            messagebox.showinfo("Duplicates",
                                "The duplicate finder works on local folders only.")
            return
        DuplicateFinderWindow(self, panel.current_path)

    # ── Checksums ─────────────────────────────────────────────────────────

    def open_checksums(self):
        panel = self.get_active_panel()
        if getattr(panel, "is_remote", False):
            messagebox.showinfo("Checksums", "Checksums work on local files only.")
            return
        paths = panel.get_all_selected()
        # Selecting a .sfv/.md5/.sha* file means "verify this"
        if len(paths) == 1 and os.path.isfile(paths[0]) and \
                os.path.splitext(paths[0])[1].lower() in (
                    ".sfv", ".md5", ".sha1", ".sha256", ".sha512"):
            ChecksumWindow(self, [], verify_file=paths[0])
            return
        if not paths:
            paths = [os.path.join(panel.current_path, panel._fullname(iid))
                     for iid in panel.tree.get_children()
                     if panel._fullname(iid) != ".."]
            paths = [p for p in paths if os.path.isfile(p)]
        ChecksumWindow(self, paths)

    # ── Split / combine ───────────────────────────────────────────────────

    def open_split(self):
        paths = self._selected_local_paths("file")
        if not paths:
            return
        if len(paths) > 1:
            messagebox.showinfo("Split", "Select exactly one file to split.")
            return
        SplitFileWindow(self, paths[0], self.get_inactive_panel().current_path)

    def open_combine(self):
        paths = self._selected_local_paths("file")
        if not paths:
            return
        first = paths[0]
        # Accept any part — always start the join from .001
        stem, ext = os.path.splitext(first)
        if _re.fullmatch(r"\.\d{3}", ext):
            first = f"{stem}.001"
        combine_parts(self, first)

    # ── Print / export listing ────────────────────────────────────────────

    def open_print_listing(self):
        panel = self.get_active_panel()
        if getattr(panel, "is_remote", False):
            messagebox.showinfo("Print", "Listings can be exported for local folders.")
            return
        PrintListingWindow(self, panel.current_path)

    # ── Command bar / library ─────────────────────────────────────────────

    def toggle_command_bar(self):
        self.cmdbar.toggle()

    def open_command_library(self):
        CommandLibraryWindow(self)

    # ── Archives ──────────────────────────────────────────────────────────

    def open_archive_browser(self):
        paths = self._selected_local_paths("file")
        if not paths:
            return
        archive = next((p for p in paths if is_archive(p)), None)
        if archive is None:
            messagebox.showinfo(
                "Archive",
                "The selected file is not a supported archive.\n\n"
                "Supported: ZIP, RAR, 7z, TAR, GZ, BZ2, XZ, ISO, CAB")
            return
        ArchiveBrowser(self, self, archive)

    def pack_files_as(self):
        """Pack the selection, asking for the archive format first."""
        paths = self._selected_local_paths()
        if not paths:
            return

        top = tk.Toplevel(self)
        top.configure(bg=C_BG)
        top.resizable(False, False)
        _setup_toplevel(top, "Pack files", self, modal=True)

        default_name = (os.path.splitext(os.path.basename(paths[0]))[0]
                        if len(paths) == 1
                        else os.path.basename(
                            self.get_active_panel().current_path.rstrip("\\/"))
                        or "archive")
        v_fmt  = tk.StringVar(value="zip")
        v_name = tk.StringVar(value=default_name)
        v_dest = tk.StringVar(value=self.get_inactive_panel().current_path)

        body = tk.Frame(top, bg=C_BG, padx=16, pady=14)
        body.pack(fill="both", expand=True)
        tk.Label(body, text="📦  Pack files", bg=C_BG, fg=C_ACCENT,
                 font=("Segoe UI", 12, "bold")).pack(anchor="w")
        tk.Label(body, text=f"{len(paths)} item(s) selected", bg=C_BG, fg=C_FG_DIM,
                 font=("Segoe UI", 9)).pack(anchor="w", pady=(0, 10))

        r = tk.Frame(body, bg=C_BG)
        r.pack(fill="x", pady=3)
        tk.Label(r, text="Format:", bg=C_BG, fg=C_FG, width=10,
                 anchor="w").pack(side="left")
        ttk.Combobox(r, textvariable=v_fmt, width=14, state="readonly",
                     values=PACK_FORMATS).pack(side="left")

        r2 = tk.Frame(body, bg=C_BG)
        r2.pack(fill="x", pady=3)
        tk.Label(r2, text="Name:", bg=C_BG, fg=C_FG, width=10,
                 anchor="w").pack(side="left")
        e_name = tk.Entry(r2, textvariable=v_name, width=40, bg=C_BG2, fg=C_FG,
                          insertbackground=C_FG,
                          insertofftime=0, insertontime=9999999)
        e_name.pack(side="left")

        r3 = tk.Frame(body, bg=C_BG)
        r3.pack(fill="x", pady=3)
        tk.Label(r3, text="Into:", bg=C_BG, fg=C_FG, width=10,
                 anchor="w").pack(side="left")
        tk.Entry(r3, textvariable=v_dest, width=40, bg=C_BG2, fg=C_FG,
                 insertbackground=C_FG,
                 insertofftime=0, insertontime=9999999).pack(side="left")
        tk.Button(r3, text="…", width=3, bg="white", fg="black",
                  command=lambda: v_dest.set(
                      filedialog.askdirectory(parent=top, initialdir=v_dest.get())
                      or v_dest.get())).pack(side="left", padx=4)

        def do_pack(event=None):
            fmt = v_fmt.get()
            name = v_name.get().strip()
            dest = v_dest.get()
            if not name:
                messagebox.showerror("Pack", "Enter an archive name.", parent=top)
                return
            if not os.path.isdir(dest):
                messagebox.showerror("Pack", "Choose an existing target folder.",
                                     parent=top)
                return
            ext = PACK_EXT.get(fmt, ".zip")
            out = os.path.join(dest, name if name.lower().endswith(ext) else name + ext)
            if os.path.exists(out) and not _ask_yes_no(
                    "Pack", f"{os.path.basename(out)} already exists.\n\nOverwrite?",
                    parent=top):
                return
            top.destroy()
            self._run_pack(out, paths, fmt)

        btns = tk.Frame(body, bg=C_BG)
        btns.pack(fill="x", pady=(14, 0))
        tk.Button(btns, text="Cancel", bg="grey", fg="white", width=10,
                  command=top.destroy).pack(side="right", padx=3)
        tk.Button(btns, text="📦  Pack", bg="lightgreen", fg="black", width=11,
                  command=do_pack).pack(side="right", padx=3)
        top.bind("<Return>", do_pack)
        e_name.focus_set()

    def _run_pack(self, out_path: str, sources: list, fmt: str):
        dlg = _ProgressDialog(self, f"Packing {os.path.basename(out_path)}",
                              total=len(sources) or 1)

        def on_progress(i, total, name):
            dlg.post("progress", i, total, name)
            return not dlg.cancelled

        def worker():
            try:
                n = archive_create(out_path, sources, fmt, progress=on_progress)
                dlg.post("done")
                self.after(0, lambda: self._pack_done(out_path, n))
            except Exception as exc:
                dlg.post("done")
                # A cancelled job leaves a half-written archive behind
                if "Cancelled" in str(exc):
                    try:
                        os.remove(out_path)
                    except OSError:
                        pass
                    return
                self.after(0, lambda e=exc: messagebox.showerror(
                    "Pack", f"Could not create the archive:\n{e}"))

        threading.Thread(target=worker, daemon=True).start()

    def _pack_done(self, out_path: str, n: int):
        self.refresh_panels()
        _flash_ok(self, f"Packed {n} file(s) into\n{os.path.basename(out_path)}",
                  "Packed")

    def unpack_any(self):
        """Alt+F9 — unpack what is selected: archives, OR every archive inside
        the FOLDERS you picked.

        The folder half is Unpacker's "drag the folder in and it deals with
        it", without the dragging: mark one or several download folders, press
        Alt+F9, and each archive in them is queued.  Those extract WHERE THEY
        LIE, sub-folders and all — that is what a release folder wants, and it
        is what makes "rename the folder to UNPACKED-…" mean anything.  An
        archive you picked by name still goes to the other panel, as before.
        """
        paths = self._selected_local_paths("any")
        if not paths:
            return
        other = self.get_inactive_panel()
        # The other panel is only a usable destination when it is showing a
        # real folder — not an FTP mount, and not the inside of an archive.
        other_ok = (not getattr(other, "is_remote", False)
                    and not getattr(other, "archive_ctx", None))
        dest_other = (other.current_path if other_ok
                      else self.get_active_panel().current_path)
        # Archives found by walking a FOLDER used to always extract WHERE THEY
        # LIE.  That is right for a release folder, but it is not what you want
        # most of the time: unpacking onto a second drive is far faster than
        # unpacking onto the one you are reading from, and "the same folder" is
        # still available simply by pointing the other panel at it.  So the
        # other panel is now the default for those too — Settings ▸ Transfers ▸
        # Unpacking turns it back.
        to_other = bool(self.settings.get("unpack_dest_other", True)) and other_ok

        # A split set is ONE job however many of its parts turn up, so 43
        # .r-files — or a folder holding them — must not become 43 jobs.
        jobs, seen = [], set()

        def _add(archive: str, dest: str):
            try:
                st  = archive_start_of(archive)
                key = os.path.normcase(os.path.abspath(st))
            except Exception:
                return
            if key not in seen:
                seen.add(key)
                jobs.append((st, dest))

        n_dirs = in_place = 0
        for p in paths:
            if os.path.isfile(p):
                if is_archive(p):
                    _add(p, dest_other)
            elif os.path.isdir(p):
                n_dirs += 1
                before = len(jobs)
                for dirpath, _dirs, fnames in os.walk(p):
                    for fn in sorted(fnames):
                        if fn.startswith(TRASH_PREFIX):
                            continue        # deleted, just not purged yet
                        fp = os.path.join(dirpath, fn)
                        if is_archive(fp):
                            _add(fp, dest_other if to_other else dirpath)
                if not to_other:
                    in_place += len(jobs) - before

        if not jobs:
            messagebox.showinfo(
                "Unpack",
                ("Nothing to unpack in the folder(s) you picked."
                 if n_dirs else
                 "No supported archive selected.")
                + "\n\nSupported: ZIP, RAR, 7z, TAR, GZ, BZ2, XZ, ISO, CAB, "
                  "ARJ, LZH, ACE, Z\n"
                  "Pick FOLDERS and everything inside them is queued.")
            return

        n    = len(jobs)
        sets = sum(1 for st, _d in jobs if len(archive_part_files(st)) > 1)
        lines = []
        if in_place:
            lines.append(f"{in_place} found in {n_dirs} folder(s) — "
                         f"each unpacks where it lies")
        if n - in_place:
            where = ("found in folders + picked by name" if (n_dirs and to_other)
                     else "picked by name")
            lines.append(f"{n - in_place} {where}  →  {dest_other}")
            if not other_ok:
                lines.append("(the other panel is not a plain folder right now, "
                             "so this side's folder is used)")
        if sets:
            lines.append(f"{sets} split set{'s' if sets != 1 else ''} — "
                         f"{'each counts' if sets != 1 else 'it counts'} as one job")
        if not _ask_yes_no("Unpack",
                           f"Extract {n} archive(s)?\n\n·  "
                           + "\n·  ".join(lines)):
            return

        # Through the Task Queue: it runs in the background, one at a time,
        # can be paused or cancelled, waits for parts that are still being
        # downloaded, and cleans up after a failed attempt.
        for st, dest in jobs:
            self.task_queue_mgr.add_unpack(st, dest)
        # Unpacking is the one job where "it is in the queue" is not enough to
        # go on: nothing visibly happens in the panels for minutes.  Show the
        # queue window (in the background — it never takes the keyboard) so
        # there is something to watch.
        if self.settings.get("unpack_show_queue", True):
            try:
                self.task_queue_mgr.open_window(activate=False)
            except Exception as exc:
                _log(f"Unpack: could not show the queue: {exc}")
        self._after_task_enqueued(f"Unpack queued — {n} archive(s)")

    def _after_unpack(self, task, archive: str, target: str):
        """Main thread, after one archive came out whole.

        Two optional tidy-ups, both off unless asked for: clear the archive
        away (the WHOLE split set, or 42 orphaned .r-files stay behind), and
        mark the folder it came from as done — which is the marker his FTP
        flow reads."""
        try:
            self.refresh_panels()
        except Exception:
            pass
        s = self.settings

        if s.get("unpack_delete_after", False):
            parts = list(getattr(task, "parts", None) or [archive])
            gone = [p for p in parts if os.path.isfile(p)]
            if gone:
                try:
                    # To the trash, not off the disk: a bad unpack is then one
                    # Restore away, and the tiered purge cleans up later.
                    n = self.move_to_trash(gone)
                    self._flash_status(
                        f"Unpacked — {n} archive file(s) moved to the trash")
                except Exception as exc:
                    _log(f"Unpack: could not clear the archive away: {exc}")

        if s.get("unpack_mark_source_folder", False):
            self._mark_folder_unpacked(archive)

    def _mark_folder_unpacked(self, archive: str):
        """Rename the folder the archive sits in to  UNPACKED-<name>.

        Left alone when it is a drive root, when it is already marked, or when
        the new name is taken.  The download-manager prefixes are stripped
        first, so nothing ever becomes UNPACKED-DOWNLOADING-…"""
        try:
            folder = Path(archive).parent
            name   = folder.name
            if (not name
                    or name.upper().startswith("UNPACKED-")
                    or folder == folder.parent
                    or folder == Path.home()):
                return
            # DOWNLOADED- was missing from this list, which is the one his own
            # FTP flow actually writes: DOWNLOADING- while it runs, DOWNLOADED-
            # when it is whole.  So the folder he most wanted marked became
            # UNPACKED-DOWNLOADED-Some.Film.2026 — the prefix stacked instead
            # of being replaced.  Longest first, or DOWNLOADING would never be
            # reached past DOWNLOAD.
            clean = _re.sub(
                r"^(DOWNLOADING|DOWNLOADED|DOWNLOAD|UNPACKING|UNPACKED"
                r"|INCOMPLETE|FETCHING|FETCHED|DONE)[_\-]+",
                "", name, flags=_re.IGNORECASE) or name
            new_folder = folder.parent / f"UNPACKED-{clean}"
            if new_folder.exists():
                _log(f"Unpack: folder mark skipped, {new_folder.name} exists")
                return
            os.rename(str(folder), str(new_folder))
            try:
                self.tagstore.remap([(str(folder), str(new_folder))])
            except Exception:
                pass
            self._flash_status(f"Folder marked  →  UNPACKED-{clean}")
            self.refresh_panels()
        except Exception as exc:
            _log(f"Unpack: could not mark the folder: {exc}")

    def _unpack_done(self, done: int, errors: list, dest: str):
        self.refresh_panels()
        if errors:
            messagebox.showerror("Unpack",
                                 f"Extracted {done}.\n\nFailed:\n"
                                 + "\n".join(errors[:10]))
        else:
            _flash_ok(self, f"Extracted {done} archive(s) into\n{dest}", "Extracted")

    # ── Auto-refresh ──────────────────────────────────────────────────────

    def apply_date_policy(self):
        """Mirror the date settings into the module-level policy.

        The archive helpers are plain functions with no access to settings,
        so they read DATE_POLICY instead.
        """
        DATE_POLICY["unpack"] = bool(self.settings.get("keep_dates_unpack", True))
        DATE_POLICY["copy"] = bool(self.settings.get("keep_dates_copy", True))

    def toggle_folders_first(self):
        """Group folders above files when sorting, or mix them together."""
        new = not self.settings.get("sort_folders_first", True)
        self.settings["sort_folders_first"] = new
        for panel in (self.left_panel, self.right_panel):
            if not getattr(panel, "is_remote", False):
                panel._reapply_sort()
        self._flash_status(
            "Folders first — folders stay above files, sorted among themselves"
            if new else
            "Folders mixed in with files — one list, sorted together")

    def toggle_auto_refresh(self):
        on = self.folder_watcher.toggle()
        self._flash_status(
            "Auto-refresh ON — panels follow changes on disk" if on
            else "Auto-refresh OFF — press Ctrl+R to refresh manually")

    # ── Shortcuts ─────────────────────────────────────────────────────────

    def open_shortcut_config(self):
        ShortcutConfigWindow(self)

    # ── Help dialog ───────────────────────────────────────────────────────

    def _show_help(self):
        top = tk.Toplevel(self)
        _setup_toplevel(top, "Help — File Manager", self)
        top.geometry("640x520")
        top.resizable(True, True)

        txt = tk.Text(
            top, wrap="word", font=("Consolas", 10),
            padx=12, pady=10, relief="flat",
            insertofftime=0,
        )
        _no_blink(txt)
        sb = ttk.Scrollbar(top, orient="vertical", command=txt.yview)
        txt.configure(yscrollcommand=sb.set)
        sb.pack(side="right", fill="y")
        txt.pack(fill="both", expand=True)
        txt.insert("1.0", HELP_TEXT)
        txt.configure(state="disabled")

        frm = ttk.Frame(top)
        frm.pack(fill="x", pady=4)
        ttk.Button(frm, text="Close", command=top.destroy).pack(side="right", padx=8)

    # ── About dialog ──────────────────────────────────────────────────────

    def _show_about(self):
        top = tk.Toplevel(self)
        _setup_toplevel(top, "About File Manager", self)
        top.configure(bg=C_BG3)
        top.resizable(False, False)

        # Header
        hdr = tk.Frame(top, bg=C_BG3)
        hdr.pack(fill="x")
        tk.Label(hdr, text="🗂", bg=C_BG3, fg=C_ACCENT,
                 font=("Segoe UI", 36)).pack(pady=(18, 0))
        tk.Label(hdr, text="File Manager",
                 bg=C_BG3, fg=C_ACCENT,
                 font=("Segoe UI", 20, "bold")).pack()
        tk.Label(hdr, text="Dual-panel file manager with FTP support",
                 bg=C_BG3, fg=C_FG_DIM,
                 font=("Segoe UI", 9, "italic")).pack(pady=(2, 0))
        tk.Label(hdr, text=f"build  {_build_stamp()}   (this is the running version)",
                 bg=C_BG3, fg=C_ACCENT,
                 font=("Segoe UI", 8, "bold")).pack(pady=(0, 10))
        tk.Frame(top, bg=C_SEP, height=1).pack(fill="x", padx=20)

        # Author
        tk.Label(top, text='Created by  Lars "Issu" Olsson',
                 bg=C_BG3, fg=C_FG,
                 font=("Segoe UI", 10, "bold")).pack(pady=(14, 0))

        # What's new
        tk.Frame(top, bg=C_SEP, height=1).pack(fill="x", padx=20, pady=(10, 0))
        tk.Label(top, text="Recent additions",
                 bg=C_BG3, fg=C_ACCENT,
                 font=("Segoe UI", 9, "bold")).pack(pady=(8, 2))
        changelog = (
            "• Workspaces remember extra tabs (half-save); base tabs protected\n"
            "• Independent file / folder sort (left-click files, right-click folders)\n"
            "• Backup rename (Ctrl+Alt+Shift+B) + 'Backup-rename old' on conflicts\n"
            "• Task Queue runs in a corner, grouped by day with per-row times\n"
            "• Home/End jump to first/last row; scrollable, colour-coded tabs\n"
            "• Multi-Rename, Compare, Sync, Duplicates, Quick View, Branch view\n"
            "• RAR/7z/TAR/GZ/ISO/CAB, Checksums, Split & Combine, hotlist\n"
            "• Note: the title bar shows the build time of the running version"
        )
        tk.Label(top, text=changelog,
                 bg=C_BG3, fg=C_FG_DIM,
                 font=("Segoe UI", 8),
                 justify="left").pack(padx=24, anchor="w", pady=(0, 4))

        # Documentation link
        DOC_URL = (
            "https://docs.google.com/document/d/"
            "1B6y3CP-DafUKoXF9Apg4BpEl2m1j0kghRgD7lweF41s/edit?usp=sharing"
        )
        doc_lbl = tk.Label(top, text="📄  View documentation",
                           bg=C_BG3, fg=C_ACCENT,
                           font=("Segoe UI", 9, "underline"),
                           cursor="hand2")
        doc_lbl.pack(pady=(6, 2))
        doc_lbl.bind("<Button-1>", lambda e: webbrowser.open(DOC_URL))
        doc_lbl.bind("<Enter>",    lambda e: doc_lbl.configure(fg="#b4d4ff"))
        doc_lbl.bind("<Leave>",    lambda e: doc_lbl.configure(fg=C_ACCENT))

        tk.Frame(top, bg=C_SEP, height=1).pack(fill="x", padx=20, pady=(14, 0))

        # Donation section
        tk.Label(top, text="☕  If you enjoy File Manager, a small gift is always welcome!",
                 bg=C_BG3, fg=C_FG_DIM,
                 font=("Segoe UI", 8, "italic"),
                 wraplength=300, justify="center").pack(pady=(10, 6))

        donate_frame = tk.Frame(top, bg="#252535", padx=16, pady=10)
        donate_frame.pack(fill="x", padx=20, pady=(0, 6))

        REVOLUT_URL = "https://revolut.me/lars72oeh"
        PAYPAL_URL  = "https://paypal.me/issusbarn"
        WISE_URL    = "https://wise.com/pay/me/larsdenniso"

        for label, url in [("💳 Revolut", REVOLUT_URL),
                            ("🅿 PayPal",  PAYPAL_URL),
                            ("🌐 Wise",    WISE_URL)]:
            lnk = tk.Label(donate_frame, text=label,
                           bg="#252535", fg=C_ACCENT,
                           font=("Segoe UI", 9, "underline"),
                           cursor="hand2")
            lnk.pack(anchor="w", pady=1)
            lnk.bind("<Button-1>", lambda e, u=url: webbrowser.open(u))
            lnk.bind("<Enter>",    lambda e, w=lnk: w.configure(fg="#b4d4ff"))
            lnk.bind("<Leave>",    lambda e, w=lnk: w.configure(fg=C_ACCENT))

        ttk.Button(top, text="Close", command=top.destroy).pack(pady=(8, 16))

    # ── Settings dialog ───────────────────────────────────────────────────

    def _show_settings(self):
        top = tk.Toplevel(self)
        _setup_toplevel(top, "Settings — File Manager", self)
        # Height is adjustable now: the Customization tab holds a list.
        top.resizable(True, True)
        top.minsize(520, 400)

        nb = ttk.Notebook(top)
        nb.pack(fill="both", expand=True, padx=6, pady=6)

        # ════════════════════════════════════════════════════════════
        # Tab 0 – General (default sort, task queue, backup folder)
        # ════════════════════════════════════════════════════════════
        # revAV — this is by far the tallest tab (it asks for ~1874px) and the
        # window is capped to the desktop, so twelve controls used to sit below
        # the bottom edge with no way to reach them: both sort dropdowns, the
        # cursor-trace tick and its log button, both Task Queue ticks, the
        # backup folder, Size grouping, reader extensions, "the reader can EDIT
        # and save" and the empty-folder colour.  It scrolls now, exactly the
        # way the Transfers tab does.  The inner frame KEEPS the name tab_gen,
        # so everything built below is untouched — it just lives on a canvas.
        tab_gen_outer = ttk.Frame(nb)
        nb.add(tab_gen_outer, text="  General  ")
        _gen_canvas = tk.Canvas(tab_gen_outer, highlightthickness=0,
                                bg=(ttk.Style().lookup("TFrame", "background")
                                    or "#f0f0f0"))
        _gen_sb = ttk.Scrollbar(tab_gen_outer, orient="vertical",
                                command=_gen_canvas.yview)
        _gen_canvas.configure(yscrollcommand=_gen_sb.set)
        # Scrollbar first, or the expanding canvas leaves it 1 px wide.
        _gen_sb.pack(side="right", fill="y")
        _gen_canvas.pack(side="left", fill="both", expand=True)
        tab_gen = ttk.Frame(_gen_canvas, padding=14)
        _gen_id = _gen_canvas.create_window((0, 0), window=tab_gen, anchor="nw")
        tab_gen.bind(
            "<Configure>",
            lambda e: _gen_canvas.configure(scrollregion=_gen_canvas.bbox("all")))
        _gen_canvas.bind(
            "<Configure>",
            lambda e: _gen_canvas.itemconfig(_gen_id, width=e.width))

        def _gen_wheel(e):
            _gen_canvas.yview_scroll(-1 * (e.delta // 120), "units")
            return "break"

        _gen_canvas.bind("<MouseWheel>", _gen_wheel)

        # ── Default sort order ────────────────────────────────────────
        ttk.Label(tab_gen, text="Default sort order for a new tab",
                  font=("", 0, "bold")).grid(
            row=0, column=0, columnspan=3, sticky="w", pady=(0, 6))

        _sort_cols = [
            ("Name",       "#0"),
            ("Type",       "type"),
            ("Size",       "size"),
            ("Modified",   "modified"),
            ("Attributes", "attributes"),
        ]
        _col_labels_by_id = {cid: lbl for lbl, cid in _sort_cols}
        _label_to_id      = {lbl: cid for lbl, cid in _sort_cols}

        df = self.settings.get("default_sort_files", ["modified", True])
        dd = self.settings.get("default_sort_dirs",  ["#0", False])

        ttk.Label(tab_gen, text="Files by:").grid(row=1, column=0, sticky="w", pady=3)
        var_fcol = tk.StringVar(value=_col_labels_by_id.get(df[0], "Modified"))
        ttk.Combobox(tab_gen, textvariable=var_fcol, state="readonly", width=14,
                     values=[lbl for lbl, _ in _sort_cols]).grid(
            row=1, column=1, sticky="w", padx=(4, 8), pady=3)
        var_frev = tk.BooleanVar(value=bool(df[1]) if len(df) > 1 else True)
        ttk.Checkbutton(tab_gen, text="Descending (newest / largest first)",
                        variable=var_frev).grid(row=1, column=2, sticky="w", pady=3)

        ttk.Label(tab_gen, text="Folders by:").grid(row=2, column=0, sticky="w", pady=3)
        var_dcol = tk.StringVar(value=_col_labels_by_id.get(dd[0], "Name"))
        ttk.Combobox(tab_gen, textvariable=var_dcol, state="readonly", width=14,
                     values=[lbl for lbl, _ in _sort_cols]).grid(
            row=2, column=1, sticky="w", padx=(4, 8), pady=3)
        var_drev = tk.BooleanVar(value=bool(dd[1]) if len(dd) > 1 else False)
        ttk.Checkbutton(tab_gen, text="Descending",
                        variable=var_drev).grid(row=2, column=2, sticky="w", pady=3)

        ttk.Label(
            tab_gen,
            text="Tip: left-click a column header sorts files, right-click sorts\n"
                 "folders — so you can keep files by date and folders A→Z.\n"
                 "Per-tab sort is remembered for the session; re-save a\n"
                 "Workspace to keep it.",
            foreground="#888888",
        ).grid(row=3, column=0, columnspan=3, sticky="w", pady=(2, 10))

        # ── Navigation ────────────────────────────────────────────────
        # Its own container, so the rows below keep the numbers they had.
        _navbox = ttk.Frame(tab_gen)
        _navbox.grid(row=4, column=0, columnspan=3, sticky="ew", pady=(2, 10))
        ttk.Separator(_navbox, orient="horizontal").pack(fill="x", pady=(0, 10))
        ttk.Label(_navbox, text="Navigation",
                  font=("", 0, "bold")).pack(anchor="w", pady=(0, 4))
        var_drvmem = tk.BooleanVar(
            value=bool(self.settings.get("drive_memory", True)))
        ttk.Checkbutton(
            _navbox,
            text="Remember where I was on each drive (per panel)",
            variable=var_drvmem).pack(anchor="w")
        ttk.Label(
            _navbox,
            text="On (default): picking a drive from the drive menu returns to the\n"
                 "folder that panel last stood in on that drive, instead of dropping\n"
                 "you in the root every time.  The menu entry shows where it will go\n"
                 "(“D:\\  💾 Backup   ⤷ Photos\\2026”), and the ↖ toolbar button still\n"
                 "jumps to the root whenever you do want the root.\n"
                 "Left and right panel remember separately; the memory survives a\n"
                 "restart and is forgotten for a drive whose folder no longer exists.",
            foreground="#888888", justify="left",
        ).pack(anchor="w")
        ttk.Separator(_navbox, orient="horizontal").pack(fill="x", pady=(10, 0))

        # ── Name clashes ──────────────────────────────────────────────
        # Packed inside the same container as Navigation (below its closing
        # separator) so the gridded rows below keep the numbers they had.
        _clashbox = ttk.Frame(_navbox)
        _clashbox.pack(fill="x", pady=(10, 0))
        ttk.Label(_clashbox, text="When a copy hits a name clash",
                  font=("", 0, "bold")).pack(anchor="w", pady=(0, 4))
        var_cmode = tk.StringVar(
            value=str(self.settings.get("conflict_alert_mode", "bar")))
        for _val, _txt, _why in (
            ("bar",    "Ask on a bar in THIS window  (above the status bar)",
             "A red strip appears at the bottom of the file manager with the file\n"
             "names, both dates and sizes, and the five answers as buttons.  It can\n"
             "never cover the panels and can never end up behind another program.\n"
             "Its first answer is ARMED, so Enter takes it and ←/→ walk to another;\n"
             "Esc (or ↑/↓) hands the keyboard back to the file list.  Ctrl+Alt+1…5\n"
             "answer it from anywhere."),
            ("dialog", "Stop and ask straight away  (one dialog per file)",
             "The old behaviour: the copy stops on the first clash and a dialog\n"
             "comes up on top, with “apply to all remaining” on it.  Nothing is\n"
             "ever missed — but every clash interrupts what you were doing."),
            ("queue",  "Say nothing — park it in the Task Queue",
             "The job waits in the queue and the ⚡ toolbar button turns into a red\n"
             "“⚠ ANSWER”.  Quietest, but nothing happens until you go and look."),
        ):
            ttk.Radiobutton(_clashbox, text=_txt, value=_val,
                            variable=var_cmode).pack(anchor="w")
            ttk.Label(_clashbox, text=_why, foreground="#888888",
                      justify="left").pack(anchor="w", padx=(22, 0), pady=(0, 4))

        _tracebox = ttk.Frame(_navbox)
        _tracebox.pack(fill="x", pady=(10, 0))
        ttk.Label(_tracebox, text="Cursor trace log",
                  font=("", 0, "bold")).pack(anchor="w", pady=(0, 2))
        var_trace = tk.BooleanVar(
            value=bool(self.settings.get("trace_cursor", True)))
        ttk.Checkbutton(
            _tracebox,
            text="Write down everything that moves a panel cursor",
            variable=var_trace).pack(anchor="w")
        ttk.Label(
            _tracebox,
            text="On (default).  Every Tab, click, refresh and Enter writes one line\n"
                 "holding the full cursor state of BOTH panels — which row is blue,\n"
                 "which is grey, where the keyboard cursor is, what Enter would act\n"
                 "on.  It is what turns \u201cthe cursor jumped again\u201d into a\n"
                 "line that names the call that moved it.  It prunes itself, so it\n"
                 "never grows past the window below.",
            foreground="#888888", justify="left").pack(anchor="w", padx=(22, 0))
        _trow = ttk.Frame(_tracebox)
        _trow.pack(anchor="w", padx=(22, 0), pady=(4, 0))
        ttk.Label(_trow, text="Keep the last").pack(side="left")
        var_thours = tk.StringVar(value=str(self.settings.get("trace_hours", 48)))
        ttk.Spinbox(_trow, from_=1, to=720, width=5,
                    textvariable=var_thours).pack(side="left", padx=4)
        ttk.Label(_trow, text="hours  (anything older is dropped at startup "
                              "and every half hour)").pack(side="left")
        ttk.Button(_trow, text="Open the log\u2026",
                   command=self.open_trace_log).pack(side="left", padx=(12, 0))

        var_ckeys = tk.BooleanVar(
            value=bool(self.settings.get("conflict_bar_keys", True)))
        ttk.Checkbutton(
            _clashbox,
            text="The bar arms its first answer — Enter answers, ←/→ pick another",
            variable=var_ckeys).pack(anchor="w", pady=(6, 0))
        ttk.Label(
            _clashbox,
            text="On (default): the moment the bar appears the keyboard cursor sits on\n"
                 "“1  Overwrite old”, so a plain Enter answers it; ←/→ walk along the\n"
                 "row (round the ends), Home/End jump to either end, and Esc — or ↑/↓ —\n"
                 "hand the keyboard straight back to the file list.  Off: the bar never\n"
                 "touches the keyboard, exactly as before, and only Ctrl+Alt+1…5 or the\n"
                 "mouse answer it.  Either way the bar never grabs the keys while you\n"
                 "are typing in a rename box or a dialog field.",
            foreground="#888888", justify="left").pack(anchor="w", padx=(22, 0))

        var_cskip = tk.BooleanVar(
            value=bool(self.settings.get("conflict_skip_identical", False)))
        ttk.Checkbutton(
            _clashbox,
            text="Do not ask when the two files are identical (same size AND same date)",
            variable=var_cskip).pack(anchor="w", pady=(4, 0))
        ttk.Label(
            _clashbox,
            text="On: such a file is skipped silently — nothing is overwritten and\n"
                 "nothing is lost, because the file already there IS the file being\n"
                 "copied.  This is what stops re-copying the same folder from asking\n"
                 "the same questions over again.  (Folders are never treated this\n"
                 "way; their contents are always walked.)",
            foreground="#888888", justify="left").pack(anchor="w", padx=(22, 0))

        ttk.Label(_clashbox, text="Default width of a saved auto-rule",
                  font=("", 0, "bold")).pack(anchor="w", pady=(10, 2))
        _scope_row = ttk.Frame(_clashbox)
        _scope_row.pack(anchor="w")
        ttk.Label(_scope_row, text="From:").pack(side="left")
        var_rsrc = tk.StringVar(
            value=_RULE_SCOPE_LABEL.get(
                int(self.settings.get("rule_scope_src", 0) or 0), "This folder"))
        ttk.Combobox(_scope_row, textvariable=var_rsrc, state="readonly", width=13,
                     values=[lbl for lbl, _n in _RULE_SCOPES]).pack(side="left", padx=(4, 12))
        ttk.Label(_scope_row, text="To:").pack(side="left")
        var_rdst = tk.StringVar(
            value=_RULE_SCOPE_LABEL.get(
                int(self.settings.get("rule_scope_dst", 0) or 0), "This folder"))
        ttk.Combobox(_scope_row, textvariable=var_rdst, state="readonly", width=13,
                     values=[lbl for lbl, _n in _RULE_SCOPES]).pack(side="left", padx=4)
        ttk.Label(
            _clashbox,
            text="A rule always covers the sub-folders of the folder it names.  These\n"
                 "two decide which folder gets written down when you tick “Always\n"
                 "auto-resolve this” in the Task Queue: the folder you actually copied\n"
                 "to, or one of its parents.\n"
                 "Why it matters: saving into a working folder makes a new dated\n"
                 "sub-folder every day (…\\Claude_working\\2026-08-29\\).  A rule on the\n"
                 "exact folder is dead tomorrow; the same rule saved “1 level up” sits\n"
                 "on the working folder and covers every dated folder ever made under\n"
                 "it.  Both pickers can still be changed per rule in the Task Queue,\n"
                 "and every rule stays visible in ⚖ Smart-queue conflict rules.\n"
                 "A rule can also be tied to one Workspace there, so it only applies\n"
                 "while that Workspace is loaded.",
            foreground="#888888", justify="left").pack(anchor="w", pady=(4, 0))
        ttk.Separator(_clashbox, orient="horizontal").pack(fill="x", pady=(10, 0))

        # ── Task queue behaviour ──────────────────────────────────────
        ttk.Label(tab_gen, text="Task queue",
                  font=("", 0, "bold")).grid(
            row=5, column=0, columnspan=3, sticky="w", pady=(0, 4))
        # (The old "show the queue on each copy" tick was never read by any
        # code — this is the setting that actually decides anything.)
        var_qopen = tk.BooleanVar(
            value=bool(self.settings.get("queue_alert_front", False)))
        ttk.Checkbutton(
            tab_gen,
            text="Bring the Task Queue window to the FRONT when a job is "
                 "waiting for you",
            variable=var_qopen).grid(row=6, column=0, columnspan=3, sticky="w")
        _qbox = ttk.Frame(tab_gen)
        _qbox.grid(row=7, column=0, columnspan=3, sticky="w", pady=(0, 10))
        ttk.Label(
            _qbox,
            text="Where the Task Queue window SITS is the ⚡ toolbar button's job\n"
                 "now — the old “📌 On top” tick here, and the 📌 / ⏱ pair on the\n"
                 "queue's own toolbar, are gone.  LEFT-click ⚡ to step through:\n"
                 "     1  🟢 green    open — no priority; anything may cover it\n"
                 "     2  🟠 orange   open — always above the FILE MANAGER only\n"
                 "     3  🔴 red      open — above EVERYTHING (the aggressive one)\n"
                 "     4  ⚡ plain    closed\n"
                 "RIGHT-click ⚡ closes it from any state, and the state is\n"
                 "remembered.  The tick above decides whether a job that is WAITING\n"
                 "for you comes up in state 3 (over everything) or state 2 (over the\n"
                 "file manager only).  The queue never takes the keyboard in any of\n"
                 "the four — the arrow keys always belong to the file list.",
            foreground="#888888", justify="left",
        ).pack(anchor="w")

        ttk.Separator(tab_gen, orient="horizontal").grid(
            row=8, column=0, columnspan=3, sticky="ew", pady=(2, 10))

        # ── Backup-rename folder ──────────────────────────────────────
        ttk.Label(tab_gen, text="Backup rename — “Yes + move” folder",
                  font=("", 0, "bold")).grid(
            row=9, column=0, columnspan=3, sticky="w", pady=(0, 4))
        var_bdir = tk.StringVar(value=self.settings.get("backup_move_dir", ""))
        bdir_e = tk.Entry(tab_gen, textvariable=var_bdir, width=40,
                          insertofftime=0, insertontime=9999999)
        bdir_e.grid(row=10, column=0, columnspan=2, sticky="we", pady=3)

        def _browse_bdir():
            d = filedialog.askdirectory(parent=top, title="Backup move folder",
                                        initialdir=var_bdir.get() or str(APP_ROOT))
            if d:
                var_bdir.set(d)

        ttk.Button(tab_gen, text="…", width=3, command=_browse_bdir).grid(
            row=10, column=2, sticky="w", padx=(4, 0))

        ttk.Separator(tab_gen, orient="horizontal").grid(
            row=11, column=0, columnspan=3, sticky="ew", pady=(12, 10))

        # ── Display ───────────────────────────────────────────────────
        ttk.Label(tab_gen, text="Display",
                  font=("", 0, "bold")).grid(
            row=12, column=0, columnspan=3, sticky="w", pady=(0, 4))
        var_szgroup = tk.BooleanVar(
            value=self.settings.get("size_group_digits", True))
        # Both Size-column settings live in ONE frame on grid row 13, so a new
        # option can be added here later without renumbering every row below
        # it (grid orders by the row NUMBER, so there is no room between 13
        # and 14 to slide anything into).
        disp_frm = ttk.Frame(tab_gen)
        disp_frm.grid(row=13, column=0, columnspan=3, sticky="w")
        ttk.Checkbutton(
            disp_frm,
            text="Group the Size column with spaces  (9133144  →  9 133 144 KB)",
            variable=var_szgroup).pack(anchor="w")

        var_autosz = tk.BooleanVar(
            value=self.settings.get("auto_folder_sizes", False))
        ttk.Checkbutton(
            disp_frm,
            text="Folders show a SIZE too  —  measure every folder listing "
                 "automatically   (Alt+Shift+Enter does it once, on demand)",
            variable=var_autosz).pack(anchor="w")
        ttk.Label(
            disp_frm,
            text="      A folder has no size until its whole tree has been walked, so on a huge\n"
                 "      folder this costs real disk work every time you open its parent.  It runs\n"
                 "      in the background and the Size cells fill in as they land.").pack(anchor="w")

        var_showbuild = tk.BooleanVar(
            value=self.settings.get("show_build_in_title", False))
        ttk.Checkbutton(
            disp_frm,
            text="Show the version (build time) in the title bar, after "
                 "\u201cFile Manager\u201d",
            variable=var_showbuild).pack(anchor="w", pady=(6, 0))

        var_qinsb = tk.BooleanVar(
            value=self.settings.get("queue_in_statusbar", False))
        ttk.Checkbutton(
            disp_frm,
            text="Show the running job (file, %, speed) in the main status bar  "
                 "—  off = see it in the Task Queue (⚡)",
            variable=var_qinsb).pack(anchor="w", pady=(6, 0))

        ttk.Label(tab_gen, text="Open in the built-in viewer on a PLAIN Enter / double-click:").grid(
            row=14, column=0, columnspan=3, sticky="w", pady=(10, 2))
        var_readerx = tk.StringVar(
            value=self.settings.get("reader_extensions", "nfo, txt"))
        tk.Entry(tab_gen, textvariable=var_readerx,
                 insertofftime=0, insertontime=9999999).grid(
            row=15, column=0, columnspan=3, sticky="we", pady=(0, 2))
        ttk.Label(
            tab_gen,
            text="Comma-separated extensions (e.g. nfo, txt, srt).  A PLAIN\n"
                 "Enter / double-click on these opens the built-in viewer; every\n"
                 "other file opens with the Windows default.  SHIFT+open = built-in\n"
                 "viewer for ANY file; CTRL+open = the per-type opener (Custom\n"
                 "openers), or the built-in viewer if none.  F3 = viewer always;\n"
                 "F4 = your program always.",
            foreground="#888888",
        ).grid(row=16, column=0, columnspan=3, sticky="w", pady=(0, 4))

        var_redit = tk.BooleanVar(
            value=self.settings.get("reader_editable", True))
        ttk.Checkbutton(
            tab_gen,
            text="The built-in reader (F3) can EDIT and save  (Ctrl+S; it starts "
                 "read-only, press ✎ Edit to unlock)",
            variable=var_redit).grid(row=17, column=0, columnspan=3,
                                     sticky="w", pady=(6, 0))

        var_emptydir = tk.BooleanVar(
            value=self.settings.get("mark_empty_dirs", True))
        ttk.Checkbutton(
            tab_gen,
            text="Colour completely-empty folders differently  (no files and no "
                 "sub-folders → dim blue-grey)",
            variable=var_emptydir).grid(row=18, column=0, columnspan=3,
                                        sticky="w", pady=(6, 0))

        # Both activation switches share grid row 19, in one frame, so the
        # rows below never have to be renumbered to fit another one in.
        act_frm = ttk.Frame(tab_gen)
        act_frm.grid(row=19, column=0, columnspan=3, sticky="w", pady=(10, 4))

        var_actrun = tk.BooleanVar(
            value=self.settings.get("activate_runs_programs", True))
        ttk.Checkbutton(
            act_frm,
            text="Enter and double-click RUN a program  (.py, .bat, .exe, .ps1 …)",
            variable=var_actrun).pack(anchor="w")
        ttk.Label(
            act_frm,
            text="   On (default).  A .py is started with pythonw, so no console window\n"
                 "   appears behind your own programs.  F4 still opens it in the editor, and\n"
                 "   right-click ▸ ▶ Run in a console is there for a script whose output you\n"
                 "   need to read.  Off, a .py follows DefaultHub instead — which sends it to\n"
                 "   the text editor, because a .py IS a text file to every other program.",
            foreground="#888888").pack(anchor="w", pady=(0, 6))

        var_acthub = tk.BooleanVar(
            value=self.settings.get("activate_uses_hub", True))
        ttk.Checkbutton(
            act_frm,
            text="Enter and double-click follow DefaultHub  (what opens a .jpg, "
                 "a .pdf, …)",
            variable=var_acthub).pack(anchor="w")
        ttk.Label(
            act_frm,
            text="   On (default).  DefaultHub is the ONE place you write down which program\n"
                 "   owns a file type for every program in the tree\n"
                 "   (Helpfiles\\DefaultHub\\defaults.json).  Off, an image or a PDF is handed to\n"
                 "   Windows instead — and if no Windows default app is registered for it,\n"
                 "   nothing happens at all.  Shift+F4 and Ctrl+F4 still go straight to Windows.",
            foreground="#888888").pack(anchor="w", pady=(0, 6))

        # revBR — the SAME table, used for the picture instead of the launch.
        var_suiteic = tk.BooleanVar(value=self.settings.get("suite_icons", True))
        ttk.Checkbutton(
            act_frm,
            text="Show MY program's icon in front of a file DefaultHub gives it  "
                 "(a .pdf wears PDFull's icon, a .jpg SeeView's)",
            variable=var_suiteic).pack(anchor="w")
        ttk.Label(
            act_frm,
            text="   On (default).  Windows' own icon for a .pdf is whatever Adobe left in the\n"
                 "   registry, and for half these types it is a blank sheet — your programs are\n"
                 "   never registered with Windows at all.  The icon is read from Icons\\<program>.ico,\n"
                 "   nothing is started to ask for it, and a type DefaultHub leaves to the system\n"
                 "   keeps the Windows icon.  Needs the Icons switch on the toolbar to be on.",
            foreground="#888888").pack(anchor="w", pady=(0, 6))

        var_suitetx = tk.BooleanVar(
            value=self.settings.get("suite_icons_skip_text", False))
        ttk.Checkbutton(
            act_frm,
            text="   …except text & code files  (keep Windows' icons so .py, .json and .txt "
                 "stay apart)",
            variable=var_suitetx).pack(anchor="w")
        ttk.Label(
            act_frm,
            text="   Off (default).  DefaultHub has ONE \"text\" kind for .py .bat .cfg .csv .ini\n"
                 "   .json .log .md .nfo .ps1 .py .srt .txt .xml, so all of them wear the editor's\n"
                 "   icon and the column stops telling them apart at a glance.  Turn this on to\n"
                 "   leave that one kind to Windows and keep the program icons for all the rest.",
            foreground="#888888").pack(anchor="w", pady=(0, 6))

        var_actopen = tk.BooleanVar(
            value=self.settings.get("activate_uses_openers", False))
        ttk.Checkbutton(
            act_frm,
            text="Enter and double-click also use MY OWN openers  (per-type "
                 "opener, F4 program)",
            variable=var_actopen).pack(anchor="w")
        ttk.Label(
            act_frm,
            text="   Off (default): a plain Enter / double-click can never fire an external\n"
                 "   program you once set and forgot.  F4 and Ctrl+Enter still use your own.\n"
                 "   On: activation walks the full F4 ladder — per-type opener, then the F4\n"
                 "   program, then DefaultHub, then Windows.",
            foreground="#888888").pack(anchor="w")

        tab_gen.columnconfigure(1, weight=1)

        # ════════════════════════════════════════════════════════════
        # Tab — Transfers (copy/move throttle)
        # ════════════════════════════════════════════════════════════
        # This tab scrolls (General does too, since revAV).  Note the inner
        # frame keeps the name tab_thr: everything built below is unchanged,
        # it just lives on a canvas now.
        tab_thr_outer = ttk.Frame(nb)
        nb.add(tab_thr_outer, text="  Transfers  ")
        _thr_canvas = tk.Canvas(tab_thr_outer, highlightthickness=0,
                                bg=(ttk.Style().lookup("TFrame", "background")
                                    or "#f0f0f0"))
        _thr_sb = ttk.Scrollbar(tab_thr_outer, orient="vertical",
                                command=_thr_canvas.yview)
        _thr_canvas.configure(yscrollcommand=_thr_sb.set)
        # Scrollbar first, or the expanding canvas leaves it 1 px wide.
        _thr_sb.pack(side="right", fill="y")
        _thr_canvas.pack(side="left", fill="both", expand=True)
        tab_thr = ttk.Frame(_thr_canvas, padding=14)
        _thr_id = _thr_canvas.create_window((0, 0), window=tab_thr, anchor="nw")
        tab_thr.bind(
            "<Configure>",
            lambda e: _thr_canvas.configure(scrollregion=_thr_canvas.bbox("all")))
        _thr_canvas.bind(
            "<Configure>",
            lambda e: _thr_canvas.itemconfig(_thr_id, width=e.width))

        def _thr_wheel(e):
            _thr_canvas.yview_scroll(-1 * (e.delta // 120), "units")
            return "break"

        _thr_canvas.bind("<MouseWheel>", _thr_wheel)

        # ── The two settings that actually keep the machine usable ──────────
        var_io_bg = tk.BooleanVar(value=self.settings.get("io_background", True))
        ttk.Checkbutton(
            tab_thr,
            text="Let other programs overtake a copy on the disk  (background I/O priority)",
            variable=var_io_bg).grid(row=0, column=0, columnspan=3, sticky="w")
        ttk.Label(
            tab_thr,
            text="THIS is the one that stops a big copy locking the computer up.  The\n"
                 "copy's threads ask Windows for their disk I/O at the lowest priority,\n"
                 "so anything YOU do — opening a program, Ctrl+Alt+Del — jumps ahead of\n"
                 "it instead of queueing behind 4 MB blocks.  It costs nothing when you\n"
                 "are not using the machine: with nothing competing, nothing overtakes\n"
                 "and the copy runs at full speed.  Leave it on.",
            foreground="#888888").grid(row=1, column=0, columnspan=3,
                                       sticky="w", pady=(2, 8))

        ttk.Label(tab_thr, text="Flush the write cache every:").grid(
            row=2, column=0, sticky="w", pady=3)
        var_flush = tk.IntVar(value=self.settings.get("copy_flush_mb", 64))
        _mk_spinbox(tab_thr, from_=0, to=4096, textvariable=var_flush, width=7,
                    increment=16).grid(row=2, column=1, sticky="w", pady=3)
        ttk.Label(tab_thr, text="MB   (0 = never)", foreground="#888888").grid(
            row=2, column=2, sticky="w", padx=(6, 0))
        ttk.Label(
            tab_thr,
            text="Windows keeps written data in RAM and drains it to the disk in its\n"
                 "own time.  Write faster than the drive can drain — easy once an SSD\n"
                 "has used up its fast write cache — and that backlog grows into\n"
                 "gigabytes, at which point Windows stalls every program that writes\n"
                 "anything and starts throwing other programs out of RAM to make room.\n"
                 "Flushing every so often writes the same bytes; it just refuses to let\n"
                 "the backlog run away.  64 MB is a good number.",
            foreground="#888888").grid(row=3, column=0, columnspan=3,
                                       sticky="w", pady=(2, 12))

        ttk.Separator(tab_thr, orient="horizontal").grid(
            row=4, column=0, columnspan=3, sticky="ew", pady=(0, 10))

        var_thr_on = tk.BooleanVar(value=self.settings.get("throttle_enabled", False))
        ttk.Checkbutton(
            tab_thr,
            text="Also cap a long copy to a percentage of full speed",
            variable=var_thr_on).grid(row=5, column=0, columnspan=3, sticky="w")
        ttk.Label(
            tab_thr,
            text="OFF by default, and worth understanding before turning it on: making\n"
                 "a copy SLEEP does not hand a single disk request back to anybody.  It\n"
                 "only makes the copy last longer — so with this alone, the bigger the\n"
                 "file, the LONGER the machine stays clogged.  That is the opposite of\n"
                 "what it was meant to do, and it is why the box above exists.  Use this\n"
                 "only when you genuinely want a copy to crawl.  A running job can also\n"
                 "be Paused or Cancelled from the Task Queue window at any time.",
            foreground="#888888").grid(row=6, column=0, columnspan=3,
                                       sticky="w", pady=(2, 10))

        # The six cap numbers live in a frame of their own, so adding the two
        # settings above did not mean renumbering thirty grid rows.
        cap_box = ttk.Frame(tab_thr)
        cap_box.grid(row=7, column=0, columnspan=3, sticky="ew")

        def _spin(row, label, key, default, to, suffix):
            ttk.Label(cap_box, text=label).grid(row=row, column=0, sticky="w", pady=3)
            v = tk.IntVar(value=self.settings.get(key, default))
            _mk_spinbox(cap_box, from_=1, to=to, textvariable=v, width=7,
                        increment=1).grid(row=row, column=1, sticky="w", pady=3)
            ttk.Label(cap_box, text=suffix, foreground="#888888").grid(
                row=row, column=2, sticky="w", padx=(6, 0))
            return v

        var_soft_after = _spin(0, "After one file runs longer than:", "throttle_soft_after_s", 60, 3600, "seconds …")
        var_soft_pct   = _spin(1, "     cap its speed to:",           "throttle_soft_pct",     80, 100, "% of full")
        var_hard_after = _spin(2, "After one file runs longer than:", "throttle_hard_after_s", 300, 7200, "seconds …")
        var_hard_pct   = _spin(3, "     cap its speed to:",           "throttle_hard_pct",     60, 100, "% of full")
        var_batch_after= _spin(4, "After the whole job runs longer than:", "throttle_batch_after_s", 600, 14400, "seconds …")
        var_batch_pct  = _spin(5, "     cap the whole job to:",       "throttle_batch_pct",    70, 100, "% of full")

        # ── Three ready-made answers, so nothing on this tab is a question
        # you have to answer.  Each button fills in everything above.
        _preset_row = ttk.Frame(cap_box)
        _preset_row.grid(row=6, column=0, columnspan=3, sticky="w", pady=(10, 2))
        ttk.Label(_preset_row, text="Ready-made:").pack(side="left", padx=(0, 8))

        def _apply_preset(name):
            vals = THROTTLE_PRESETS[name]
            var_io_bg.set(vals["io_background"])
            var_flush.set(vals["copy_flush_mb"])
            var_thr_on.set(vals["throttle_enabled"])
            var_soft_after.set(vals["throttle_soft_after_s"])
            var_soft_pct.set(vals["throttle_soft_pct"])
            var_hard_after.set(vals["throttle_hard_after_s"])
            var_hard_pct.set(vals["throttle_hard_pct"])
            var_batch_after.set(vals["throttle_batch_after_s"])
            var_batch_pct.set(vals["throttle_batch_pct"])

        for _lbl, _key in (("⚡ Full speed", "full"),
                           ("🙂 Polite", "polite"),
                           ("🐢 Background", "background")):
            ttk.Button(_preset_row, text=_lbl, width=15,
                       command=lambda k=_key: _apply_preset(k)).pack(side="left",
                                                                     padx=3)
        ttk.Label(
            cap_box,
            text="Full speed = the copy is an ordinary program competing with\n"
                 "     yours for the disk, and its writes pile up in the Windows\n"
                 "     cache.  Fastest on paper; it is also what made a 10 GB\n"
                 "     copy take half a minute to open Ctrl+Alt+Del.\n"
                 "Polite = background I/O priority, cache flushed every 64 MB,\n"
                 "     no speed cap.  The default.  Full speed when you are not\n"
                 "     using the machine, out of your way the moment you are.\n"
                 "Background = the same, plus an outright cap once a file drags\n"
                 "     on.  Only worth it when you want a copy to crawl.\n"
                 "There is a ⚡ Full speed tickbox on the Task Queue toolbar too,\n"
                 "and it reaches the file that is ALREADY being copied.",
            foreground="#888888").grid(row=7, column=0, columnspan=3,
                                       sticky="w", pady=(2, 4))

        ttk.Separator(tab_thr, orient="horizontal").grid(
            row=10, column=0, columnspan=3, sticky="ew", pady=(14, 10))

        # ── Fast lane ────────────────────────────────────────────────
        ttk.Label(tab_thr, text="Fast lane — small files never wait",
                  font=("", 0, "bold")).grid(row=11, column=0, columnspan=3,
                                             sticky="w", pady=(0, 4))
        var_fl_on = tk.BooleanVar(
            value=bool(self.settings.get("fastlane_enabled", True)))
        ttk.Checkbutton(
            tab_thr,
            text="Let small jobs overtake a big transfer",
            variable=var_fl_on).grid(row=12, column=0, columnspan=3, sticky="w")
        ttk.Label(
            tab_thr,
            text="A copy/move under the size below runs in its OWN worker, in\n"
                 "parallel with whatever big job is already going — so a 200 KB\n"
                 "file is done instantly instead of sitting behind 9 GB.\n"
                 "A same-drive MOVE always takes this lane whatever its size: it\n"
                 "is only a rename, so no bytes travel and it finishes at once.",
            foreground="#888888").grid(row=13, column=0, columnspan=3,
                                       sticky="w", pady=(2, 8))

        ttk.Label(tab_thr, text="Counts as “small” up to:").grid(
            row=14, column=0, sticky="w", pady=3)
        var_fl_mb = tk.IntVar(value=int(self.settings.get("fastlane_max_mb", 50)))
        _mk_spinbox(tab_thr, from_=1, to=100000, textvariable=var_fl_mb,
                    width=7, increment=10).grid(row=14, column=1, sticky="w", pady=3)
        ttk.Label(tab_thr, text="MB (total job size)",
                  foreground="#888888").grid(row=14, column=2, sticky="w",
                                             padx=(6, 0))

        var_up_wait = tk.BooleanVar(
            value=bool(self.settings.get("unpack_wait_enabled", True)))
        var_up_every = tk.IntVar(
            value=int(self.settings.get("unpack_wait_seconds", 20)))
        var_up_give  = tk.IntVar(
            value=int(self.settings.get("unpack_wait_max_minutes", 60)))
        var_up_sub   = tk.BooleanVar(
            value=bool(self.settings.get("unpack_subfolder", False)))
        var_up_del   = tk.BooleanVar(
            value=bool(self.settings.get("unpack_delete_after", False)))
        var_up_mark  = tk.BooleanVar(
            value=bool(self.settings.get("unpack_mark_source_folder", False)))
        var_up_show  = tk.BooleanVar(
            value=bool(self.settings.get("unpack_show_queue", True)))
        var_up_other = tk.BooleanVar(
            value=bool(self.settings.get("unpack_dest_other", True)))

        var_fl_pause = tk.BooleanVar(
            value=bool(self.settings.get("fastlane_pause_big", True)))
        ttk.Checkbutton(
            tab_thr,
            text="Pause the big transfer while a small one slips past",
            variable=var_fl_pause).grid(row=15, column=0, columnspan=3,
                                        sticky="w", pady=(6, 0))
        ttk.Label(
            tab_thr,
            text="On (recommended): the small file gets the whole disk and is over\n"
                 "in a blink, then the big one carries on exactly where it stopped.\n"
                 "Off: both run at once and share the disk.",
            foreground="#888888").grid(row=16, column=0, columnspan=3,
                                       sticky="w", pady=(2, 0))

        # ── Unpacking (DEL 20b) ──────────────────────────────────────
        ttk.Separator(tab_thr, orient="horizontal").grid(
            row=17, column=0, columnspan=3, sticky="ew", pady=(14, 10))
        ttk.Label(tab_thr, text="Unpacking",
                  font=("", 0, "bold")).grid(row=18, column=0, columnspan=3,
                                             sticky="w", pady=(0, 4))
        # One container for row 19, so adding the destination tick below does
        # not renumber every gridded row after it.
        _updest = ttk.Frame(tab_thr)
        _updest.grid(row=19, column=0, columnspan=3, sticky="ew", pady=(0, 8))
        ttk.Label(
            _updest,
            text="Archives go through the Task Queue — one at a time, in the\n"
                 "background, and a split set (movie.rar + .r00 … , part01.rar … ,\n"
                 ".7z.001 … ) counts as ONE job however many pieces you pick.\n"
                 "A failed or cancelled extraction takes back exactly what it\n"
                 "wrote, so a folder is never left half full.",
            foreground="#888888").pack(anchor="w", pady=(0, 8))

        ttk.Checkbutton(
            _updest,
            text="Unpack into the OTHER panel's folder",
            variable=var_up_other).pack(anchor="w")
        ttk.Label(
            _updest,
            text="On (default): everything you unpack lands where the other panel is\n"
                 "pointing — including archives found by picking whole FOLDERS, which\n"
                 "used to always extract where they lie.  Unpacking onto a second\n"
                 "drive is far faster than onto the one being read from, and if you do\n"
                 "want them where they lie, point the other panel at that folder.\n"
                 "Off: an archive picked by name still goes to the other panel, but\n"
                 "archives found inside folders extract beside themselves again.\n"
                 "Either way, if the other panel is on FTP or inside an archive, this\n"
                 "side's folder is used instead — and the confirmation says so.",
            foreground="#888888").pack(anchor="w", padx=(22, 0))

        ttk.Checkbutton(
            tab_thr,
            text="Wait for a set whose parts are still being downloaded",
            variable=var_up_wait).grid(row=20, column=0, columnspan=3, sticky="w")
        wait_row = ttk.Frame(tab_thr)
        wait_row.grid(row=21, column=0, columnspan=3, sticky="w", pady=(2, 0))
        ttk.Label(wait_row, text="        look again every").pack(side="left")
        _mk_spinbox(wait_row, from_=5, to=600, textvariable=var_up_every,
                    width=6, increment=5).pack(side="left", padx=4)
        ttk.Label(wait_row, text="seconds, give up after").pack(side="left")
        _mk_spinbox(wait_row, from_=1, to=1440, textvariable=var_up_give,
                    width=6, increment=5).pack(side="left", padx=4)
        ttk.Label(wait_row, text="minutes").pack(side="left")
        ttk.Label(
            tab_thr,
            text="An FTP client writes  movie.r37.part  while it is fetching that\n"
                 "part; an .sfv in the folder, when there is one, says outright\n"
                 "which files the release still owes.  Either way the job simply\n"
                 "waits its turn instead of failing.",
            foreground="#888888").grid(row=22, column=0, columnspan=3,
                                       sticky="w", pady=(2, 8))

        ttk.Checkbutton(
            tab_thr,
            text="Put the files in a folder named after the archive",
            variable=var_up_sub).grid(row=23, column=0, columnspan=3, sticky="w")
        ttk.Label(
            tab_thr,
            text="Unless the archive already holds one folder of its own — no\n"
                 "Film/Film/ either way.",
            foreground="#888888").grid(row=24, column=0, columnspan=3,
                                       sticky="w", pady=(0, 6))
        ttk.Checkbutton(
            tab_thr,
            text="Move the archive to the trash afterwards (the whole split set)",
            variable=var_up_del).grid(row=25, column=0, columnspan=3, sticky="w")
        ttk.Checkbutton(
            tab_thr,
            text="Rename the folder it came from to  UNPACKED-…",
            variable=var_up_mark).grid(row=26, column=0, columnspan=3, sticky="w")
        ttk.Label(
            tab_thr,
            text="Both are off unless you ask for them — each one moves or\n"
                 "renames something.  Nothing is deleted outright: the archive\n"
                 "goes to the same trash as the Del key, and comes back the\n"
                 "same way.",
            foreground="#888888").grid(row=27, column=0, columnspan=3,
                                       sticky="w", pady=(2, 0))
        ttk.Checkbutton(
            tab_thr,
            text="Show the Task Queue when an unpack is queued",
            variable=var_up_show).grid(row=28, column=0, columnspan=3,
                                       sticky="w", pady=(8, 0))
        ttk.Label(
            tab_thr,
            text="Nothing visibly happens in the panels while an archive is\n"
                 "being extracted, so without this there is only a line in the\n"
                 "status bar to say the job ever took.  The window opens in the\n"
                 "BACKGROUND and never takes the keyboard.",
            foreground="#888888").grid(row=29, column=0, columnspan=3,
                                       sticky="w", pady=(2, 0))

        # ════════════════════════════════════════════════════════════
        # Tab 1 – Column widths
        # ════════════════════════════════════════════════════════════
        tab_cols = ttk.Frame(nb, padding=14)
        nb.add(tab_cols, text="  Customization  ")

        ttk.Label(tab_cols, text="Default column widths (pixels)",
                  font=("", 0, "bold")).grid(
            row=0, column=0, columnspan=2, sticky="w", pady=(0, 8))

        cw = self.settings.get("column_widths", {})
        _col_defaults = [
            ("Name",       "name",       320),
            ("Type",       "type",       100),
            (f"{FLAG_CHAR} flag", "flag",  26),
            ("Size",       "size",        90),
            ("Modified",   "modified",   140),
            ("Attributes", "attributes",  70),
        ]
        col_vars = {}
        for i, (label, key, default) in enumerate(_col_defaults, start=1):
            ttk.Label(tab_cols, text=f"{label}:").grid(
                row=i, column=0, sticky="w", padx=(0, 10), pady=4)
            var = tk.IntVar(value=cw.get(key, default))
            # The ★ column is a single character wide on purpose, so it is
            # the one column allowed below the 40 px floor.
            sb = _mk_spinbox(tab_cols, from_=(16 if key == "flag" else 40),
                             to=800, textvariable=var,
                             width=7, increment=10)
            sb.grid(row=i, column=1, sticky="w", pady=4)
            col_vars[key] = var

        ttk.Separator(tab_cols, orient="horizontal").grid(
            row=len(_col_defaults) + 1, column=0, columnspan=2,
            sticky="ew", pady=(10, 8))

        ttk.Label(
            tab_cols,
            text="Changes take effect on next Manager start.\n"
                 "Resizing panels during a session is always temporary.",
            foreground="#888888",
        ).grid(row=len(_col_defaults) + 2, column=0, columnspan=2,
               sticky="w", pady=(0, 10))

        # ── File colours by extension ────────────────────────────────
        collect_ext_groups = self._build_ext_colour_section(
            tab_cols, len(_col_defaults) + 3)

        # ════════════════════════════════════════════════════════════
        # Tab 3 – My programs   (revAR — build watch)
        # ════════════════════════════════════════════════════════════
        tab_mine = ttk.Frame(nb, padding=12)
        nb.add(tab_mine, text="  My programs  ")

        ttk.Label(tab_mine, text="Is the program I run still the program I wrote?",
                  font=("", 0, "bold")).pack(anchor="w")
        ttk.Label(
            tab_mine,
            text=(
                "This compares each source .py against the program built from it, and says\n"
                "which ones have moved on.  It never builds anything itself — building is\n"
                "minutes of work and hundreds of megabytes, and a build that dies halfway\n"
                "leaves a program that will not start.  Tick what you want and it writes the\n"
                "build list out for Exe-bygg, whose job that is.\n"
                "\n"
                "It also flags anything still built ONE-FILE.  A one-file .exe unpacks its\n"
                "whole bundle into TEMP on every single launch — measured here: 1075 ms for a\n"
                "14 MB bundle against 104 ms for the same program built one-folder, and the\n"
                "gap grows with size (PDFull is 171 MB, WhyBrowse 197 MB).  That cost is paid\n"
                "every time, from anywhere — Tower, the desktop, a double-click here."),
            justify="left").pack(anchor="w", pady=(4, 8))

        _wf = ttk.Frame(tab_mine)
        _wf.pack(fill="x")
        ttk.Label(_wf, text="Sources (.py):").grid(row=0, column=0, sticky="w")
        var_wsrc = tk.StringVar(value="  ".join(
            self.settings.get("watch_src_dirs") or []))
        tk.Entry(_wf, textvariable=var_wsrc, width=64, insertofftime=0,
                 insertontime=9999999).grid(row=0, column=1, sticky="we", padx=4)
        ttk.Label(_wf, text="Built programs:").grid(row=1, column=0, sticky="w",
                                                    pady=(4, 0))
        var_wbld = tk.StringVar(value="  ".join(
            self.settings.get("watch_build_dirs") or []))
        tk.Entry(_wf, textvariable=var_wbld, width=64, insertofftime=0,
                 insertontime=9999999).grid(row=1, column=1, sticky="we", padx=4,
                                            pady=(4, 0))
        ttk.Label(_wf, text="two spaces between folders", foreground="#888888",
                  font=("", 8)).grid(row=2, column=1, sticky="w")
        _wf.columnconfigure(1, weight=1)

        # The tree and its scrollbar get their OWN container.  Packed straight
        # into the tab, a side="right" scrollbar claims the right-hand edge of
        # everything packed AFTER it too, and the buttons below end up squeezed
        # in beside a scrollbar running the full height of the tab.
        w_box = ttk.Frame(tab_mine)
        w_box.pack(fill="both", expand=True, pady=(8, 0))
        w_cols = ("tick", "name", "state", "src", "build")
        w_tree = ttk.Treeview(w_box, columns=w_cols, show="headings",
                              height=11, selectmode="browse")
        for _c, _t, _w, _a in (("tick", "Watch", 46, "center"),
                               ("name", "Program", 140, "w"),
                               ("state", "Status", 110, "w"),
                               ("src", "Source", 165, "w"),
                               ("build", "Built program", 215, "w")):
            w_tree.heading(_c, text=_t)
            w_tree.column(_c, width=_w, anchor=_a)
        w_tree.tag_configure("stale", foreground="#c00028")
        w_tree.tag_configure("slow",  foreground="#b06000")
        w_tree.tag_configure("fine",  foreground="#2a7a2a")
        _wsb = ttk.Scrollbar(w_box, orient="vertical", command=w_tree.yview)
        w_tree.configure(yscrollcommand=_wsb.set)
        # Scrollbar packed BEFORE the expanding tree, or it renders 1 px wide.
        _wsb.pack(side="right", fill="y")
        w_tree.pack(side="left", fill="both", expand=True)

        w_rows = []
        w_chosen = set(self.settings.get("watch_chosen") or [])
        var_wall = tk.BooleanVar(value=False)

        def _w_dirs(var):
            return [d.strip() for d in var.get().split("  ") if d.strip()]

        def _w_stamp(m, s, unit="K"):
            if not m:
                return "—"
            when = datetime.fromtimestamp(m).strftime("%Y-%m-%d")
            if unit == "K":
                return f"{when}   {s/1024:,.0f} KB"
            return f"{when}   {s/1048576:,.0f} MB"

        def _w_draw():
            w_tree.delete(*w_tree.get_children())
            for i, r in enumerate(w_rows):
                if not var_wall.get() and r["name"] not in w_chosen:
                    continue
                tag = ("stale" if r["state"] in ("newer source", "never built")
                       else "slow" if r["state"] == "one-file" else "fine")
                build = _w_stamp(r["exe_mtime"], r["exe_size"], "M")
                if r["kind"]:
                    build += f"   ({r['kind']})"
                w_tree.insert("", "end", iid=str(i), tags=(tag,), values=(
                    "✓" if r["name"] in w_chosen else "",
                    r["name"], r["state"],
                    _w_stamp(r["src_mtime"], r["src_size"]), build))
            n_shown = len(w_tree.get_children())
            lbl_wcount.configure(
                text=f"{n_shown} shown · {len(w_chosen)} watched · "
                     f"{len(w_rows)} found in total")

        def _w_scan():
            lbl_wcount.configure(text="looking…")
            top.update_idletasks()
            try:
                w_rows[:] = build_watch_scan(_w_dirs(var_wsrc), _w_dirs(var_wbld))
            except Exception as exc:
                messagebox.showerror("My programs", str(exc), parent=top)
                return
            _w_draw()

        def _w_toggle(_event=None):
            sel = w_tree.selection()
            if not sel:
                return "break"
            r = w_rows[int(sel[0])]
            if r["name"] in w_chosen:
                w_chosen.discard(r["name"])
            else:
                w_chosen.add(r["name"])
            _w_draw()
            if w_tree.exists(sel[0]):
                w_tree.selection_set(sel[0])
                w_tree.focus(sel[0])
            return "break"

        def _w_pick_built():
            """Tick everything that HAS a build — those are your programs."""
            for r in w_rows:
                if r["exe"]:
                    w_chosen.add(r["name"])
            _w_draw()

        def _w_send():
            """Hand the ticked, out-of-date programs to ExeForge.

            This program still builds nothing: it writes the order and lets
            ExeForge do the minutes of work, the hundreds of megabytes and the
            backup of the previous version."""
            want = [r for r in w_rows if r["name"] in w_chosen
                    and r["src"] and r["state"] != "up to date"]
            if not want:
                messagebox.showinfo(
                    "Send to ExeForge",
                    "Nothing ticked needs building - every watched program is "
                    "up to date and already one-folder.", parent=top)
                return
            names = ", ".join(r["name"] for r in want[:8])
            if len(want) > 8:
                names += f" and {len(want) - 8} more"
            ok, msg = send_to_exeforge(
                want, note=f"{len(want)} with a newer source or a one-file build")
            (messagebox.showinfo if ok else messagebox.showerror)(
                "Send to ExeForge", f"{names}\n\n{msg}", parent=top)

        def _w_write():
            """Write the build list for the ticked programs that need one."""
            want = [r for r in w_rows if r["name"] in w_chosen
                    and r["src"] and r["state"] != "up to date"]
            if not want:
                messagebox.showinfo(
                    "Build list",
                    "Nothing ticked needs building — every watched program is "
                    "up to date and already one-folder.", parent=top)
                return
            outs = _w_dirs(var_wbld)
            out_dir = outs[0] if outs else str(APP_ROOT)
            text = build_watch_commands(want, out_dir)
            path = filedialog.asksaveasfilename(
                parent=top, title="Write the build list",
                defaultextension=".txt",
                initialfile="build_one-folder_"
                            + datetime.now().strftime("%Y-%m-%d") + ".txt",
                filetypes=[("Text", "*.txt"), ("All files", "*.*")])
            if not path:
                return
            try:
                with open(path, "w", encoding="utf-8") as fh:
                    fh.write(text)
            except Exception as exc:
                messagebox.showerror("Build list", str(exc), parent=top)
                return
            try:
                self.clipboard_clear()
                self.clipboard_append(text)
            except Exception:
                pass
            messagebox.showinfo(
                "Build list",
                f"{len(want)} program(s) written to:\n{path}\n\n"
                "It is on the clipboard as well.\n\n"
                "Each line gives the program its OWN payload folder\n"
                "(--contents-directory), so several one-folder programs can\n"
                "live side by side without overwriting each other's DLLs.",
                parent=top)

        w_tree.bind("<Double-1>", _w_toggle)
        w_tree.bind("<space>", _w_toggle)
        w_tree.bind("<Return>", _w_toggle)

        w_btns = ttk.Frame(tab_mine)
        w_btns.pack(fill="x", pady=(8, 0))
        ttk.Button(w_btns, text="Look now", command=_w_scan).pack(side="left")
        ttk.Button(w_btns, text="Watch ⇄  (Space)",
                   command=_w_toggle).pack(side="left", padx=(8, 0))
        ttk.Button(w_btns, text="Watch everything already built",
                   command=_w_pick_built).pack(side="left", padx=4)
        ttk.Button(w_btns, text="Send to ExeForge →",
                   command=_w_send).pack(side="left", padx=(12, 0))
        ttk.Button(w_btns, text="Write the build list…",
                   command=_w_write).pack(side="left", padx=4)
        ttk.Checkbutton(w_btns, text="show everything found",
                        variable=var_wall,
                        command=_w_draw).pack(side="left", padx=(12, 0))

        lbl_wcount = ttk.Label(tab_mine, text="", foreground="#888888",
                               font=("", 8))
        lbl_wcount.pack(anchor="w", pady=(4, 0))

        var_wstart = tk.BooleanVar(
            value=bool(self.settings.get("watch_at_startup", True)))
        ttk.Checkbutton(
            tab_mine, text="Check at startup, in the background",
            variable=var_wstart).pack(anchor="w", pady=(6, 0))
        ttk.Label(
            tab_mine,
            text="On (default): a few seconds after the window opens, the watched programs\n"
                 "are compared on a worker thread and ONE status line appears if any source\n"
                 "has moved on or is still built one-file.  Nothing pops up, nothing blinks,\n"
                 "and nothing at all is said when there is nothing to say.",
            foreground="#888888", justify="left").pack(anchor="w", padx=(22, 0))

        _w_scan()

        # ════════════════════════════════════════════════════════════
        # Tab 2 – Custom openers
        # ════════════════════════════════════════════════════════════
        tab_open = ttk.Frame(nb, padding=14)
        nb.add(tab_open, text="  Custom openers  ")

        # ── F4: THE external program ─────────────────────────────────
        ttk.Label(
            tab_open,
            text="F4 — open in an external program\n"
                 "Windows only asks “open with…” once and then remembers, which is\n"
                 "how one stray choice becomes “F4 always opens the wrong program”.\n"
                 "Set your own program here and F4 uses THAT instead. Leave it empty\n"
                 "to keep using whatever Windows associates with the file.",
            justify="left",
        ).pack(anchor="w", pady=(0, 6))

        f4_frame = ttk.Frame(tab_open)
        f4_frame.pack(fill="x", pady=(0, 4))

        ttk.Label(f4_frame, text="Program:").grid(row=0, column=0, sticky="w")
        var_f4prog = tk.StringVar(value=self.settings.get("f4_program", ""))
        tk.Entry(f4_frame, textvariable=var_f4prog, width=52,
                 insertofftime=0, insertontime=9999999
                 ).grid(row=0, column=1, sticky="we", padx=4)

        def _browse_f4():
            path = filedialog.askopenfilename(
                parent=top, title="Select the program F4 should use",
                filetypes=[("Executables", "*.exe"), ("All files", "*.*")])
            if path:
                var_f4prog.set(path)

        ttk.Button(f4_frame, text="…", width=3,
                   command=_browse_f4).grid(row=0, column=2)
        ttk.Button(f4_frame, text="Clear", width=6,
                   command=lambda: var_f4prog.set("")).grid(row=0, column=3, padx=(4, 0))

        ttk.Label(f4_frame, text="Arguments:").grid(row=1, column=0, sticky="w",
                                                    pady=(4, 0))
        var_f4args = tk.StringVar(value=self.settings.get("f4_args", ""))
        tk.Entry(f4_frame, textvariable=var_f4args, width=52,
                 insertofftime=0, insertontime=9999999
                 ).grid(row=1, column=1, sticky="we", padx=4, pady=(4, 0))
        ttk.Label(f4_frame, text='%1 = the file  (empty is fine)',
                  foreground="#888888", font=("", 8)
                  ).grid(row=1, column=2, columnspan=2, sticky="w", pady=(4, 0))

        ttk.Label(f4_frame, text="Only for:").grid(row=2, column=0, sticky="w",
                                                   pady=(4, 0))
        var_f4ext = tk.StringVar(value=self.settings.get("f4_extensions", ""))
        tk.Entry(f4_frame, textvariable=var_f4ext, width=52,
                 insertofftime=0, insertontime=9999999
                 ).grid(row=2, column=1, sticky="we", padx=4, pady=(4, 0))
        ttk.Label(f4_frame, text="e.g.  txt, nfo, log   (empty = every file)",
                  foreground="#888888", font=("", 8)
                  ).grid(row=2, column=2, columnspan=2, sticky="w", pady=(4, 0))
        f4_frame.columnconfigure(1, weight=1)

        ttk.Label(
            tab_open,
            text="CTRL+F4 opens Windows' own “Open with…” box — use it to undo a\n"
                 "wrong association you once picked by accident.",
            foreground="#888888", font=("", 8), justify="left",
        ).pack(anchor="w", pady=(4, 6))

        # ── F3 = F4 ──────────────────────────────────────────────────
        var_f3ext = tk.BooleanVar(
            value=bool(self.settings.get("f3_use_external", True)))
        ttk.Checkbutton(
            tab_open,
            text="F3 uses the same external program as F4 "
                 "(skip the built-in reader)",
            variable=var_f3ext,
        ).pack(anchor="w", pady=(2, 0))
        ttk.Label(
            tab_open,
            text="With this on, ONE program serves both keys: F3 hands the file to the\n"
                 "per-extension opener, or to the F4 program above.  It only applies when\n"
                 "such a program actually covers that file type — otherwise the built-in\n"
                 "reader still opens it, so F3 never becomes a dead key.  SHIFT+ENTER\n"
                 "always forces the built-in viewer, whatever this is set to.",
            foreground="#888888", font=("", 8), justify="left",
        ).pack(anchor="w", pady=(0, 10))

        ttk.Separator(tab_open, orient="horizontal").pack(fill="x", pady=(0, 10))

        # ── SHIFT+F4: a SECOND external program ──────────────────────
        ttk.Label(
            tab_open,
            text="SHIFT+F4 — open in a SECOND program (e.g. a different editor)\n"
                 "Same idea as the F4 program above, on its own key.  Leave the\n"
                 "program empty and SHIFT+F4 falls back to the Windows association.",
            justify="left",
        ).pack(anchor="w", pady=(0, 6))

        f4b_frame = ttk.Frame(tab_open)
        f4b_frame.pack(fill="x", pady=(0, 4))

        ttk.Label(f4b_frame, text="Program:").grid(row=0, column=0, sticky="w")
        var_f4bprog = tk.StringVar(value=self.settings.get("f4b_program", ""))
        tk.Entry(f4b_frame, textvariable=var_f4bprog, width=52,
                 insertofftime=0, insertontime=9999999
                 ).grid(row=0, column=1, sticky="we", padx=4)

        def _browse_f4b():
            path = filedialog.askopenfilename(
                parent=top, title="Select the program Shift+F4 should use",
                filetypes=[("Executables", "*.exe"), ("All files", "*.*")])
            if path:
                var_f4bprog.set(path)

        ttk.Button(f4b_frame, text="…", width=3,
                   command=_browse_f4b).grid(row=0, column=2)
        ttk.Button(f4b_frame, text="Clear", width=6,
                   command=lambda: var_f4bprog.set("")).grid(row=0, column=3, padx=(4, 0))

        ttk.Label(f4b_frame, text="Arguments:").grid(row=1, column=0, sticky="w",
                                                     pady=(4, 0))
        var_f4bargs = tk.StringVar(value=self.settings.get("f4b_args", ""))
        tk.Entry(f4b_frame, textvariable=var_f4bargs, width=52,
                 insertofftime=0, insertontime=9999999
                 ).grid(row=1, column=1, sticky="we", padx=4, pady=(4, 0))
        ttk.Label(f4b_frame, text='%1 = the file  (empty is fine)',
                  foreground="#888888", font=("", 8)
                  ).grid(row=1, column=2, columnspan=2, sticky="w", pady=(4, 0))

        ttk.Label(f4b_frame, text="Only for:").grid(row=2, column=0, sticky="w",
                                                    pady=(4, 0))
        var_f4bext = tk.StringVar(value=self.settings.get("f4b_extensions", ""))
        tk.Entry(f4b_frame, textvariable=var_f4bext, width=52,
                 insertofftime=0, insertontime=9999999
                 ).grid(row=2, column=1, sticky="we", padx=4, pady=(4, 0))
        ttk.Label(f4b_frame, text="e.g.  txt, nfo, log   (empty = every file)",
                  foreground="#888888", font=("", 8)
                  ).grid(row=2, column=2, columnspan=2, sticky="w", pady=(4, 0))
        f4b_frame.columnconfigure(1, weight=1)

        ttk.Separator(tab_open, orient="horizontal").pack(fill="x", pady=(10, 10))

        ttk.Label(
            tab_open,
            text="Per-type openers — the program to use for one file type.\n"
                 "They are used by the F4 key and by CTRL+Enter / CTRL+double-click\n"
                 "on that type.  A PLAIN Enter / double-click uses the Windows\n"
                 "default; SHIFT+Enter / SHIFT+double-click uses the built-in viewer.",
            justify="left",
        ).pack(anchor="w", pady=(0, 8))

        # ── opener list ──────────────────────────────────────────────
        list_frame = ttk.Frame(tab_open)
        list_frame.pack(fill="both", expand=True)

        cols_op = ("ext", "program")
        opener_tree = ttk.Treeview(list_frame, columns=cols_op,
                                    show="headings", selectmode="browse",
                                    height=8)
        opener_tree.heading("ext",     text="Extension")
        opener_tree.heading("program", text="Program path")
        opener_tree.column("ext",     width=90,  stretch=False, anchor="w")
        opener_tree.column("program", width=380, stretch=True,  anchor="w")
        opener_tree.pack(side="left", fill="both", expand=True)
        ttk.Scrollbar(list_frame, orient="vertical",
                      command=opener_tree.yview).pack(side="right", fill="y")
        opener_tree.configure(
            yscrollcommand=list_frame.winfo_children()[-1].set)

        # Populate from settings
        _custom_openers: dict = dict(self.settings.get("custom_openers", {}))

        def _refresh_opener_tree():
            opener_tree.delete(*opener_tree.get_children())
            for ext_key in sorted(_custom_openers):
                opener_tree.insert("", "end",
                                   values=(ext_key, _custom_openers[ext_key]))

        _refresh_opener_tree()

        # ── entry row ────────────────────────────────────────────────
        entry_frame = ttk.Frame(tab_open)
        entry_frame.pack(fill="x", pady=(8, 2))

        ttk.Label(entry_frame, text="Ext:").pack(side="left")
        var_ext = tk.StringVar()
        ext_e   = tk.Entry(entry_frame, textvariable=var_ext, width=8,
                           insertofftime=0, insertontime=9999999)
        ext_e.pack(side="left", padx=(2, 8))

        ttk.Label(entry_frame, text="Program:").pack(side="left")
        var_prog = tk.StringVar()
        prog_e   = tk.Entry(entry_frame, textvariable=var_prog, width=36,
                            insertofftime=0, insertontime=9999999)
        prog_e.pack(side="left", padx=(2, 4), fill="x", expand=True)

        def _browse_program():
            path = filedialog.askopenfilename(
                parent=top, title="Select program",
                filetypes=[("Executables", "*.exe"), ("All files", "*.*")])
            if path:
                var_prog.set(path)

        ttk.Button(entry_frame, text="…", width=3,
                   command=_browse_program).pack(side="left")

        # ── action buttons ───────────────────────────────────────────
        op_btn_row = ttk.Frame(tab_open)
        op_btn_row.pack(fill="x", pady=(4, 0))

        def _add_opener():
            ext_raw  = var_ext.get().strip().lower()
            prog_raw = var_prog.get().strip()
            if not ext_raw or not prog_raw:
                return
            ext_key = ext_raw if ext_raw.startswith(".") else f".{ext_raw}"
            _custom_openers[ext_key] = prog_raw
            _refresh_opener_tree()
            var_ext.set("")
            var_prog.set("")

        def _del_opener():
            sel = opener_tree.selection()
            if not sel:
                return
            ext_key = opener_tree.item(sel[0], "values")[0]
            _custom_openers.pop(ext_key, None)
            _refresh_opener_tree()

        def _edit_opener():
            sel = opener_tree.selection()
            if not sel:
                return
            ext_key, prog = opener_tree.item(sel[0], "values")
            var_ext.set(ext_key)
            var_prog.set(prog)

        ttk.Button(op_btn_row, text="Add / update", command=_add_opener,
                   width=16).pack(side="left", padx=(0, 4))
        ttk.Button(op_btn_row, text="Edit selected", command=_edit_opener,
                   width=16).pack(side="left", padx=(0, 4))
        ttk.Button(op_btn_row, text="Delete selected", command=_del_opener,
                   width=16).pack(side="left")

        opener_tree.bind("<Double-1>", lambda e: _edit_opener())

        ttk.Label(
            tab_open,
            text="Tip: leave Program empty and click Delete to remove an entry.",
            foreground="#888888", font=("", 8),
        ).pack(anchor="w", pady=(6, 0))

        # ════════════════════════════════════════════════════════════
        # Bottom buttons (shared)
        # ════════════════════════════════════════════════════════════
        # The wheel has to work over the WIDGETS too, not just the canvas
        # background — bound one by one rather than with bind_all, which would
        # take the wheel away from everything else in the program.
        # revAV — General scrolls too now, so the helper takes the handler as an
        # argument instead of hard-wiring the Transfers one.  A Spinbox and a
        # Combobox scroll their own VALUE on the wheel, which is a nasty way to
        # change a setting by accident, so those keep their own behaviour and
        # are skipped here.
        _NO_WHEEL = ("TSpinbox", "Spinbox", "TCombobox")

        def _bind_wheel(w, handler):
            if w.winfo_class() not in _NO_WHEEL:
                try:
                    w.bind("<MouseWheel>", handler)
                except Exception:
                    pass
            for c in w.winfo_children():
                _bind_wheel(c, handler)

        def _bind_all_wheels():
            _bind_wheel(tab_thr, _thr_wheel)
            _bind_wheel(tab_gen, _gen_wheel)

        top.after_idle(_bind_all_wheels)

        btn_row = ttk.Frame(top, padding=(14, 4, 14, 12))
        # revAU — Save and Cancel used to be INVISIBLE.
        # pack hands out space in the order the slaves were packed, not in
        # screen order.  The notebook is packed first with expand=True, so on a
        # window shorter than the tallest tab wants (the height cap below makes
        # it exactly that: 1953px wanted, ~940px of desktop) the notebook took
        # every pixel and this row was left one pixel tall and unmapped.  The
        # last thing on screen was "Add / update" inside the Custom openers tab,
        # which is not a save button and never was.
        # Packing the row FIRST — at the bottom — reserves its height before the
        # notebook gets a look in; re-packing the notebook after it puts the
        # notebook last in line, so it takes what is left instead of everything.
        btn_row.pack(side="bottom", fill="x")
        nb.pack_configure(after=btn_row)

        def _save():
            widths = {key: var.get() for key, var in col_vars.items()}
            self.settings["column_widths"] = widths
            self.settings["custom_openers"] = dict(_custom_openers)
            self.settings["f4_program"]    = var_f4prog.get().strip()
            self.settings["f4_args"]       = var_f4args.get().strip()
            self.settings["f4_extensions"] = var_f4ext.get().strip()
            self.settings["f4b_program"]    = var_f4bprog.get().strip()
            self.settings["f4b_args"]       = var_f4bargs.get().strip()
            self.settings["f4b_extensions"] = var_f4bext.get().strip()
            self.settings["reader_editable"] = bool(var_redit.get())
            self.settings["f3_use_external"] = bool(var_f3ext.get())
            # General tab
            self.settings["default_sort_files"] = [
                _label_to_id.get(var_fcol.get(), "modified"), bool(var_frev.get())]
            self.settings["default_sort_dirs"] = [
                _label_to_id.get(var_dcol.get(), "#0"), bool(var_drev.get())]
            self.settings["queue_alert_front"] = bool(var_qopen.get())
            self.settings["drive_memory"]      = bool(var_drvmem.get())
            self.settings["conflict_alert_mode"]     = var_cmode.get()
            self.settings["conflict_bar_keys"]       = bool(var_ckeys.get())
            self.settings["watch_src_dirs"]   = _w_dirs(var_wsrc)
            self.settings["watch_build_dirs"] = _w_dirs(var_wbld)
            self.settings["watch_chosen"]     = sorted(w_chosen)
            self.settings["watch_at_startup"] = bool(var_wstart.get())
            self.settings["trace_cursor"] = bool(var_trace.get())
            try:
                self.settings["trace_hours"] = max(1, min(720, int(var_thours.get())))
            except Exception:
                self.settings["trace_hours"] = 48
            try:
                _trace.configure(self.settings["trace_cursor"],
                                 self.settings["trace_hours"])
                _trace.prune()
            except Exception:
                pass
            self.settings["conflict_skip_identical"] = bool(var_cskip.get())
            self.settings["rule_scope_src"] = _RULE_SCOPE_NUM.get(var_rsrc.get(), 0)
            self.settings["rule_scope_dst"] = _RULE_SCOPE_NUM.get(var_rdst.get(), 0)
            # Switching away from the bar must take a bar that is already on
            # screen away with it, not leave a dead strip behind.
            try:
                self._conflict_bar_sync()
            except Exception:
                pass
            # (Where the queue SITS is no longer a setting — it is the ⚡
            # button's four states, applied the moment it is clicked.)
            self.settings["backup_move_dir"] = var_bdir.get().strip()
            self.settings["size_group_digits"] = bool(var_szgroup.get())
            self.settings["auto_folder_sizes"] = bool(var_autosz.get())
            self.settings["show_build_in_title"] = bool(var_showbuild.get())
            self.settings["queue_in_statusbar"] = bool(var_qinsb.get())
            self._apply_window_title()
            self.settings["mark_empty_dirs"] = bool(var_emptydir.get())
            self.settings["activate_uses_openers"] = bool(var_actopen.get())
            self.settings["activate_uses_hub"]     = bool(var_acthub.get())
            self.settings["activate_runs_programs"] = bool(var_actrun.get())
            self.settings["suite_icons"]           = bool(var_suiteic.get())
            self.settings["suite_icons_skip_text"] = bool(var_suitetx.get())
            # DefaultHub's table is cached after the first read; drop it so a
            # change made in DefaultHub is picked up without a restart.
            # The icon side keeps its own copy (it is read by a module-level
            # helper, not by this frame) — drop that one too, or the pictures
            # would go on showing yesterday's answer.
            self._hub_cache = None
            try:
                global _HUB_OWNERS_STAMP, _ICON_TREE_SUBS
                _HUB_OWNERS_STAMP = -1.0
                _ICON_TREE_SUBS = None
                _PROG_ICO_CACHE.clear()
                if _ICON_PROVIDER is not None:
                    _ICON_PROVIDER._hub_stamp = None
                    for _k in [k for k in _ICON_PROVIDER._cache
                               if k.startswith("hub:")]:
                        del _ICON_PROVIDER._cache[_k]
            except Exception:
                pass
            # Transfers (throttle)
            self.settings["io_background"]          = bool(var_io_bg.get())
            self.settings["copy_flush_mb"]          = max(0, int(var_flush.get()))
            self.settings["throttle_enabled"]       = bool(var_thr_on.get())
            self.settings["throttle_soft_after_s"]  = max(1, int(var_soft_after.get()))
            self.settings["throttle_soft_pct"]      = min(100, max(1, int(var_soft_pct.get())))
            self.settings["throttle_hard_after_s"]  = max(1, int(var_hard_after.get()))
            self.settings["throttle_hard_pct"]      = min(100, max(1, int(var_hard_pct.get())))
            self.settings["throttle_batch_after_s"] = max(1, int(var_batch_after.get()))
            self.settings["throttle_batch_pct"]     = min(100, max(1, int(var_batch_pct.get())))
            self.settings["fastlane_enabled"]       = bool(var_fl_on.get())
            self.settings["fastlane_max_mb"]        = max(1, int(var_fl_mb.get()))
            self.settings["fastlane_pause_big"]     = bool(var_fl_pause.get())
            self.settings["unpack_wait_enabled"]     = bool(var_up_wait.get())
            self.settings["unpack_wait_seconds"]     = max(5, int(var_up_every.get()))
            self.settings["unpack_wait_max_minutes"] = max(1, int(var_up_give.get()))
            self.settings["unpack_subfolder"]        = bool(var_up_sub.get())
            self.settings["unpack_delete_after"]     = bool(var_up_del.get())
            self.settings["unpack_mark_source_folder"] = bool(var_up_mark.get())
            self.settings["unpack_show_queue"]       = bool(var_up_show.get())
            self.settings["unpack_dest_other"]       = bool(var_up_other.get())
            self.settings["reader_extensions"] = var_readerx.get().strip() or "nfo, txt"
            # Customization: file colours by extension, live from the next
            # refresh (not "next start" — colours are the kind of thing you
            # want to SEE while you are choosing them).
            self.settings["ext_color_groups"] = collect_ext_groups()
            self.reload_ext_colours()
            self.save_settings()
            self.refresh_panels()   # apply the Size-grouping change immediately
            top.destroy()
            _flash_ok(self,
                      "Column width and default-sort changes take effect on "
                      "the next new tab (and on next Manager start).",
                      "Settings saved")

        ttk.Button(btn_row, text="Save",   command=_save,       width=12).pack(side="left")
        ttk.Button(btn_row, text="Cancel", command=top.destroy, width=10).pack(side="right")

        # Never open taller than the desktop can actually show.  An un-capped
        # window puts its own bottom edge under the taskbar; a capped one keeps
        # Save and Cancel on screen, because the row above them is now packed
        # first and no longer competes with the notebook for the last pixels.
        try:
            top.update_idletasks()
            want_w = max(560, top.winfo_reqwidth())
            want_h = top.winfo_reqheight()
            room_h = max(420, top.winfo_screenheight() - 140)
            top.geometry(f"{want_w}x{min(want_h, room_h)}")
        except Exception:
            pass



# ══════════════════════════════════════════════════════════════════════════
#  Search window  (non-blocking – runs in a daemon thread)
# ══════════════════════════════════════════════════════════════════════════

# Extensions treated as searchable plain-text for content search
_TEXT_EXTS = {
    ".txt", ".log", ".md", ".nfo", ".diz", ".nix",
    ".json", ".xml", ".csv", ".yaml", ".yml", ".toml", ".ini", ".cfg",
    ".py", ".pyw", ".js", ".ts", ".html", ".htm", ".css",
    ".bat", ".cmd", ".ps1", ".sh",
}


class SearchWindow(tk.Toplevel):
    """
    Non-blocking search dialog.

    • Searches recursively under a start folder by name (glob)
    • Can also search inside the content of text files
    • Runs in a background thread – does NOT freeze the main program
    • Double-click a hit → navigates the active panel to that result
    """

    def __init__(self, manager: "EditorFrame"):
        super().__init__(manager)
        self.manager = manager
        self.title("🔍  Search")
        self.geometry("820x580")
        self.resizable(True, True)

        # Do NOT grab_set – window must be non-modal
        self.transient(manager)
        self.focus_force()
        self.bind("<Escape>", lambda e: self._on_close())
        self.protocol("WM_DELETE_WINDOW", self._on_close)

        self._stop_event   = threading.Event()
        self._result_queue = queue.Queue()
        self._search_thread: threading.Thread | None = None
        self._after_id = None

        # ── start directory ────────────────────────────────────────────
        start = manager.get_active_panel().current_path

        # ── top form ──────────────────────────────────────────────────
        form = ttk.Frame(self, padding=(10, 8, 10, 4))
        form.pack(fill="x")

        # Row 0 – search pattern
        ttk.Label(form, text="File name:").grid(row=0, column=0, sticky="w", padx=(0, 6), pady=3)
        self._var_pattern = tk.StringVar(value="*")
        e_pat = tk.Entry(form, textvariable=self._var_pattern, width=30,
                         insertofftime=0, insertontime=9999999)
        e_pat.grid(row=0, column=1, sticky="we", pady=3)
        self._create_tip(e_pat, "File name glob, e.g.  *.txt  or  report*  (empty = all)")

        # Row 1 – content search
        ttk.Label(form, text="Search in files:").grid(row=1, column=0, sticky="w", padx=(0, 6), pady=3)
        self._var_content = tk.StringVar()
        e_cont = tk.Entry(form, textvariable=self._var_content, width=30,
                          insertofftime=0, insertontime=9999999)
        e_cont.grid(row=1, column=1, sticky="we", pady=3)
        self._create_tip(e_cont,
            "Optional text to find inside files\n"
            "(searches: txt json nfo log md xml csv py …)\n"
            "Leave empty to search by name only")

        # Row 2 – start dir
        ttk.Label(form, text="Start folder:").grid(row=2, column=0, sticky="w", padx=(0, 6), pady=3)
        self._var_dir = tk.StringVar(value=start)
        e_dir = tk.Entry(form, textvariable=self._var_dir, width=30,
                         insertofftime=0, insertontime=9999999)
        e_dir.grid(row=2, column=1, sticky="we", pady=3)
        btn_browse = ttk.Button(form, text="…", width=3,
                                command=self._browse_dir)
        btn_browse.grid(row=2, column=2, padx=(4, 0))

        # Row 3 – options
        opt_frame = ttk.Frame(form)
        opt_frame.grid(row=3, column=0, columnspan=3, sticky="w", pady=(4, 2))

        self._var_case    = tk.BooleanVar(value=False)
        self._var_subdirs = tk.BooleanVar(value=True)
        ttk.Checkbutton(opt_frame, text="Case-sensitive",
                        variable=self._var_case).pack(side="left", padx=(0, 14))
        ttk.Checkbutton(opt_frame, text="Search subdirectories",
                        variable=self._var_subdirs).pack(side="left")

        form.columnconfigure(1, weight=1)

        # ── button row ────────────────────────────────────────────────
        btn_row = ttk.Frame(self, padding=(10, 0, 10, 6))
        btn_row.pack(fill="x")

        self._btn_search = ttk.Button(btn_row, text="▶  Search", width=12,
                                      command=self._start_search)
        self._btn_search.pack(side="left")
        self._btn_stop = ttk.Button(btn_row, text="■  Stop", width=12,
                                    command=self._stop_search, state="disabled")
        self._btn_stop.pack(side="left", padx=6)
        ttk.Button(btn_row, text="Clear", width=8,
                   command=self._clear_results).pack(side="left")

        self._lbl_status = ttk.Label(btn_row, text="")
        self._lbl_status.pack(side="left", padx=10)

        ttk.Button(btn_row, text="Close", command=self._on_close).pack(side="right")

        # ── results treeview ──────────────────────────────────────────
        res_frame = ttk.Frame(self)
        res_frame.pack(fill="both", expand=True, padx=10, pady=(0, 8))

        cols = ("path", "match")
        self._tree = ttk.Treeview(res_frame, columns=cols, selectmode="browse")
        self._tree.heading("#0",     text="Name",         anchor="w")
        self._tree.heading("path",   text="Path",          anchor="w")
        self._tree.heading("match",  text="Match / line", anchor="w")
        self._tree.column("#0",    width=200, stretch=False)
        self._tree.column("path",  width=350, stretch=True)
        self._tree.column("match", width=220, stretch=True)
        self._tree.tag_configure("dir",  foreground="blue")
        self._tree.tag_configure("hit",  foreground="#007700")

        vsb = ttk.Scrollbar(res_frame, orient="vertical",   command=self._tree.yview)
        hsb = ttk.Scrollbar(res_frame, orient="horizontal", command=self._tree.xview)
        self._tree.configure(yscrollcommand=vsb.set, xscrollcommand=hsb.set)
        self._tree.grid(row=0, column=0, sticky="nsew")
        vsb.grid(row=0, column=1, sticky="ns")
        hsb.grid(row=1, column=0, sticky="ew")
        res_frame.rowconfigure(0, weight=1)
        res_frame.columnconfigure(0, weight=1)

        self._tree.bind("<Double-1>",  self._on_double_click)
        self._tree.bind("<Return>",    self._on_double_click)

        # Allow Enter to start search from the entry fields
        e_pat.bind("<Return>",  lambda e: self._start_search())
        e_cont.bind("<Return>", lambda e: self._start_search())
        e_dir.bind("<Return>",  lambda e: self._start_search())
        e_pat.focus_set()

    # ── helpers ───────────────────────────────────────────────────────

    def _create_tip(self, widget, text: str):
        """Simple tooltip."""
        tip: list[tk.Toplevel | None] = [None]

        def _show(e):
            tip[0] = tk.Toplevel(self)
            tip[0].overrideredirect(True)
            tip[0].attributes("-topmost", True)
            tk.Label(tip[0], text=text, background="#ffffe0",
                     relief="solid", borderwidth=1,
                     font=("Segoe UI", 8),
                     justify="left", padx=4, pady=2).pack()
            tip[0].geometry(f"+{e.x_root+14}+{e.y_root+14}")

        def _hide(e):
            if tip[0]:
                try:
                    tip[0].destroy()
                except Exception:
                    pass
                tip[0] = None

        widget.bind("<Enter>", _show)
        widget.bind("<Leave>", _hide)

    def _browse_dir(self):
        d = filedialog.askdirectory(
            initialdir=self._var_dir.get() or str(Path.home()),
            parent=self,
            title="Select start folder",
        )
        if d:
            self._var_dir.set(d)

    def _clear_results(self):
        self._tree.delete(*self._tree.get_children())
        self._lbl_status.configure(text="")

    # ── search control ────────────────────────────────────────────────

    def _start_search(self):
        # Abort any running search first
        self._stop_search()

        self._clear_results()
        self._stop_event.clear()

        root_dir  = self._var_dir.get().strip()
        pattern   = self._var_pattern.get().strip() or "*"
        content   = self._var_content.get().strip()
        case_sens = self._var_case.get()
        recursive = self._var_subdirs.get()

        if not root_dir or not os.path.isdir(root_dir):
            self._lbl_status.configure(text="⚠  Invalid start folder.")
            return

        self._btn_search.configure(state="disabled")
        self._btn_stop.configure(state="normal")
        self._lbl_status.configure(text="Searching …")

        self._search_thread = threading.Thread(
            target=self._search_worker,
            args=(root_dir, pattern, content, case_sens, recursive),
            daemon=True,
        )
        self._search_thread.start()
        self._after_id = self.after(100, self._poll_results)

    def _stop_search(self):
        self._stop_event.set()
        if self._after_id:
            try:
                self.after_cancel(self._after_id)
            except Exception:
                pass
            self._after_id = None
        self._btn_search.configure(state="normal")
        self._btn_stop.configure(state="disabled")

    # ── background worker ─────────────────────────────────────────────

    def _search_worker(self, root_dir: str, pattern: str,
                       content: str, case_sens: bool, recursive: bool):
        """Runs entirely in a daemon thread – never touches Tk directly."""
        import fnmatch

        # Normalise for case-insensitive matching
        pat_cmp  = pattern   if case_sens else pattern.lower()
        # Friendly name search: a word with no wildcard, or one that only ends
        # in * (Happymaker, Happymaker*), means "the name CONTAINS it" — so
        # The_Happymaker is found.  *.exe, ab?d, *x*y keep their exact meaning.
        # Several terms may be separated by ; or , .  Only ever matches more.
        def _friendly(term):
            term = term.strip()
            if not term:
                return None
            body = term[:-1] if term.endswith("*") else term
            if not any(c in body for c in "*?[") and not term.startswith("*"):
                return "*" + body + "*"
            return term
        pats = [p for p in (_friendly(t) for t in
                            pat_cmp.replace(";", ",").split(",")) if p]
        if not pats:
            pats = ["*"]
        def _name_ok(n):
            return any(fnmatch.fnmatchcase(n, p) for p in pats)
        cont_cmp = content   if case_sens else content.lower()
        count = 0

        walk_iter = os.walk(root_dir) if recursive else [(root_dir, [], os.listdir(root_dir))]

        for dirpath, dirnames, filenames in walk_iter:
            if self._stop_event.is_set():
                self._result_queue.put(("__stopped__", None, None, None))
                return

            # ── directory name match ─────────────────────────────────
            for dname in dirnames:
                if self._stop_event.is_set():
                    break
                cmp = dname if case_sens else dname.lower()
                if _name_ok(cmp):
                    full = os.path.join(dirpath, dname)
                    self._result_queue.put(("dir", dname, full, ""))
                    count += 1

            # ── file name + optional content match ───────────────────
            for fname in filenames:
                if self._stop_event.is_set():
                    break
                cmp = fname if case_sens else fname.lower()

                # name filter
                if not _name_ok(cmp):
                    continue

                full = os.path.join(dirpath, fname)

                # no content search requested → emit name-only hit
                if not cont_cmp:
                    self._result_queue.put(("file", fname, full, ""))
                    count += 1
                    continue

                # content search (only for recognised text extensions)
                ext = os.path.splitext(fname)[1].lower()
                if ext not in _TEXT_EXTS:
                    # emit name hit but mark as binary (no content search)
                    self._result_queue.put(("file", fname, full, ""))
                    count += 1
                    continue

                try:
                    with open(full, encoding="utf-8", errors="replace") as fh:
                        for lineno, line in enumerate(fh, 1):
                            if self._stop_event.is_set():
                                break
                            hay = line if case_sens else line.lower()
                            if cont_cmp in hay:
                                snippet = line.rstrip()[:120]
                                self._result_queue.put(
                                    ("hit", fname, full,
                                     f"line {lineno}: {snippet}")
                                )
                                count += 1
                except Exception:
                    pass

        # Signal done
        self._result_queue.put(("__done__", count, None, None))

    # ── UI polling ────────────────────────────────────────────────────

    def _poll_results(self):
        """Called from main thread every 100 ms to drain the result queue."""
        try:
            for _ in range(200):          # drain up to 200 items per tick
                kind, name, path, match = self._result_queue.get_nowait()

                if kind == "__done__":
                    self._lbl_status.configure(
                        text=f"✔  Done — {name} match(es)"
                        if name else "✔  No matches"
                    )
                    self._btn_search.configure(state="normal")
                    self._btn_stop.configure(state="disabled")
                    return

                if kind == "__stopped__":
                    n_hits = len(self._tree.get_children())
                    self._lbl_status.configure(
                        text=f"⏹  Stopped — {n_hits} match(es) shown"
                    )
                    self._btn_search.configure(state="normal")
                    self._btn_stop.configure(state="disabled")
                    return

                # Regular result
                tags = ("dir",) if kind == "dir" else ("hit",) if match else ()
                icon = "📁" if kind == "dir" else "📄"
                display_name = f"{icon}  {name}"
                self._tree.insert("", "end",
                                  text=display_name,
                                  values=(path, match or ""),
                                  tags=tags)
        except queue.Empty:
            pass

        # Re-schedule
        self._after_id = self.after(100, self._poll_results)

    # ── result navigation ─────────────────────────────────────────────

    def _on_double_click(self, event=None):
        sel = self._tree.selection()
        if not sel:
            return
        path = self._tree.set(sel[0], "path")
        if not path:
            return

        panel = self.manager.get_active_panel()
        if getattr(panel, "is_remote", False):
            return

        if os.path.isdir(path):
            panel.change_directory(path)
            self.manager._update_disk_info()
        elif os.path.isfile(path):
            parent = os.path.dirname(path)
            panel.change_directory(parent)
            self.manager._update_disk_info()
            # Try to select the file in the tree
            target_name = os.path.basename(path)
            for iid in panel.tree.get_children():
                if panel._fullname(iid) == target_name:
                    panel.tree.selection_set(iid)
                    panel.tree.focus(iid)
                    panel.tree.see(iid)
                    break

    # ── cleanup ───────────────────────────────────────────────────────

    def _on_close(self):
        self._stop_search()
        self.destroy()


# ══════════════════════════════════════════════════════════════════════════
#  DEL 42 · Shell file-type icons (Total-Commander-style)
# ══════════════════════════════════════════════════════════════════════════
#
#  Shows the real Windows shell icon in front of every file/folder so the file
#  type is obvious at a glance — no need to read the extension.  Icons are
#  looked up PER EXTENSION via SHGetFileInfo with SHGFI_USEFILEATTRIBUTES
#  (a registry lookup only, no disk read), and cached, so even huge folders
#  stay fast.  Requires Windows + Pillow; on anything else the feature quietly
#  disables itself and the panels render exactly as before.

_GDI_SIGS_READY = False


def _setup_gdi_signatures():
    """Declare argtypes/restypes so 64-bit GDI handles are not truncated.

    Without this, ctypes treats handles as C ints and a 64-bit HBITMAP/HDC
    overflows ("int too long to convert").  Idempotent + process-wide.
    """
    global _GDI_SIGS_READY
    if _GDI_SIGS_READY:
        return
    from ctypes import c_void_p, c_int, c_uint, POINTER, c_wchar_p
    from ctypes import wintypes
    g = ctypes.windll.gdi32
    u = ctypes.windll.user32
    u.GetDC.restype  = c_void_p; u.GetDC.argtypes = [c_void_p]
    u.ReleaseDC.argtypes  = [c_void_p, c_void_p]
    u.DrawIconEx.argtypes = [c_void_p, c_int, c_int, c_void_p,
                             c_int, c_int, c_uint, c_void_p, c_uint]
    u.DestroyIcon.argtypes = [c_void_p]
    g.CreateCompatibleDC.restype  = c_void_p
    g.CreateCompatibleDC.argtypes = [c_void_p]
    g.CreateDIBSection.restype  = c_void_p
    g.CreateDIBSection.argtypes = [c_void_p, c_void_p, c_uint,
                                   POINTER(c_void_p), c_void_p, c_uint]
    g.SelectObject.restype  = c_void_p
    g.SelectObject.argtypes = [c_void_p, c_void_p]
    g.DeleteObject.argtypes = [c_void_p]
    g.DeleteDC.argtypes     = [c_void_p]
    ctypes.windll.shell32.SHGetFileInfoW.argtypes = [
        c_wchar_p, wintypes.DWORD, c_void_p, c_uint, c_uint]
    _GDI_SIGS_READY = True


def _hicon_to_photoimage(hicon, size=16):
    """Convert a Win32 HICON into a Tk PhotoImage (16×16, alpha preserved)."""
    from PIL import Image, ImageTk
    from ctypes import wintypes

    _setup_gdi_signatures()
    gdi32  = ctypes.windll.gdi32
    user32 = ctypes.windll.user32

    class BITMAPINFOHEADER(ctypes.Structure):
        _fields_ = [("biSize", wintypes.DWORD), ("biWidth", wintypes.LONG),
                    ("biHeight", wintypes.LONG), ("biPlanes", wintypes.WORD),
                    ("biBitCount", wintypes.WORD), ("biCompression", wintypes.DWORD),
                    ("biSizeImage", wintypes.DWORD), ("biXPelsPerMeter", wintypes.LONG),
                    ("biYPelsPerMeter", wintypes.LONG), ("biClrUsed", wintypes.DWORD),
                    ("biClrImportant", wintypes.DWORD)]

    class BITMAPINFO(ctypes.Structure):
        _fields_ = [("bmiHeader", BITMAPINFOHEADER), ("bmiColors", wintypes.DWORD * 3)]

    bmi = BITMAPINFO()
    bmi.bmiHeader.biSize        = ctypes.sizeof(BITMAPINFOHEADER)
    bmi.bmiHeader.biWidth       = size
    bmi.bmiHeader.biHeight      = -size          # negative = top-down rows
    bmi.bmiHeader.biPlanes      = 1
    bmi.bmiHeader.biBitCount    = 32
    bmi.bmiHeader.biCompression = 0              # BI_RGB

    hdc_screen = user32.GetDC(0)
    memdc      = gdi32.CreateCompatibleDC(hdc_screen)
    ppv        = ctypes.c_void_p()
    hbmp = gdi32.CreateDIBSection(memdc, ctypes.byref(bmi), 0,
                                  ctypes.byref(ppv), None, 0)
    old = gdi32.SelectObject(memdc, hbmp)
    try:
        # DI_NORMAL alpha-blends the icon onto the (transparent) DIB, so a
        # 32-bit source icon keeps its per-pixel transparency.
        user32.DrawIconEx(memdc, 0, 0, hicon, size, size, 0, None, 0x0003)
        raw = (ctypes.c_char * (size * size * 4)).from_address(ppv.value)
        img = Image.frombuffer("RGBA", (size, size), bytes(raw), "raw", "BGRA", 0, 1)
        return ImageTk.PhotoImage(img)
    finally:
        gdi32.SelectObject(memdc, old)
        gdi32.DeleteObject(hbmp)
        gdi32.DeleteDC(memdc)
        user32.ReleaseDC(0, hdc_screen)


# ══════════════════════════════════════════════════════════════════════════
#  DEL 42b · MY OWN programs' icons, in front of the files they open (revBR)
# ══════════════════════════════════════════════════════════════════════════
#
#  Windows' shell icon for a .pdf is whatever Adobe once left in the
#  registry, and for half the types here it is a blank sheet of paper — the
#  programs that actually open these files are HIS, they are started through
#  DefaultHub, and they are not registered with Windows as default apps at
#  all.  (See the long note at "OPEN THINGS WITH MY OWN PROGRAMS" for why
#  registering them is not worth it: Windows identifies an application by its
#  .exe PATH, so every one of them would be the same app, "Python", with one
#  icon for all of them.)
#
#  So the icon is taken from the same two files that already answer the very
#  same question for the double-click:
#
#       Helpfiles\DefaultHub\defaults.json    ".pdf  ->  PDFull"
#       Icons\PDFull.ico                      the icon that program already has
#
#  That is the whole trick, and it is why no program has to be taught to hand
#  out its icon, nothing is imported, and nothing is LAUNCHED to ask: both
#  files are sitting there already, and the second one is named after the
#  answer the first one gives.  Change "PDFs open in X" in DefaultHub and the
#  icon in the panel changes with it, because there is only ever one table.
#
#  Everything falls through, never over:  a kind DefaultHub marks "system" is
#  a deliberate "let Windows have it" and keeps the shell icon; a program
#  with no .ico anywhere keeps the shell icon; a missing or half-written
#  defaults.json means "no opinion" and keeps the shell icon.  The column can
#  never end up blank because of this block.

_HUB_DEFAULTS_REL = ("Helpfiles", "DefaultHub", "defaults.json")

# House-keeping folders that are not program worlds.  0---Retired and
# 0---Claude_work_dir hold copies that are deliberately NOT his live
# programs — the same list DefaultHub's own folder search skips.
_ICON_TREE_SKIP = {"py", "helpfiles", "icons", "folder-exe", "downloads"}

_HUB_OWNERS: dict = {}
_HUB_OWNERS_STAMP: float = -1.0
_PROG_ICO_CACHE: dict = {}
_ICON_TREE_SUBS: "list | None" = None


def _hub_defaults_file() -> str:
    return os.path.join(str(APP_ROOT), *_HUB_DEFAULTS_REL)


def _hub_defaults_stamp() -> float:
    """mtime of DefaultHub's table, 0.0 when there is none."""
    try:
        return os.path.getmtime(_hub_defaults_file())
    except OSError:
        return 0.0


def _hub_ext_owners() -> dict:
    """{'.pdf': ('pdf', 'PDFull'), '.jpg': ('image', 'SeeView'), …}

    Extension -> (kind id, program name), read straight from DefaultHub and
    re-read only when the file's mtime changes.  Only kinds marked "suite"
    are listed: "system" is an answer ("Windows owns this"), not a gap.
    File_manager itself is dropped — handing a folder its own icon would
    replace the folder picture with this program's."""
    global _HUB_OWNERS, _HUB_OWNERS_STAMP
    stamp = _hub_defaults_stamp()
    if stamp == _HUB_OWNERS_STAMP:
        return _HUB_OWNERS
    owners = {}
    try:
        with open(_hub_defaults_file(), "r", encoding="utf-8") as fh:
            data = json.load(fh) or {}
        for kind_id, kind in (data.get("kinds") or {}).items():
            if not isinstance(kind, dict):
                continue
            if kind.get("match_type") != "extension":
                continue
            if kind.get("target_type") != "suite":
                continue
            target = str(kind.get("target") or "").strip()
            if not target or target.lower() == "file_manager":
                continue
            for m in (kind.get("match") or []):
                ext = str(m).strip().lower()
                if ext and not ext.startswith("."):
                    ext = "." + ext
                if ext:
                    owners[ext] = (str(kind_id).lower(), target)
    except Exception:
        owners = {}                 # missing / half-written = no opinion
    _HUB_OWNERS, _HUB_OWNERS_STAMP = owners, stamp
    return owners


def _icon_tree_subs() -> list:
    """The program worlds under the home folder (1---Musik, 1---Annat, …)."""
    global _ICON_TREE_SUBS
    if _ICON_TREE_SUBS is not None:
        return _ICON_TREE_SUBS
    subs = []
    try:
        root = str(APP_ROOT)
        for entry in sorted(os.listdir(root)):
            low = entry.lower()
            if (low in _ICON_TREE_SKIP or low.startswith("0---")
                    or low.startswith("~")):
                continue
            sub = os.path.join(root, entry)
            if os.path.isdir(sub):
                subs.append(sub)
    except OSError:
        pass
    _ICON_TREE_SUBS = subs
    return subs


def _program_icon_file(name: str) -> str:
    """Where <name>'s own icon file is, or "".

    An `Icons` folder sits beside the `Py` folder it belongs to — that is the
    shape of the whole tree, and `Icons\\SeeView.ico` answers almost every
    case on its own.  Two more places are looked at because two real programs
    live there: a music program's icon is in `1---Musik\\Icons`, and a
    program with its own folder keeps its .ico beside its .py
    (`1---Annat\\Chess\\Chess.ico`).  A build's .exe is the last resort — it
    carries the same picture baked in, so a program that never got a loose
    .ico still shows the right one.  Cached per name: this walk runs once per
    program, not once per file."""
    key = name.lower()
    if key in _PROG_ICO_CACHE:
        return _PROG_ICO_CACHE[key]
    found = ""
    try:
        root  = str(APP_ROOT)
        subs  = _icon_tree_subs()
        cands = [os.path.join(root, "Icons", name + ".ico")]
        for sub in subs:
            cands.append(os.path.join(sub, "Icons", name + ".ico"))
            cands.append(os.path.join(sub, name, name + ".ico"))
        cands.append(os.path.join(root, "Folder-exe", name, name + ".exe"))
        for sub in subs:
            cands.append(os.path.join(sub, "Folder-exe", name, name + ".exe"))
        for cand in cands:
            if os.path.isfile(cand):
                found = cand
                break
    except Exception:
        found = ""
    _PROG_ICO_CACHE[key] = found
    return found


def _real_file_photoimage(path: str, size: int = 16):
    """The icon a REAL file carries — used for a build's .exe.

    Deliberately without SHGFI_USEFILEATTRIBUTES: that flag means "answer
    from the registry, do not touch the disk", which is right for a
    per-extension lookup and exactly wrong here, where the whole point is the
    icon inside THIS .exe."""
    from ctypes import wintypes

    class SHFILEINFO(ctypes.Structure):
        _fields_ = [("hIcon", wintypes.HICON), ("iIcon", ctypes.c_int),
                    ("dwAttributes", wintypes.DWORD),
                    ("szDisplayName", ctypes.c_wchar * 260),
                    ("szTypeName", ctypes.c_wchar * 80)]

    _setup_gdi_signatures()
    info = SHFILEINFO()
    res = ctypes.windll.shell32.SHGetFileInfoW(
        path, 0, ctypes.byref(info), ctypes.sizeof(info),
        0x00000100 | 0x00000001)          # SHGFI_ICON | SHGFI_SMALLICON
    if not res or not info.hIcon:
        return None
    try:
        return _hicon_to_photoimage(info.hIcon, size)
    finally:
        ctypes.windll.user32.DestroyIcon(info.hIcon)


def _ico_to_photoimage(path: str, size: int = 16):
    """A 16x16 Tk PhotoImage from a program's .ico (or from its .exe)."""
    if path.lower().endswith(".exe"):
        return _real_file_photoimage(path, size)
    from PIL import Image, ImageTk

    img = Image.open(path)
    try:
        # An .ico holds SEVERAL sizes.  Pillow opens the largest, and
        # shrinking a 256-px frame to 16 px turns a crisp icon into grey
        # mush — so take the smallest frame that is still at least 16 px
        # (usually the hand-made 16-px one) and scale that.
        pick = None
        for w, h in sorted(img.ico.sizes()):
            if w >= size and (pick is None or w < pick[0]):
                pick = (w, h)
        if pick and pick != img.size:
            img = img.ico.getimage(pick)
    except Exception:
        pass                    # not an .ico, or an old Pillow — scale below
    img = img.convert("RGBA")
    if img.size != (size, size):
        img = img.resize((size, size), Image.LANCZOS)
    return ImageTk.PhotoImage(img)


class _ShellIconProvider:
    """Per-extension cache of small shell icons for the file panels.

    One shared instance serves both panels.  Returns a Tk PhotoImage (whose
    reference it keeps alive so tkinter does not garbage-collect it) or None
    when icons are unavailable / disabled.
    """

    _SHGFI_ICON             = 0x00000100
    _SHGFI_SMALLICON        = 0x00000001
    _SHGFI_USEFILEATTRIBUTES = 0x00000010
    _FILE_ATTRIBUTE_NORMAL    = 0x00000080
    _FILE_ATTRIBUTE_DIRECTORY = 0x00000010

    def __init__(self):
        self._cache: dict = {}          # key -> PhotoImage | None
        # revBR — DefaultHub program icons.  Switched from the settings on
        # every panel refresh, see configure().
        self._suite     = True
        self._skip_text = False
        self._hub_stamp = None
        self._ok = (platform.system() == "Windows")
        if self._ok:
            try:
                import PIL.ImageTk       # noqa: F401  (probe availability)
                _setup_gdi_signatures()
            except Exception:
                self._ok = False

    @property
    def available(self) -> bool:
        return self._ok

    def configure(self, suite: bool = True, skip_text: bool = False):
        """Set the DefaultHub-icon switches (revBR).  Called once per refresh.

        This is also the one place DefaultHub's table is re-checked: one
        os.stat per panel refresh, so a change made over in DefaultHub shows
        up on the next Ctrl+R instead of surviving until the next restart.
        Only the program icons are dropped from the cache when something
        changes — the Windows shell icons cost a registry lookup each and
        have no reason to be thrown away."""
        suite, skip_text = bool(suite), bool(skip_text)
        stamp = _hub_defaults_stamp() if suite else None
        if (suite, skip_text, stamp) == (self._suite, self._skip_text,
                                         self._hub_stamp):
            return
        self._suite, self._skip_text, self._hub_stamp = suite, skip_text, stamp
        for key in [k for k in self._cache if k.startswith("hub:")]:
            del self._cache[key]

    def folder(self):
        """Generic closed-folder icon (also used for the '..' row)."""
        return self._lookup("<DIR>", "folder", is_dir=True)

    def for_file(self, name: str):
        """Icon for a file, keyed on its (lower-cased) extension.

        A type one of MY OWN programs owns wears THAT program's icon (revBR);
        everything else keeps the Windows shell icon exactly as before."""
        _, ext = os.path.splitext(name)
        ext = ext.lower()
        if self._suite and ext:
            img = self._suite_icon(ext)
            if img is not None:
                return img
        key = ext if ext else "<NOEXT>"
        return self._lookup(key, "file" + ext, is_dir=False)

    def _suite_icon(self, ext: str):
        """PDFull's icon for a .pdf, SeeView's for a .jpg — or None (revBR).

        None means "no answer here", not "no icon": the caller falls through
        to the Windows shell icon, which is what a type nobody owns, a
        program with no .ico and a missing defaults.json all end up with."""
        if not self._ok:
            return None
        key = "hub:" + ext
        if key in self._cache:
            return self._cache[key]
        img = None
        try:
            kind, target = _hub_ext_owners().get(ext, ("", ""))
            # "text" is ONE kind covering .py .json .txt .md .log .csv .xml,
            # so with the skip on it is left to Windows and those extensions
            # keep telling themselves apart.
            if target and not (self._skip_text and kind == "text"):
                path = _program_icon_file(target)
                if path:
                    img = _ico_to_photoimage(path, 16)
        except Exception as exc:
            _log(f"Program icon for {ext!r} failed: {exc}")
            img = None
        self._cache[key] = img          # cache even None so we don't retry
        return img

    # ── internals ─────────────────────────────────────────────────────────
    def _lookup(self, key, sample_name, is_dir):
        if not self._ok:
            return None
        if key in self._cache:
            return self._cache[key]
        img = None
        try:
            img = self._build(sample_name, is_dir)
        except Exception as exc:
            _log(f"Icon lookup failed for {key!r}: {exc}")
            img = None
        self._cache[key] = img          # cache even None so we don't retry
        return img

    def _build(self, sample_name, is_dir):
        from ctypes import wintypes

        class SHFILEINFO(ctypes.Structure):
            _fields_ = [("hIcon", wintypes.HICON), ("iIcon", ctypes.c_int),
                        ("dwAttributes", wintypes.DWORD),
                        ("szDisplayName", ctypes.c_wchar * 260),
                        ("szTypeName", ctypes.c_wchar * 80)]

        info  = SHFILEINFO()
        attrs = (self._FILE_ATTRIBUTE_DIRECTORY if is_dir
                 else self._FILE_ATTRIBUTE_NORMAL)
        flags = (self._SHGFI_ICON | self._SHGFI_SMALLICON
                 | self._SHGFI_USEFILEATTRIBUTES)
        res = ctypes.windll.shell32.SHGetFileInfoW(
            sample_name, attrs, ctypes.byref(info), ctypes.sizeof(info), flags)
        if not res or not info.hIcon:
            return None
        try:
            return _hicon_to_photoimage(info.hIcon, 16)
        finally:
            ctypes.windll.user32.DestroyIcon(info.hIcon)


# One provider shared by every panel; created lazily on first use (needs Tk).
_ICON_PROVIDER: "_ShellIconProvider | None" = None


def _icons():
    """Return the shared icon provider, building it on first call."""
    global _ICON_PROVIDER
    if _ICON_PROVIDER is None:
        _ICON_PROVIDER = _ShellIconProvider()
    return _ICON_PROVIDER


# ══════════════════════════════════════════════════════════════════════════
#  Clipboard file interchange (CF_HDROP) — real Ctrl+C / Ctrl+X / Ctrl+V
# ══════════════════════════════════════════════════════════════════════════
#
# Until now the only thing this program ever put on the clipboard was PATH
# TEXT (SEL ▾ "Copy paths to clipboard"), and it never read the clipboard at
# all — so copying a file in Explorer and pressing Ctrl+V in here did
# nothing; nothing here was listening for it.  Explorer (and virtually every
# other Windows program) exchanges actual FILES through two clipboard
# formats: CF_HDROP — the same list-of-paths structure a drag-and-drop hands
# over — plus "Preferred DropEffect", a 4-byte flag saying whether it was a
# Copy or a Cut.  The two functions below talk that format directly with
# ctypes, no pywin32 dependency, matching how the rest of this file already
# calls Win32 (see _drive_kind_info, the MTP block, etc.).  Ctrl+C / Ctrl+X /
# Ctrl+V now work exactly like they do in every other program, in BOTH
# directions: paste something copied in Explorer into a panel here, or copy
# files here and paste them into Explorer, an email, or anywhere else that
# accepts dropped files.

_CF_HDROP        = 15
_DROPEFFECT_COPY = 1
_DROPEFFECT_MOVE = 2
_GMEM_MOVEABLE   = 0x0002
_GMEM_ZEROINIT   = 0x0040


def clipboard_get_files():
    """Files currently on the Windows clipboard, or ([], False) if none.

    Returns (paths, is_cut).  is_cut is True when the files were put there
    with a Cut (Explorer's own "Preferred DropEffect" says Move) — the
    caller should then MOVE rather than copy, exactly as pasting into
    Explorer would.  Never raises: a busy, empty, or non-file clipboard just
    comes back as no files.
    """
    try:
        from ctypes import wintypes
        u32, k32, s32 = (ctypes.windll.user32, ctypes.windll.kernel32,
                         ctypes.windll.shell32)
        # HANDLEs are pointer-sized; left at ctypes' default (32-bit signed
        # int) they get silently truncated on 64-bit Python — a very quiet
        # bug where a handle above 2 GB comes back negative and every later
        # call on it fails.  Every HANDLE here is typed as c_void_p.
        u32.GetClipboardData.restype  = ctypes.c_void_p
        u32.GetClipboardData.argtypes = [wintypes.UINT]
        s32.DragQueryFileW.restype    = wintypes.UINT
        s32.DragQueryFileW.argtypes   = [ctypes.c_void_p, wintypes.UINT,
                                         ctypes.c_wchar_p, wintypes.UINT]
        k32.GlobalLock.restype    = ctypes.c_void_p
        k32.GlobalLock.argtypes   = [ctypes.c_void_p]
        k32.GlobalUnlock.argtypes = [ctypes.c_void_p]

        if not u32.OpenClipboard(0):
            return [], False
        try:
            paths = []
            hdrop = u32.GetClipboardData(_CF_HDROP)
            if hdrop:
                n = s32.DragQueryFileW(hdrop, 0xFFFFFFFF, None, 0)
                for i in range(n):
                    need = s32.DragQueryFileW(hdrop, i, None, 0)
                    buf  = ctypes.create_unicode_buffer(need + 1)
                    s32.DragQueryFileW(hdrop, i, buf, need + 1)
                    if buf.value:
                        paths.append(buf.value)
            is_cut = False
            if paths:
                fmt = u32.RegisterClipboardFormatW("Preferred DropEffect")
                h   = u32.GetClipboardData(fmt)
                if h:
                    p = k32.GlobalLock(h)
                    if p:
                        try:
                            val = ctypes.cast(
                                p, ctypes.POINTER(wintypes.DWORD)).contents.value
                            is_cut = bool(val & _DROPEFFECT_MOVE)
                        finally:
                            k32.GlobalUnlock(h)
            return paths, is_cut
        finally:
            u32.CloseClipboard()
    except Exception as exc:
        _log(f"clipboard_get_files: {exc}")
        return [], False


def clipboard_set_files(paths: list, cut: bool = False) -> bool:
    """Put local file paths on the clipboard as CF_HDROP, Explorer-style.

    *cut* marks it as a Cut (Preferred DropEffect = Move) instead of a Copy,
    so pasting these files anywhere — Explorer, another program, or back
    into this one — removes the originals, the same as after a real Ctrl+X.
    Returns whether it worked; a failure here is quiet, same as any other
    clipboard-busy moment (another program briefly holding it open).
    """
    if not paths:
        return False
    try:
        from ctypes import wintypes

        class _DROPFILES(ctypes.Structure):
            _fields_ = [("pFiles", wintypes.DWORD), ("pt", wintypes.POINT),
                        ("fNC", wintypes.BOOL), ("fWide", wintypes.BOOL)]

        u32, k32 = ctypes.windll.user32, ctypes.windll.kernel32
        k32.GlobalAlloc.restype   = ctypes.c_void_p
        k32.GlobalAlloc.argtypes  = [wintypes.UINT, ctypes.c_size_t]
        k32.GlobalLock.restype    = ctypes.c_void_p
        k32.GlobalLock.argtypes   = [ctypes.c_void_p]
        k32.GlobalUnlock.argtypes = [ctypes.c_void_p]
        k32.GlobalFree.argtypes   = [ctypes.c_void_p]
        u32.SetClipboardData.restype  = ctypes.c_void_p
        u32.SetClipboardData.argtypes = [wintypes.UINT, ctypes.c_void_p]

        body     = ("\0".join(paths) + "\0\0").encode("utf-16-le")
        hdr_size = ctypes.sizeof(_DROPFILES)
        h_drop   = k32.GlobalAlloc(_GMEM_MOVEABLE | _GMEM_ZEROINIT,
                                   hdr_size + len(body))
        if not h_drop:
            return False
        p = k32.GlobalLock(h_drop)
        if not p:
            k32.GlobalFree(h_drop)
            return False
        try:
            header = _DROPFILES(pFiles=hdr_size, pt=wintypes.POINT(0, 0),
                                fNC=False, fWide=True)
            ctypes.memmove(p, ctypes.byref(header), hdr_size)
            ctypes.memmove(p + hdr_size, body, len(body))
        finally:
            k32.GlobalUnlock(h_drop)

        h_effect = k32.GlobalAlloc(_GMEM_MOVEABLE | _GMEM_ZEROINIT,
                                   ctypes.sizeof(wintypes.DWORD))
        if h_effect:
            p2 = k32.GlobalLock(h_effect)
            if p2:
                eff = wintypes.DWORD(_DROPEFFECT_MOVE if cut else _DROPEFFECT_COPY)
                ctypes.memmove(p2, ctypes.byref(eff), ctypes.sizeof(eff))
                k32.GlobalUnlock(h_effect)

        if not u32.OpenClipboard(0):
            k32.GlobalFree(h_drop)
            if h_effect:
                k32.GlobalFree(h_effect)
            return False
        try:
            u32.EmptyClipboard()
            # SetClipboardData takes OWNERSHIP of the handle on success — it
            # must NOT be freed afterwards, or the next paste anywhere would
            # read memory this process already handed back to Windows.
            if not u32.SetClipboardData(_CF_HDROP, h_drop):
                k32.GlobalFree(h_drop)
                return False
            if h_effect:
                fmt = u32.RegisterClipboardFormatW("Preferred DropEffect")
                if not u32.SetClipboardData(fmt, h_effect):
                    k32.GlobalFree(h_effect)
            return True
        finally:
            u32.CloseClipboard()
    except Exception as exc:
        _log(f"clipboard_set_files: {exc}")
        return False


# ══════════════════════════════════════════════════════════════════════════
#  File panel (local)
# ══════════════════════════════════════════════════════════════════════════

class FilePanel(ttk.Frame):

    def __init__(self, parent, side, manager: EditorFrame):
        super().__init__(parent)
        self.manager     = manager
        self.side        = side
        self.is_remote   = False
        _saved_path = manager.last_positions.get(
            side,
            manager.settings.get(f"start_dir_{side}", DEFAULT_START_DIR)
        )
        # The saved path may be gone — the folder was deleted since, or the
        # settings were written on another machine.  Walk UP to the nearest
        # folder that still exists rather than opening in the user folder: a
        # Workspace made when D:\Foo\Bar existed opens in D:\Foo (revBU).
        if not os.path.isdir(_saved_path):
            up = _nearest_existing_dir(_saved_path)
            _log(f"Saved path not found: {_saved_path!r} — opening in {up!r}.")
            _saved_path = up or os.path.expanduser("~")
        if not os.path.isdir(_saved_path):
            _saved_path = DEFAULT_START_DIR
        self.current_path = os.path.abspath(_saved_path)

        self._rename_entry = None
        self._rename_data  = None
        self._rename_after = None   # scheduled after-id for slow-click rename
        self._press_xy     = None   # where Button-1 went down (drag vs slow click)
        # revCE: a slow-click rename needs an EARLIER plain mouse click on the
        # same row, no longer than this many seconds ago.
        self._last_plain_click = ("", 0.0)
        self.SLOW_CLICK_MAX_GAP_S = 2.5

        # Independent sort state for files and folders.  Left-click a column
        # header sorts files; right-click sorts folders.  Defaults come from
        # settings so a fresh tab opens with the user's preferred order
        # (factory default: files newest-first, folders alphabetically).
        _df = manager.settings.get("default_sort_files", ["modified", True])
        _dd = manager.settings.get("default_sort_dirs",  ["#0", False])
        self._sort_files_col = _df[0] if _df and _df[0] else "modified"
        self._sort_files_rev = bool(_df[1]) if _df and len(_df) > 1 else True
        self._sort_dirs_col  = _dd[0] if _dd and _dd[0] else "#0"
        self._sort_dirs_rev  = bool(_dd[1]) if _dd and len(_dd) > 1 else False

        # Full filename (base+ext) for every tree item – kept in sync with refresh()
        self._iid_to_fullname: dict = {}

        # Items explicitly marked with Insert / Shift+arrows (iid → stays until dir change)
        self._marked: set = set()
        # Re-entrancy guard for _reconcile_marked_cursor(), which itself calls
        # selection_remove() — that would otherwise re-trigger <<TreeviewSelect>>
        # and recurse.
        self._reconciling_marks = False

        # Selection captured on ButtonPress-1, before ttk.Treeview collapses a
        # multi-row selection down to the clicked row.  Used so a drag started
        # on a normally (Ctrl/Shift) multi-selected set still carries them all.
        self._drag_sel_snapshot: tuple = ()

        # The row the cursor last stood on, remembered by NAME.  iids are thrown
        # away on every rebuild, so a name is the only thing that survives an
        # auto-refresh or a trip through another program.  Without it, coming
        # back to this panel used to drop the cursor on row 0 — the ".." row —
        # and the next Enter went UP a level instead of opening anything.
        self._last_cursor_name: str = ""
        # (name, timestamp) of the row the cursor was just PUT on by the
        # program itself (Tab, a click, an activation).  A refresh landing
        # within two seconds honours it instead of guessing — see refresh()
        # and _promote_panel.  Unlike _last_cursor_name this one may be "..".
        self._cursor_pin: tuple = ("", 0.0)
        # (iid, name, time) of the row a plain mouse click just landed on; see
        # _on_single_click and __promote_panel (revCD).
        self._click_target: tuple = ("", "", 0.0)
        # (row, timestamp) of the last HOME press that landed on the top row.
        # Only a real, recent, still-standing Home press turns the NEXT one
        # into the "drop to the first file" move — see _on_home_key.
        self._home_stamp: tuple = ("", 0.0)

        # Branch view (Ctrl+B): list the whole tree flat instead of one level
        self.branch_mode = False
        self.branch_dirs = False      # Ctrl+Shift+B also lists folders

        # Treeview tag names already configured for label colours
        self._tag_colours: set = set()

        # Browsing INSIDE an archive (Enter / double-click on a ZIP/RAR/7z/…
        # descends into it exactly like a folder — see enter_archive() below).
        # None while showing the real disk; a dict while inside one:
        #   archive_path  — the .zip/.rar/… file on disk
        #   real_path     — the real folder that contains it, to return to
        #   subpath       — current folder INSIDE the archive ("" = root),
        #                   forward-slash separated, no leading/trailing slash
        #   entries       — the whole archive's ArchiveEntry list (loaded once)
        #   fmt           — logical format string, e.g. "zip" / "rar" / "7z"
        self.archive_ctx: dict | None = None

        self.tree = ttk.Treeview(
            self,
            columns=("type", "flag", "size", "modified", "attributes", "tags"),
            selectmode="extended"
        )
        # Left-click a header = sort FILES; right-click a header = sort FOLDERS
        self.tree.heading("#0",          text="Name",       anchor="w", command=lambda: self._sort_files_by("#0"))
        self.tree.heading("type",        text="Type",       anchor="w", command=lambda: self._sort_files_by("type"))
        # ★ — the hand-set "done with this one" flag (DEL 42b).  Its header
        # sorts like any other column, which is how you pull every flagged
        # row to the top of a busy folder.
        self.tree.heading("flag",        text=FLAG_CHAR,    anchor="center", command=lambda: self._sort_files_by("flag"))
        self.tree.heading("size",        text="Size",       anchor="e", command=lambda: self._sort_files_by("size"))
        self.tree.heading("modified",    text="Modified",   anchor="w", command=lambda: self._sort_files_by("modified"))
        self.tree.heading("attributes",  text="Attr",       anchor="w", command=lambda: self._sort_files_by("attributes"))
        self.tree.heading("tags",        text="Tags",       anchor="w", command=lambda: self._sort_files_by("tags"))
        _cw = manager.settings.get("column_widths", {})
        self.tree.column("#0",          stretch=True, width=_cw.get("name",       320))
        self.tree.column("type",        width=_cw.get("type",       100), anchor="w")
        self.tree.column("flag",        width=_cw.get("flag",        26),
                         minwidth=18, stretch=False, anchor="center")
        self.tree.column("size",        width=_cw.get("size",        90), anchor="e")
        self.tree.column("modified",    width=_cw.get("modified",   140), anchor="w")
        self.tree.column("attributes",  width=_cw.get("attributes",  70), anchor="w")
        # Remembered width, applied only when this folder has tagged items
        self._tags_col_width = _cw.get("tags", 110)
        self.tree.column("tags", width=0, minwidth=0, stretch=False, anchor="w")
        self.tree.tag_configure("dir",             foreground="blue")
        # Completely-empty folders (no files, no sub-folders) get a dimmer,
        # blue-grey tint so they are easy to spot.  Change the colour here.
        self.tree.tag_configure("dir_empty",       foreground="#8ea6c8")
        self.tree.tag_configure("hidden",          foreground="gray")
        self.tree.tag_configure("marked",          background="#cc2222", foreground="#ffffff")
        self.tree.tag_configure("marked_inactive", background="#cc8888", foreground="#2a2a2a")
        # Cursor sitting on an already-marked row: ttk.Treeview always paints
        # the WHOLE row in its native "selected" colour, which otherwise hides
        # the red 'marked' tag completely (whole-row wins over whole-row, not
        # column by column — there's no per-cell colouring in this widget).
        # _reconcile_marked_cursor() pulls such rows OUT of the native
        # selection and applies this tag instead — a THIRD colour of its own
        # (neither plain red nor plain blue), so "marked", "cursor", and
        # "cursor on a marked file" are three unambiguous looks rather than
        # one being a blend of the other two. Change the colour here.
        self.tree.tag_configure("marked_cursor",   background="#8a3fb5", foreground="#ffffff")
        # The INACTIVE panel's cursor row: a neutral GREY (deliberately NOT blue)
        # so it can never be mistaken for the active panel's dark-blue selection.
        self.tree.tag_configure("inactive_sel",    background="#c6c6c6", foreground="#333333")
        # ⚖ Side comparison (DEL 48) — change these three to re-colour it.
        # Dark, saturated shades so they stay readable on the light list.
        self.tree.tag_configure("cmp_newer",     foreground="#0b7a25")   # green  = newer, different size
        self.tree.tag_configure("cmp_older",     foreground="#c1121f")   # red    = older, different size
        self.tree.tag_configure("cmp_same_diff", foreground="#a15c00")   # amber  = same moment, different size
        self.tree.tag_configure("cmp_restamp",   foreground="#1a5fb4")   # blue   = same size, different moment
        self.tree.tag_configure("cmp_only",      foreground="#7b3fb5")   # violet = on this side only

        scroll = ttk.Scrollbar(self, orient="vertical", command=self.tree.yview)
        self.tree.configure(yscrollcommand=scroll.set)
        # Pack the scrollbar FIRST so it always keeps its width and is never
        # clipped off the edge when the panel is made narrow (pack gives space
        # to earlier-packed widgets first; an expand=True tree packed first
        # would otherwise swallow the scrollbar's column).
        scroll.pack(side="right", fill="y")
        self.tree.pack(side="left", fill="both", expand=True)

        # Archive breadcrumb — "📦 archive.zip › sub › folder" + an Exit
        # button.  Created here but not packed until enter_archive() shows it,
        # using before=self.tree so it takes its own row above the list
        # whenever it IS packed (see _show_archive_bar / _hide_archive_bar).
        self._archive_bar = tk.Frame(self, bg=C_BG3)
        self._archive_bar_lbl = tk.Label(
            self._archive_bar, text="", bg=C_BG3, fg=C_ACCENT,
            font=("Segoe UI", 9, "bold"), anchor="w")
        self._archive_bar_lbl.pack(side="left", padx=(6, 4), pady=3)
        tk.Button(self._archive_bar, text="✕ Exit archive", bg="grey", fg="white",
                  font=("Segoe UI", 8), relief="flat", padx=6,
                  command=lambda: self.exit_archive()).pack(side="right", padx=6, pady=2)

        self.tree.bind("<Double-1>",   self._on_double_click)
        # A 3rd and 4th press inside the double-click time are the SAME burst,
        # not a second order.  Without these two bindings Tk hands them to the
        # <Double-1> binding above, and one impatient burst of clicks on ".."
        # opened / went up / opened / went up.  (revBQ)
        self.tree.bind("<Triple-1>",    self._on_extra_click)
        self.tree.bind("<Quadruple-1>", self._on_extra_click)
        self.tree.bind("<Button-3>",   self._on_right_click)
        self.tree.bind("<Button-1>",   self._on_single_click)
        # Any real mouse movement with the button down means "drag", not "slow
        # click" — kill the pending inline rename before it can open.  add="+"
        # so the Treeview's own drag-select and tkinterdnd2 keep working.
        self.tree.bind("<B1-Motion>",      self._cancel_slow_rename, add="+")
        self.tree.bind("<Leave>",          self._cancel_slow_rename, add="+")
        self.tree.bind("<FocusOut>",       self._cancel_slow_rename, add="+")
        self.tree.bind("<FocusIn>",
                       lambda e: manager._activate_side(side, set_focus=False))
        self.tree.bind("<Insert>",     self._on_insert_key)
        self.tree.bind("<Shift-Up>",   self._on_shift_up)
        self.tree.bind("<Shift-Down>", self._on_shift_down)
        # Home / End jump to the first / last row (ttk.Treeview does not do
        # this by default).  Ctrl+Home / Ctrl+End behave the same.
        self.tree.bind("<Home>",         self._on_home_key)
        self.tree.bind("<End>",          self._on_end_key)
        self.tree.bind("<Control-Home>", self._on_home_key)
        self.tree.bind("<Control-End>",  self._on_end_key)
        # Page Up / Page Down move the CURSOR by one visible page (ttk.Treeview
        # only scrolls the view by default, which left the cursor behind).
        # Ctrl+Page = fixed small jump (no marking), Shift+Page = big jump that
        # MARKS everything it passes, the way Shift+Up / Shift+Down do.
        self.tree.bind("<Prior>",         self._on_page_up)
        self.tree.bind("<Next>",          self._on_page_down)
        self.tree.bind("<Control-Prior>", self._on_ctrl_page_up)
        self.tree.bind("<Control-Next>",  self._on_ctrl_page_down)
        self.tree.bind("<Shift-Prior>",   self._on_shift_page_up)
        self.tree.bind("<Shift-Next>",    self._on_shift_page_down)
        # Select-all / range-select.  Ctrl+A marks everything; Shift+End and
        # Shift+Home mark from the cursor to the last / first row.  (Both cases
        # and the lowercase 'a' are bound so it works regardless of Caps/Shift.)
        self.tree.bind("<Control-a>",    self._on_select_all)
        self.tree.bind("<Control-A>",    self._on_select_all)
        self.tree.bind("<Control-n>",    self._on_unmark_all)   # N = None (unmark)
        self.tree.bind("<Control-N>",    self._on_unmark_all)
        self.tree.bind("<Shift-End>",    self._on_shift_end)
        self.tree.bind("<Shift-Home>",   self._on_shift_home)
        # Numeric-keypad "*" / "-" — Total Commander-style mark-all / unmark-all,
        # with the modifier deciding WHAT gets (un)marked:
        #   plain        → files only   (folders untouched)
        #   Shift        → folders only (files untouched)
        #   Ctrl         → both files and folders (same as Ctrl+A / Ctrl+N)
        # Bound under BOTH possible keysym names for the plain/no-modifier
        # case: some Tcl/Tk-on-Windows builds report the numpad operator keys
        # as KP_Multiply/KP_Subtract, others as plain asterisk/minus,
        # depending on Tk version and keyboard driver — binding both means it
        # works either way. (Shift/Ctrl combos follow suit for consistency.)
        for mult_sym, sub_sym in (("KP_Multiply", "KP_Subtract"),
                                   ("asterisk",    "minus")):
            self.tree.bind(f"<{mult_sym}>",
                            lambda e: self._on_select_all(e, kind="files"))
            self.tree.bind(f"<{sub_sym}>",
                            lambda e: self._on_unmark_all(e, kind="files"))
            self.tree.bind(f"<Shift-{mult_sym}>",
                            lambda e: self._on_select_all(e, kind="dirs"))
            self.tree.bind(f"<Shift-{sub_sym}>",
                            lambda e: self._on_unmark_all(e, kind="dirs"))
            self.tree.bind(f"<Control-{mult_sym}>",
                            lambda e: self._on_select_all(e, kind="all"))
            self.tree.bind(f"<Control-{sub_sym}>",
                            lambda e: self._on_unmark_all(e, kind="all"))
        # Feed the Quick View panel whenever the cursor moves
        self.tree.bind("<<TreeviewSelect>>", self._on_select_changed)

        # Real OS clipboard — paste files copied (or cut) in Explorer or any
        # other program straight into this panel, and copy/cut files out of
        # here so Explorer can paste them.  Only the lower-case "c" is bound:
        # Ctrl+Shift+C is already "Compare files" (DEL 33) and must keep
        # working untouched.  This is separate from SEL ▾ "Copy paths to
        # clipboard", which puts path TEXT on the clipboard, not files.
        self.tree.bind("<Control-c>", self._on_copy_to_os_clipboard)
        self.tree.bind("<Control-x>", self._on_cut_to_os_clipboard)
        self.tree.bind("<Control-X>", self._on_cut_to_os_clipboard)
        self.tree.bind("<Control-v>", self._on_paste_from_os_clipboard)
        self.tree.bind("<Control-V>", self._on_paste_from_os_clipboard)

        self._setup_dnd()
        self.refresh()

    # ── Branch view ───────────────────────────────────────────────────────

    def toggle_branch_view(self, with_dirs: bool = False):
        """Ctrl+B / Ctrl+Shift+B — flatten this folder tree into one list."""
        if self.branch_mode and self.branch_dirs == with_dirs:
            self.branch_mode = False
        else:
            self.branch_mode = True
            self.branch_dirs = with_dirs
        self.refresh()
        return self.branch_mode

    def _on_select_changed(self, event=None):
        # If the cursor just landed on (or left) a marked row, fix up the
        # red/blue tag before anything else reads focus() or selection().
        self._reconcile_marked_cursor()
        # Remember where the cursor stands, by name — see _last_cursor_name.
        try:
            cur = self.tree.focus() or (self.tree.selection()[0]
                                        if self.tree.selection() else "")
            if cur and self.tree.exists(cur):
                nm = self._fullname(cur)
                if nm and nm != "..":
                    self._last_cursor_name = nm
                # The moment the cursor is somewhere OTHER than the pinned row,
                # the pin has done its job (or the user has moved on) — drop
                # it, so a refresh two seconds later never drags him back.
                if nm != self._cursor_pin[0]:
                    self._cursor_pin = ("", 0.0)
        except Exception:
            pass
        qv = getattr(self.manager, "quickview", None)
        if qv is not None and qv.visible and self.manager.active_panel == self.side:
            qv.update_current()
        # Keep the bottom-bar counter ("X of Y selected") in step with the marks
        if self.manager.active_panel == self.side:
            try:
                self.manager._update_counts()
            except Exception:
                pass

    # ── Rendering ─────────────────────────────────────────────────────────

    def _fullname(self, iid: str) -> str:
        """Return the full filename (base+ext) for a tree item, or its text as fallback."""
        return self._iid_to_fullname.get(iid, self.tree.item(iid, "text"))

    def refresh(self):
        if self.archive_ctx is not None:
            self._refresh_archive_view()
            return
        self.manager._ct("REFRESH-in", f"panel={self.side}", depth=2)
        # Preserve the red marks across an IN-PLACE refresh (folder watcher,
        # post-operation refresh, sort, …).  Tree iids change when the list is
        # rebuilt, but file NAMES do not — so remember the marked names and
        # re-apply them below.  (change_directory clears _marked BEFORE calling
        # refresh, so navigating to a new folder still starts unmarked.)
        prev_marked_names = {self._fullname(iid) for iid in self._marked}
        # Remember the keyboard cursor too.  Arrow navigation in a ttk.Treeview
        # moves relative to the "focus" item; if a rebuild leaves it unset the
        # arrows appear dead, and after a move the cursor must land on the row
        # that took the moved file's place — not vanish or jump to the top.
        _prev_children  = self.tree.get_children()
        _prev_focus_iid = self.tree.focus()
        prev_focus_name = self._fullname(_prev_focus_iid) if _prev_focus_iid else ""
        try:
            prev_focus_index = (_prev_children.index(_prev_focus_iid)
                                if _prev_focus_iid else -1)
        except ValueError:
            prev_focus_index = -1
        prev_had_selection = bool(self.tree.selection())
        self._marked.clear()
        self._iid_to_fullname.clear()
        self.tree.delete(*self.tree.get_children())
        try:
            show_hidden = self.manager.settings.get("show_hidden", False)
            show_system = self.manager.settings.get("show_system", False)

            # Total-Commander-style per-type icons (Windows + Pillow only).
            icons     = _icons() if self.manager.settings.get("show_icons", True) else None
            use_icons = bool(icons and icons.available)
            if use_icons:
                # revBR — and MY programs' own icons for the types they own.
                icons.configure(
                    self.manager.settings.get("suite_icons", True),
                    self.manager.settings.get("suite_icons_skip_text", False))
            dir_icon  = icons.folder() if use_icons else None

            if self.current_path != os.path.dirname(self.current_path):
                self.tree.insert("", "end", text="..",
                                 values=("Folder", "", "", "", "", ""),
                                 tags=("dir",), image=(dir_icon or ""))

            if self.branch_mode:
                # Flat view of the whole tree — names become relative paths
                raw = branch_scan(self.current_path,
                                  include_dirs=self.branch_dirs,
                                  show_hidden=show_hidden,
                                  show_system=show_system)
            else:
                raw = os.listdir(self.current_path)

            def _attrs(p):
                """Return Windows file attribute bits (or 0 on error)."""
                try:
                    return ctypes.windll.kernel32.GetFileAttributesW(p)
                except Exception:
                    return 0

            def _attr_str(bits, is_dir):
                """Convert attribute bits to a compact flag string, e.g. 'RHA'."""
                flags = ""
                if bits & 0x01:  flags += "R"   # Read-only
                if bits & 0x02:  flags += "H"   # Hidden
                if bits & 0x04:  flags += "S"   # System
                if bits & 0x20:  flags += "A"   # Archive
                if bits & 0x800: flags += "C"   # Compressed
                if bits & 0x400: flags += "E"   # Encrypted
                return flags if flags else "-"

            filtered = []
            # First drop any soft-delete marks whose file was resurrected by
            # another program, so we never hide a file that really exists.
            try:
                self.manager._reconcile_pending()
            except Exception:
                pass
            _trash_set = {os.path.normcase(p)
                          for p in getattr(self.manager, "_trash", [])}
            _show_trash = self.manager.settings.get("show_trash", False)
            for name in raw:
                fp    = os.path.join(self.current_path, name)
                # Deleted items are renamed to a ~deleted~ name and hidden.
                if not _show_trash and (name.startswith(TRASH_PREFIX)
                                        or os.path.normcase(fp) in _trash_set):
                    continue
                attrs = _attrs(fp)
                is_hidden = (attrs & 2) or name.startswith(".")
                is_system = (attrs & 4) != 0
                if not show_hidden and is_hidden:
                    continue
                if not show_system and is_system:
                    continue
                filtered.append((name, attrs))

            # ── Apply name/extension filter ───────────────────────────────
            _flt = getattr(self.manager, "_filter_var", None)
            _flt = _flt.get().strip() if _flt else ""
            if _flt:
                _flt_lo = _flt.lower()
                if _flt_lo in ("*", "-*", "flag:", "flag:-"):
                    # *  → only the ★ rows.
                    # -* → only the ones still WITHOUT a ★, i.e. what is left
                    #      to deal with.  Folders are filtered here too: when
                    #      you ask "what is still open?" you do not want every
                    #      sub-folder in the way.
                    want  = _flt_lo in ("*", "flag:")
                    store = getattr(self.manager, "tagstore", None)

                    def _is_flagged(name):
                        if store is None:
                            return not want
                        try:
                            hit = store.is_flagged(
                                os.path.join(self.current_path, name))
                        except Exception:
                            hit = False
                        return hit is want

                    filtered = [(n, a) for n, a in filtered if _is_flagged(n)]
                elif _flt_lo.startswith("tag:"):
                    # tag:Work  → only items carrying that label.
                    # Folders are filtered too here: when you ask for a tag you
                    # want the tagged things, not every folder in the way.
                    wanted = _flt[4:].strip().lower()
                    store = getattr(self.manager, "tagstore", None)

                    def _tagged(name):
                        if store is None:
                            return False
                        names = [t.lower() for t in
                                 store.get(os.path.join(self.current_path, name))]
                        if not names:
                            return False
                        return (not wanted) or any(wanted in t for t in names)

                    filtered = [(n, a) for n, a in filtered if _tagged(n)]
                else:
                    def _matches(name):
                        n_lo = name.lower()
                        if _flt_lo.startswith("."):
                            # Extension match: .py → only files whose ext == .py
                            return os.path.splitext(n_lo)[1] == _flt_lo
                        else:
                            return _flt_lo in n_lo
                    # Always keep ".." — dirs stay visible so you can navigate
                    filtered = [(n, a) for n, a in filtered
                                if os.path.isdir(os.path.join(self.current_path, n))
                                or _matches(n)]

            dirs  = sorted(
                [(n, a) for n, a in filtered if os.path.isdir( os.path.join(self.current_path, n))],
                key=lambda x: x[0].lower()
            )
            files = sorted(
                [(n, a) for n, a in filtered if os.path.isfile(os.path.join(self.current_path, n))],
                key=lambda x: x[0].lower()
            )

            # Remember how many are on show, for the status-bar counter
            self._n_dirs  = len(dirs)
            self._n_files = len(files)

            tagstore = getattr(self.manager, "tagstore", None)
            mark_empty = self.manager.settings.get("mark_empty_dirs", True)

            def _tag_info(path):
                """(text for the Tags column, treeview tag name for its colour)"""
                if tagstore is None:
                    return "", None
                names = tagstore.get(path)
                if not names:
                    return "", None
                colour = tagstore.colour_of(names[0])
                tag_name = f"tagcol_{colour.lstrip('#')}"
                if tag_name not in self._tag_colours:
                    self.tree.tag_configure(tag_name, foreground=colour)
                    self._tag_colours.add(tag_name)
                return "● " + " ".join(names), tag_name

            def _ext_colour_tag(ext_lo: str):
                """Treeview tag for this extension's colour, or None.

                Configured lazily, the same way the colour labels are — one tag
                per colour, not one per file."""
                colours = getattr(self.manager, "ext_colours", None)
                if not colours:
                    return None
                colour = colours.get(ext_lo.lstrip(".").lower())
                if not colour:
                    return None
                tag_name = f"extcol_{colour.lstrip('#')}"
                if tag_name not in self._tag_colours:
                    try:
                        self.tree.tag_configure(tag_name, foreground=colour)
                    except Exception:
                        return None
                    self._tag_colours.add(tag_name)
                return tag_name

            def _flag_char(path):
                """★ when this item carries the hand-set flag, else nothing."""
                if tagstore is None:
                    return ""
                try:
                    return FLAG_CHAR if tagstore.is_flagged(path) else ""
                except Exception:
                    return ""

            for name, attr_bits in dirs:
                attr_s = _attr_str(attr_bits, is_dir=True)
                fp = os.path.join(self.current_path, name)
                tag_text, tag_colour = _tag_info(fp)
                # Folders carry their modified date too, so the Modified column
                # can actually sort them — Total Commander leaves folders in
                # alphabetical order no matter which column you click.
                try:
                    dmtime = datetime.fromtimestamp(
                        os.path.getmtime(fp)).strftime("%Y-%m-%d %H:%M")
                except OSError:
                    dmtime = ""
                # A tag colour replaces the plain "dir" blue, so it is visible;
                # otherwise a completely-empty folder gets the dim "dir_empty"
                # tint and every other folder the normal "dir" blue.
                if tag_colour:
                    row_tags = (tag_colour,)
                elif mark_empty and _dir_is_empty(fp):
                    row_tags = ("dir_empty",)
                else:
                    row_tags = ("dir",)
                iid = self.tree.insert("", "end", text=name,
                                       values=("Folder", _flag_char(fp), "",
                                               dmtime, attr_s, tag_text),
                                       tags=row_tags, image=(dir_icon or ""))
                self._iid_to_fullname[iid] = name

            for name, attr_bits in files:
                fp = os.path.join(self.current_path, name)
                try:
                    size   = os.path.getsize(fp)
                    mtime  = datetime.fromtimestamp(os.path.getmtime(fp)).strftime("%Y-%m-%d %H:%M")
                    base, ext = os.path.splitext(name)
                    ext_lo = ext.lower()
                    attr_s = _attr_str(attr_bits, is_dir=False)
                    tag_text, tag_colour = _tag_info(fp)
                    file_icon = icons.for_file(name) if use_icons else None
                    # Size column, in KB.  Optional space grouping (default on):
                    # 9133144 → "9 133 144 KB".  Toggle in Settings.
                    _kb = size // 1024
                    if size <= 0:
                        size_txt = "0 KB"
                    elif self.manager.settings.get("size_group_digits", True):
                        size_txt = f"{_group_digits(_kb)} KB"
                    else:
                        size_txt = f"{_kb} KB"
                    # A colour LABEL (Ctrl+G) is a deliberate mark on this one
                    # file, so it wins; the extension colour is the fallback.
                    row_colour = tag_colour or _ext_colour_tag(ext_lo)
                    iid = self.tree.insert(
                        "", "end", text=base,
                        values=(ext_lo.lstrip("."), _flag_char(fp), size_txt,
                                mtime, attr_s, tag_text),
                        tags=(row_colour,) if row_colour else (),
                        image=(file_icon or ""),
                    )
                    self._iid_to_fullname[iid] = name
                except Exception:
                    continue

        except Exception as exc:
            gone = self.current_path
            try:
                still_there = os.path.isdir(gone)
            except Exception:
                still_there = False

            if still_there:
                # It is THERE, it just cannot be read — no rights, a disk
                # error, a folder Windows is holding.  That is not a deleted
                # folder and must not move the tab anywhere.  And it must not
                # be a message box either: the auto-refresh poll comes back
                # every 1.5 seconds and would put one on the screen every 1.5
                # seconds (revBU).
                _log(f"Could not read {gone!r}: {exc}")
                try:
                    why = (_friendly_oserror(exc) if isinstance(exc, OSError)
                           else str(exc))
                    self.manager._flash_status(
                        f"Could not read this folder — {why}", 8000)
                except Exception:
                    pass
                return

            # The folder has GONE — deleted from another tab, another profile
            # or another program.  Walk UP to the nearest folder that still
            # exists, one level at a time; never across the disk to the user
            # folder (revBU).
            up = _nearest_existing_dir(gone)
            if up and os.path.normcase(up) != os.path.normcase(
                    os.path.abspath(gone)):
                _log(f"{gone!r} is gone ({exc}) — this tab goes up to {up!r}")
                self.current_path = os.path.abspath(up)
                self.refresh()          # one silent retry, one level up
                try:
                    self.manager._folder_vanished(gone, self.current_path)
                except Exception as exc2:
                    _log(f"Tab rescue after {gone!r}: {exc2}")
            else:
                messagebox.showerror("Error", f"Could not read directory: {exc}")
            return

        # The Tags column costs horizontal room the other columns need, so it
        # only claims space when something in this folder is actually tagged.
        try:
            any_tagged = any(self.tree.set(iid, "tags")
                             for iid in self.tree.get_children())
            self.tree.column("tags", width=self._tags_col_width if any_tagged else 0,
                             minwidth=0, stretch=False)
        except Exception:
            pass

        # Re-apply the user's chosen sort order after every refresh
        self._reapply_sort()

        # Re-apply the red marks that survived this refresh (see the top of the
        # method).  Matched by file name, so multi-select is not silently lost
        # when the folder auto-refreshes — which used to make a drag carry only
        # the single cursor row instead of everything marked.
        if prev_marked_names:
            is_active_panel = (self.manager.active_panel == self.side)
            for iid in self.tree.get_children():
                nm = self._fullname(iid)
                if nm != ".." and nm in prev_marked_names:
                    self._marked.add(iid)
                    self._set_mark_tag(iid, active=is_active_panel)

        # ── Restore the keyboard cursor (see the top of this method) ──────────
        # Put the cursor back on the same file; if it is gone (moved/deleted),
        # put it on the row that now occupies that position so the arrow keys
        # keep working from a sensible spot instead of going dead.
        try:
            kids = self.tree.get_children()
            target = None
            # A cursor PIN beats everything: _promote_panel writes one every
            # time Tab (or a click) lands in this panel, and it stays valid for
            # a couple of seconds.  Without it the auto-refresh poll — which
            # fires every 1.5 s and rebuilds the whole list — could land in the
            # gap between the Tab and the Enter and move the cursor off the row
            # that had just gone blue.  That is how Enter ended up opening a
            # file a little below the ".." you were looking at.  (revAO)
            _how = "?"
            pin_name, pin_when = getattr(self, "_cursor_pin", ("", 0.0))
            if pin_name and (_time.time() - pin_when) <= 2.0:
                for iid in kids:
                    if self._fullname(iid) == pin_name:
                        target = iid
                        _how = "pin"
                        break
            # ".." is a real answer, not a missing one: a cursor deliberately
            # parked on the parent dots must survive a rebuild instead of
            # sliding down to the first file.
            if target is None and prev_focus_name == ".." and kids:
                for iid in kids:
                    if self.tree.item(iid, "text") == "..":
                        target = iid
                        _how = "dotdot"
                        break
            if target is None and prev_focus_name and prev_focus_name != "..":
                for iid in kids:
                    if self._fullname(iid) == prev_focus_name:
                        target = iid
                        _how = "same-name"
                        break
            if target is None and prev_focus_index >= 0 and kids:
                target = kids[min(prev_focus_index, len(kids) - 1)]
                _how = "same-position"
            if target is None:
                # Nothing to restore — make sure the cursor is at least on a
                # real row rather than the ".." dots, so the next Enter opens
                # something instead of climbing a level.
                target = self.manager._panel_default_cursor(self)
                _how = "DEFAULT-CURSOR"
            if target is not None:
                self.manager._ct(
                    "REFRESH-target",
                    f"panel={self.side} chose={self._fullname(target)!r} via={_how} "
                    f"(prev focus={prev_focus_name!r} idx={prev_focus_index} "
                    f"had-sel={prev_had_selection})")
                self.tree.focus(target)
                self.tree.see(target)
                # Re-highlight the row only when a single-row selection was
                # cleared by the rebuild (e.g. the selected file was just moved
                # away) — never invent a selection that wasn't there before.
                # The ACTIVE panel is the exception: its cursor is the thing
                # Enter acts on, so it must always be visibly on a row rather
                # than a bare focus rectangle nobody can see (revAO).
                if (not self.tree.selection() and not self._marked
                        and (prev_had_selection
                             or self.manager.active_panel == self.side)):
                    self.tree.selection_set(target)
                # The INACTIVE panel has no real selection (it was demoted to
                # the grey 'inactive_sel' tag), and a rebuild throws that tag
                # away.  One helper owns that state — see
                # _sync_inactive_cursor — so the grey row after a rebuild is
                # always the row Tab will turn blue.
                if self.manager.active_panel != self.side:
                    self.manager._sync_inactive_cursor(self)
        except Exception:
            pass

        self.manager._ct("REFRESH-out", f"panel={self.side}", depth=2)

        # Refresh the status bar: this side's own section (path / counts / free)
        # always, and the middle active-panel counter when this is the active one.
        try:
            self.manager._update_disk_info()
            if self.manager.active_panel == self.side:
                self.manager._update_counts()
        except Exception:
            pass

        # ⚖ Re-run the newest/oldest comparison against the other panel.  It is
        # coalesced onto one idle callback, so a burst of refreshes (both panels
        # after a copy) still only compares once.
        try:
            self.manager.schedule_side_comparison()
        except Exception:
            pass

        # "Folders show a SIZE too" (Settings → Display, off by default).  The
        # per-press Alt+Shift+Enter becomes a MODE: every listing measures its
        # own folders.
        #
        # The numbers already measured are written back FIRST, straight from
        # the cache — the auto-refresh watcher rebuilds this list every 1.5 s,
        # and without the cache every rebuild would blank the Size column and
        # then fill it in again: a column that flickers between empty and a
        # number for as long as you stand there.  Only the folders that have no
        # number yet are actually walked, and that walk is started on an idle
        # callback so the LIST is on screen first.
        try:
            if (self.manager.settings.get("auto_folder_sizes", False)
                    and not getattr(self, "is_remote", False)
                    and getattr(self, "archive_ctx", None) is None):
                self._apply_cached_folder_sizes()
                self.after_idle(lambda: self.calc_folder_sizes(only_missing=True))
        except Exception:
            pass

    # ── Column sorting ────────────────────────────────────────────────────

    # Map the Treeview column id from an event ("#0", "#1", …) to our name.
    # "#0" is the tree/Name column; "#1"… follow the columns= order.
    _COL_ORDER = ("type", "flag", "size", "modified", "attributes", "tags")

    def _colid_to_name(self, col_id: str) -> str:
        if col_id == "#0":
            return "#0"
        try:
            n = int(col_id.lstrip("#"))
        except ValueError:
            return ""
        if 1 <= n <= len(self._COL_ORDER):
            return self._COL_ORDER[n - 1]
        return ""

    @staticmethod
    def _sort_value(get_set, get_text, iid, col):
        """Sort key for one row on one column.  *get_set*/*get_text* are the
        tree.set / tree.item('text') callables, passed in so the same logic
        serves both the file and folder passes."""
        if col == "#0":
            return get_text(iid).lower()
        elif col == "type":
            return get_set(iid, "type").lower()
        elif col == "size":
            # Strip the "KB" unit and any grouping (spaces or commas) so the
            # displayed "9 133 144 KB" still sorts as the number 9133144.
            raw = (get_set(iid, "size")
                   .replace("KB", "").replace(",", "").replace(" ", "").strip())
            try:
                return int(raw)
            except ValueError:
                return -1
        elif col == "modified":
            return get_set(iid, "modified")
        elif col == "flag":
            # Flagged rows sort FIRST ascending — clicking ★ once brings
            # everything you have ticked to the top, which is the whole point.
            return "0" if get_set(iid, "flag") else "1"
        elif col == "attributes":
            return get_set(iid, "attributes").lower()
        elif col == "tags":
            v = get_set(iid, "tags").lstrip("● ").lower()
            return v if v else "￿"
        return ""

    def _reapply_sort(self):
        """Re-order the tree using the independent file / folder sort state.

        Left-click a header sets the FILE order (filled ▲/▼); right-click sets
        the FOLDER order (hollow ▵/▿).  Both arrows can appear on one header
        when files and folders happen to share a column.
        """
        _col_labels = {
            "#0":         ("Name",     "w"),
            "type":       ("Type",     "w"),
            "flag":       (FLAG_CHAR,  "center"),
            "size":       ("Size",     "e"),
            "modified":   ("Modified", "w"),
            "attributes": ("Attr",     "w"),
            "tags":       ("Tags",     "w"),
        }
        f_col, f_rev, d_col, d_rev, overridden = self._effective_sort()
        for c, (label, anchor) in _col_labels.items():
            suffix = ""
            if c == f_col:                       # filled arrow = FILE order
                suffix += " ▼" if f_rev else " ▲"
                if overridden:
                    # This folder has a sort of its OWN (DEL 45) — say so, or the
                    # list looks like it ignored the header you clicked.
                    suffix += " 🔀"
            if c == d_col:                       # hollow arrow = FOLDER order
                suffix += " ▿" if d_rev else " ▵"
            self.tree.heading(c, text=label + suffix, anchor=anchor)

        all_items = self.tree.get_children()
        dotdot    = [i for i in all_items if self.tree.item(i, "text") == ".."]
        rest      = [i for i in all_items if self.tree.item(i, "text") != ".."]

        _get_text = lambda x: self.tree.item(x, "text")

        def _keyf(iid):
            return self._sort_value(self.tree.set, _get_text, iid, f_col)

        def _keyd(iid):
            return self._sort_value(self.tree.set, _get_text, iid, d_col)

        def _is_dir(iid):
            return self.tree.set(iid, "type") == "Folder"

        # "Folders first" (default) keeps folders grouped above files, each
        # group sorted by its own column.  Turn it off to mix folders and files
        # into one list — that list follows the FILE order.
        folders_first = self.manager.settings.get("sort_folders_first", True)

        # "Folders sort like files" (Workspace bar, default off): the folders
        # drop their own order and follow the FILE column instead — still above
        # the files.  Sorting them by Size only means something once the sizes
        # have been measured (Alt+Shift+Enter); until then every folder's cell
        # is empty and _sort_value gives them all the same key.
        dirs_follow = self.manager.settings.get("folders_follow_file_sort", False)

        if folders_first:
            dirs_part  = [i for i in rest if _is_dir(i)]
            files_part = [i for i in rest if not _is_dir(i)]
            if dirs_follow:
                dirs_part.sort(key=_keyf, reverse=f_rev)
            else:
                dirs_part.sort(key=_keyd, reverse=d_rev)
            files_part.sort(key=_keyf, reverse=f_rev)
            rest = dirs_part + files_part
        else:
            rest.sort(key=_keyf, reverse=f_rev)

        for idx, iid in enumerate(dotdot + rest):
            self.tree.move(iid, "", idx)

        # Keep the cursor visible: after re-sorting, the selected row has moved
        # to a new position, so scroll it back into view instead of leaving the
        # window where it was.
        try:
            foc = self.tree.focus()
            if not foc:
                sel = self.tree.selection()
                foc = sel[0] if sel else None
            if foc:
                self.tree.see(foc)
        except Exception:
            pass

    # ── Folder sizes  (Alt+Shift+Enter — Total Commander parity) ────────
    #
    # A folder row is inserted with an EMPTY size cell, and _sort_value()
    # gives anything non-numeric the key -1 — so every folder tied and
    # "sort folders by size" (the hollow ▵ arrow) did nothing at all.  Put a
    # real number in the cell and that sort starts working by itself; no
    # change to the sorting code is needed.
    #
    # JUNCTIONS ARE NOT FOLLOWED.  Every build folder carries a Helpfiles
    # junction pointing at the real tree, so walking through one would add
    # the whole of Helpfiles (thousands of files, gigabytes) to that one
    # folder's size — and take minutes doing it.  os.path.islink() is False
    # for a junction on Windows, so the ATTRIBUTE is what has to be tested.

    @staticmethod
    def _is_reparse(path) -> bool:
        try:
            return bool(os.stat(path, follow_symlinks=False).st_file_attributes
                        & 0x400)                      # FILE_ATTRIBUTE_REPARSE_POINT
        except (OSError, AttributeError, ValueError):
            return False

    @classmethod
    def _tree_size(cls, root, stop) -> int:
        total = 0
        for dirpath, dirnames, filenames in os.walk(root):
            if stop.is_set():
                break
            dirnames[:] = [d for d in dirnames
                           if not cls._is_reparse(os.path.join(dirpath, d))]
            for fn in filenames:
                fp = os.path.join(dirpath, fn)
                try:
                    if not cls._is_reparse(fp):
                        total += os.path.getsize(fp)
                except OSError:
                    pass
        return total

    def _folder_size_text(self, n: int) -> str:
        """The Size cell for a measured folder, in the same KB form the file
        rows use, so the column still sorts as one set of numbers."""
        kb = n // 1024
        return (f"{_group_digits(kb)} KB"
                if self.manager.settings.get("size_group_digits", True)
                else f"{kb} KB")

    def _apply_cached_folder_sizes(self):
        """Write back the folder sizes already measured for THIS folder.

        Runs after every rebuild of the list.  Without it the auto mode would
        blank the Size column on each auto-refresh and measure it all again —
        a column flickering between empty and a number while you stand still.
        """
        cache = getattr(self, "_fsize_cache", None)
        if not cache:
            return
        base = self.current_path
        for iid in self.tree.get_children():
            try:
                if self.tree.set(iid, "type") != "Folder":
                    continue
                name = self._fullname(iid)
                if name == "..":
                    continue
                n = cache.get(os.path.normcase(os.path.join(base, name)))
                if n is not None and not self.tree.set(iid, "size"):
                    self.tree.set(iid, "size", self._folder_size_text(n))
            except Exception:
                pass

    def calc_folder_sizes(self, only_missing: bool = False):
        """Fill the Size column for every folder here.  Press again to stop.

        *only_missing* is the automatic pass ("Folders show a SIZE too"): it
        measures just the folders whose cell is still empty, and it must NEVER
        cancel a measurement already running — a second PRESS means stop, an
        automatic pass does not.
        """
        old = getattr(self, "_fsize_thread", None)
        if old is not None and old.is_alive():
            if only_missing:
                return
            self._fsize_stop.set()                    # a second press cancels
            return
        if getattr(self, "is_remote", False) or getattr(self, "archive_ctx", None):
            return
        rows, base = [], self.current_path
        for iid in self.tree.get_children():
            try:
                if (self.tree.set(iid, "type") == "Folder"
                        and self._fullname(iid) != ".."):
                    if only_missing and self.tree.set(iid, "size"):
                        continue
                    rows.append((iid, self._fullname(iid)))
            except Exception:
                pass
        if not rows:
            return
        self._fsize_done = []
        self._fsize_stop = threading.Event()
        stop, done = self._fsize_stop, self._fsize_done
        # A manual press means "measure it again NOW", so it throws the old
        # numbers away; the automatic pass keeps what it already has.
        if not only_missing:
            self._fsize_cache = {}
        elif getattr(self, "_fsize_cache", None) is None:
            self._fsize_cache = {}
        cache = self._fsize_cache

        def work():
            for iid, name in rows:
                if stop.is_set():
                    break
                full = os.path.join(base, name)
                try:
                    n = self._tree_size(full, stop)
                except Exception:
                    n = -1
                if n >= 0 and not stop.is_set():
                    # Keyed by the FULL path, so the numbers survive the
                    # rebuild that the auto-refresh watcher does every 1.5 s.
                    if len(cache) > 5000:
                        cache.clear()
                    cache[os.path.normcase(full)] = n
                done.append((iid, n))

        self._fsize_thread = threading.Thread(target=work, daemon=True)
        self._fsize_thread.start()
        self._drain_folder_sizes(len(rows))

    def _drain_folder_sizes(self, total: int):
        """MAIN thread: pick up whatever the worker has finished so far.

        after() is started from HERE and never from the worker: a worker's
        after() only fires while mainloop happens to be running, which is how
        the last update goes missing."""
        done = getattr(self, "_fsize_done", None)
        if done is None:
            return
        while done:
            iid, n = done.pop(0)
            try:
                if not self.tree.exists(iid):
                    continue
                self.tree.set(iid, "size",
                              "?" if n < 0 else self._folder_size_text(n))
            except Exception:
                pass
        alive = getattr(self, "_fsize_thread", None)
        if alive is not None and alive.is_alive():
            try:
                self.manager._counts_lbl.config(
                    text="⏳ measuring folders…  (Alt+Shift+Enter again to stop)")
            except Exception:
                pass
            self.after(120, lambda: self._drain_folder_sizes(total))
        else:
            try:
                self.manager._update_counts()
            except Exception:
                pass

    def _effective_sort(self):
        """The sort this panel should ACTUALLY use right now.

        Normally the panel's own state, but a folder can carry a sort of its own
        (DEL 45) which wins while you stand in it — that is the whole point of
        the override.  Returns (f_col, f_rev, d_col, d_rev, is_override)."""
        ovr = None
        try:
            if not getattr(self, "is_remote", False) and not self.branch_mode:
                ovr = self.manager.folder_sort_for(self.current_path)
        except Exception:
            ovr = None
        if ovr:
            s = ovr[0]
            if isinstance(s, (list, tuple)) and len(s) >= 4:
                return (s[0] or "#0", bool(s[1]), s[2] or "#0", bool(s[3]), True)
        return (self._sort_files_col, self._sort_files_rev,
                self._sort_dirs_col,  self._sort_dirs_rev, False)

    # Columns whose FIRST click should sort DESCENDING (newest / largest first),
    # which is what people expect from a date or size column.
    _DESC_FIRST_COLS = ("modified", "size")

    def _initial_rev_for(self, col: str) -> bool:
        return col in self._DESC_FIRST_COLS

    def _folder_override_active(self):
        """The override rule in force here, or None (DEL 45)."""
        try:
            if getattr(self, "is_remote", False) or self.branch_mode:
                return None
            return self.manager.folder_sort_for(self.current_path)
        except Exception:
            return None

    def _sort_files_by(self, col):
        """Left-click a header — sort FILES by *col*; toggle on repeat click.

        In a folder that has a sort override, the click edits THAT override
        instead of the window's sort — otherwise clicking a header here would
        look like it did nothing, because the override wins on redraw."""
        ovr = self._folder_override_active()
        if ovr:
            s = list(ovr[0])
            s[1] = (not bool(s[1])) if s[0] == col else self._initial_rev_for(col)
            s[0] = col
            self.manager.set_folder_sort(self.current_path, s, quiet=True)
            return
        if self._sort_files_col == col:
            self._sort_files_rev = not self._sort_files_rev
        else:
            self._sort_files_col = col
            self._sort_files_rev = self._initial_rev_for(col)   # date/size → newest first
        self._reapply_sort()
        self.manager._on_panel_sort_changed(self.side)

    def _sort_dirs_by(self, col):
        """Right-click a header — sort FOLDERS by *col*; toggle on repeat click."""
        ovr = self._folder_override_active()
        if ovr:
            s = list(ovr[0])
            s[3] = (not bool(s[3])) if s[2] == col else self._initial_rev_for(col)
            s[2] = col
            self.manager.set_folder_sort(self.current_path, s, quiet=True)
            return
        if self._sort_dirs_col == col:
            self._sort_dirs_rev = not self._sort_dirs_rev
        else:
            self._sort_dirs_col = col
            self._sort_dirs_rev = self._initial_rev_for(col)
        self._reapply_sort()
        self.manager._on_panel_sort_changed(self.side)

    # ── Sort state get / set (used by per-tab memory) ─────────────────────
    def get_sort_state(self):
        """Return [f_col, f_rev, d_col, d_rev] — the full sort snapshot."""
        return [self._sort_files_col, self._sort_files_rev,
                self._sort_dirs_col,  self._sort_dirs_rev]

    def set_sort_state(self, state):
        """Apply a sort snapshot (or the configured default when *state* is None)."""
        if not state or len(state) < 4:
            df = self.manager.settings.get("default_sort_files", ["modified", True])
            dd = self.manager.settings.get("default_sort_dirs",  ["#0", False])
            state = [df[0] or "modified", bool(df[1]),
                     dd[0] or "#0",       bool(dd[1])]
        self._sort_files_col = state[0]
        self._sort_files_rev = bool(state[1])
        self._sort_dirs_col  = state[2]
        self._sort_dirs_rev  = bool(state[3])
        self._reapply_sort()

    # ── Subfolder navigation (Shift/Ctrl+Enter on a folder) ───────────────

    def _subdirs_sorted(self, path: str) -> list:
        """Immediate sub-folders of *path* as FULL paths, ordered exactly the way
        this panel sorts folders (so "the topmost one" means the same here as in
        the list).  Honours the show-hidden / show-system settings and skips
        ~deleted~ trash."""
        show_hidden = self.manager.settings.get("show_hidden", False)
        show_system = self.manager.settings.get("show_system", False)
        names = []
        try:
            for name in os.listdir(path):
                if name.startswith(TRASH_PREFIX):
                    continue
                full = os.path.join(path, name)
                try:
                    if not os.path.isdir(full):
                        continue
                except OSError:
                    continue
                attrs = 0
                try:
                    attrs = ctypes.windll.kernel32.GetFileAttributesW(full)
                except Exception:
                    pass
                is_hidden = (attrs & 2) or name.startswith(".")
                is_system = (attrs & 4) != 0
                if not show_hidden and is_hidden:
                    continue
                if not show_system and is_system:
                    continue
                names.append(name)
        except OSError:
            return []

        _f_c, _f_r, col, rev, _ovr = self._effective_sort()

        def _key(n):
            if col == "modified":
                try:
                    return os.path.getmtime(os.path.join(path, n))
                except OSError:
                    return 0.0
            return n.lower()

        names.sort(key=_key, reverse=rev)
        return [os.path.join(path, n) for n in names]

    def dive_to_deepest(self, start_dir: str):
        """Shift+Enter on a folder: keep entering the FIRST sub-folder at each
        level (following this panel's folder sort) until a folder has no more
        sub-folders, then open that deepest folder."""
        current = start_dir
        for _ in range(400):            # guard against symlink loops / silliness
            subs = self._subdirs_sorted(current)
            if not subs:
                break
            nxt = subs[0]
            if os.path.normcase(os.path.abspath(nxt)) == \
               os.path.normcase(os.path.abspath(current)):
                break
            current = nxt
        self.change_directory(current)
        try:
            self.manager._flash_status(f"↳  dived to:  {current}")
        except Exception:
            pass

    # ── Mark helpers ──────────────────────────────────────────────────────

    def _set_mark_tag(self, item, *, active: bool, cursor: bool = False):
        """Apply the correct mark tag to an already-marked item.

        cursor=True only makes sense when active=True: it means the keyboard
        cursor is sitting on this row right now, so it gets 'marked_cursor'
        (its own third colour) instead of plain 'marked'.
        See _reconcile_marked_cursor()."""
        if active:
            tag = "marked_cursor" if cursor else "marked"
        else:
            tag = "marked_inactive"
        # A rebuild throws every iid away, so a mark can outlive its row —
        # painting one then raises TclError "Item I13CE not found" and takes
        # the whole Tk callback with it.  Both tag helpers are the choke point
        # every caller goes through, so the guard belongs HERE rather than in
        # each of them.  (That crash was real: copying out of a zip, where an
        # in-place refresh rebuilt the list behind a still-marked selection.)
        if not self.tree.exists(item):
            return
        tags = [t for t in self.tree.item(item, "tags")
                if t not in ("marked", "marked_inactive", "marked_cursor")]
        tags.append(tag)
        self.tree.item(item, tags=tags)

    def _clear_mark_tag(self, item):
        """Remove all mark tags from an item (no-op if the row is gone)."""
        if not self.tree.exists(item):
            return
        tags = [t for t in self.tree.item(item, "tags")
                if t not in ("marked", "marked_inactive", "marked_cursor")]
        self.tree.item(item, tags=tags)

    def _reconcile_marked_cursor(self):
        """Make sure a marked row stays visibly red even when the keyboard
        cursor is on it, by keeping such rows OUT of ttk's native selection
        (whose blue would otherwise paint over the whole row, tag or no tag)
        and giving them the 'marked_cursor' look instead. Focus alone keeps
        keyboard navigation, Enter, etc. working on that row as normal."""
        if self._reconciling_marks or not self._marked:
            return
        if self.manager.active_panel != self.side:
            return
        self._reconciling_marks = True
        try:
            sel = self.tree.selection()
            overlap = [i for i in sel if i in self._marked and self.tree.exists(i)]
            if overlap:
                self.tree.selection_remove(*overlap)
            cursor_set = set(overlap)
            foc = self.tree.focus()
            if foc and foc in self._marked and self.tree.exists(foc):
                cursor_set.add(foc)
            for iid in self._marked:
                if not self.tree.exists(iid):
                    continue
                want = iid in cursor_set
                have = "marked_cursor" in self.tree.item(iid, "tags")
                if want != have:
                    self._set_mark_tag(iid, active=True, cursor=want)
        finally:
            self._reconciling_marks = False

    def _toggle_mark(self, item):
        """Toggle item in _marked; update tag. Active panel assumed."""
        if item in self._marked:
            self._marked.discard(item)
            self._clear_mark_tag(item)
        else:
            self._marked.add(item)
            self._set_mark_tag(item, active=True)
        self._reconcile_marked_cursor()

    def _add_mark(self, item):
        """Add item to _marked (no-op if already there); update tag."""
        if item not in self._marked:
            self._marked.add(item)
            self._set_mark_tag(item, active=True)
        self._reconcile_marked_cursor()

    # ── Mouse / keyboard events ───────────────────────────────────────────

    def _on_extra_click(self, event):
        """Swallow the 3rd / 4th press of one fast click train  (revBQ).

        Tk falls back to the <Double-1> binding when there is no <Triple-1> /
        <Quadruple-1> one, so an impatient burst of clicks fired open / go-up /
        open / go-up — once per press.  Binding them here (and returning
        "break", which stops ttk's own class binding too) makes one burst of
        clicks on one row ONE activation instead of four.
        """
        if self._rename_after:
            self.after_cancel(self._rename_after)
            self._rename_after = None
        return "break"

    def _on_double_click(self, event):
        # Cancel any pending slow-click rename
        if self._rename_after:
            self.after_cancel(self._rename_after)
            self._rename_after = None

        # WHICH row was activated?  For a MOUSE double-click that is the row
        # UNDER THE POINTER — never tree.selection().  (revBQ)
        #
        # ttk selects the row you are pointing at on the FIRST press of a click
        # train only: the second press arrives as <Double-ButtonPress-1> and
        # ttk::treeview::DoubleClick does not touch the selection at all.  So
        # whenever something moved the selection after that first press, this
        # handler opened a different row than the one the mouse was on — and
        # go_up() moves it EVERY time, by design: it puts the cursor back on
        # the folder you just came out of.
        #
        # That is the "..-bouncing":  double-click ".." → up one level, cursor
        # lands on the folder you left → the next press (the 3rd/4th of the
        # same burst, or a second double-click arriving while the panel was
        # still busy listing) read THAT selection and walked straight back INTO
        # it.  In and out, twice a second, with ".." sitting highlighted under
        # the pointer the whole time.  Straight out of the cursor log:
        #     19:39:04.295 CHDIR [go_up]            -> …\Foul_bridge
        #     19:39:04.648 CHDIR [_on_double_click] -> …\Foul_bridge\csv
        #     19:39:04.840 CHDIR [go_up]            -> …\Foul_bridge
        #     19:39:05.264 CHDIR [_on_double_click] -> …\Foul_bridge\csv   …
        # — one single CLICK-pin at the top of that run and no click after it.
        item = None
        if str(getattr(event, "type", "")) in ("4", "ButtonPress"):
            try:
                region = self.tree.identify_region(event.x, event.y)
            except Exception:
                region = "cell"
            if region not in ("tree", "cell"):
                # A column heading, a separator, or empty space below the last
                # row: nothing was aimed at, so nothing is opened.  This used
                # to activate whatever happened to be selected.
                return "break"
            item = self.tree.identify_row(event.y)
            if not item:
                return "break"
            # What you SEE is what gets opened: pull the highlight and the
            # keyboard cursor onto the clicked row before acting on it, and pin
            # it so the 1.5 s auto-refresh cannot slide it off mid-flight.
            try:
                if item not in self.tree.selection():
                    self.tree.selection_set(item)
                self.tree.focus(item)
                self._cursor_pin = (self._fullname(item), _time.time())
            except Exception:
                pass
        else:
            # Keyboard activation (Enter): the selection IS the aim.
            sel  = self.tree.selection()
            item = sel[0] if sel else (self.tree.focus() or None)
        if not item or not self.tree.exists(item):
            return
        text       = self.tree.item(item, "text")
        shift_held = bool(event.state & 0x1)
        ctrl_held  = bool(event.state & 0x4)
        if self.archive_ctx is not None:
            self.archive_activate(self._fullname(item), shift_held, ctrl_held)
        elif text == "..":
            self.go_up()
        else:
            full = os.path.join(self.current_path, self._fullname(item))
            if os.path.isdir(full):
                self.change_directory(full)
            elif not shift_held and not ctrl_held and is_archive(full):
                # Plain double-click on an archive: browse INTO it like a
                # folder, instead of popping up the read-only Archive viewer.
                self.enter_archive(full)
            else:
                # A file: plain = Windows default, Shift = built-in viewer,
                # Ctrl = per-type opener (else built-in).  See _open_file_activated.
                self.manager._open_file_activated(full, shift_held, ctrl_held)

    def _on_single_click(self, event):
        """Slow double-click (click on already-selected item) → rename after delay."""
        # Snapshot the selection NOW, before ttk.Treeview's own ButtonPress
        # handler collapses a multi-row selection to the single clicked row.
        # A drag that begins on this press can then restore the full set.
        self._drag_sel_snapshot = self.tree.selection()

        # Cancel any earlier pending rename
        if self._rename_after:
            self.after_cancel(self._rename_after)
            self._rename_after = None

        item = self.tree.identify_row(event.y)
        if not item:
            return

        # PIN the clicked row.  When the program was in the background, the
        # click both activates the window and hits the list, and the resulting
        # <FocusIn> can land AFTER ttk has already selected the row — the
        # activation logic would then restore its own idea of the cursor and
        # you ended up on the ".." dots instead of the file you clicked.
        # Re-asserting the clicked row on the next idle cycle always wins.
        # Ctrl/Shift clicks are extending or toggling a selection on purpose —
        # leave those completely alone, only plain clicks are pinned.
        plain_click = not (event.state & 0x0005)
        # revCE — was this panel the active one BEFORE this press?  The click
        # that merely activates a panel must never count towards a rename.
        was_active = (self.manager.active_panel == self.side)

        # revCD — tell the panel-activation code which row was clicked BEFORE
        # the <FocusIn> that follows can restore the old grey keyboard row, and
        # activate this panel right now when it is the inactive one.
        if plain_click:
            try:
                self._click_target = (item, self._fullname(item), _time.time())
                if self.manager.active_panel != self.side:
                    self.manager._activate_side(self.side, set_focus=False)
            except Exception:
                pass

        def _pin(i=item):
            try:
                if not self.tree.exists(i):
                    return
                if plain_click and self.manager.active_panel != self.side:
                    self.manager._activate_side(self.side, set_focus=True)
                self.tree.focus(i)
                if plain_click and i not in self.tree.selection():
                    self.tree.selection_set(i)
                nm = self._fullname(i)
                if nm and nm != "..":
                    self._last_cursor_name = nm
                if nm:
                    self._cursor_pin = (nm, _time.time())
                self._home_stamp = ("", 0.0)
                self.manager._ct("CLICK-pin", f"panel={self.side} on {nm!r}")
            except Exception:
                pass
        self.after_idle(_pin)

        already_selected = item in self.tree.selection()
        text = self.tree.item(item, "text")
        col  = self.tree.identify_column(event.x)   # "#0", "type", "size", …

        # Remember where the button went down, so _cancel_slow_rename() can
        # tell a real slow-click apart from the start of a drag.
        self._press_xy = (event.x_root, event.y_root)

        # A slow click only ever means "rename THIS one".  With several rows
        # selected (or marked) the press is the start of something else — a
        # drag to another program, a copy, a delete — so scheduling a rename
        # there just puts the bottom file into edit mode behind your back.
        multi = len(self.tree.selection()) > 1 or len(self._marked) > 1

        # revCE — "File manager has become very sensitive: sometimes one short
        # click on a file is enough to open edit mode".  A row counts as
        # "already selected" also when it is only the keyboard cursor (the
        # first row after a folder opens, the row a refresh put back, the grey
        # row of the other panel), so a FIRST click on it armed the rename.
        # Now the slow-click rename needs all of:
        #   · this panel was already active when the button went down,
        #   · an earlier plain click on THIS row, between 0 and
        #     SLOW_CLICK_MAX_GAP_S seconds ago (that click is what selected it),
        #   · and at fire time (_fire_slow_rename) the pointer is still on the
        #     row and it is still the only selected row.
        # F2 and Shift+F2 are unchanged.
        now = _time.time()
        prev_item, prev_t = self._last_plain_click
        slow_ok = (plain_click and was_active and prev_item == item
                   and 0.0 < now - prev_t <= self.SLOW_CLICK_MAX_GAP_S)
        if plain_click:
            self._last_plain_click = (item, now)

        if already_selected and slow_ok and text != ".." and not multi:
            if (col == "#1" and item in self._iid_to_fullname
                    and self.tree.set(item, "type") != "Folder"):
                # Clicked on Type column of a FILE → rename extension.  On a
                # folder the Type column says "Folder", not an extension, so
                # the click means the ordinary rename instead (revBM).
                self._rename_after = self.after(
                    650, lambda: self._fire_slow_rename(item, True))
            else:
                # Name column (or other column) → rename base name
                self._rename_after = self.after(
                    650, lambda: self._fire_slow_rename(item, False))

    def _fire_slow_rename(self, item, type_column):
        """The 650 ms timer of a slow click ran out: open the edit box only if
        nothing has changed meanwhile (revCE)."""
        self._rename_after = None
        try:
            if not self.tree.exists(item):
                return
            if tuple(self.tree.selection()) != (item,):
                return   # a key / another click moved the cursor
            ry = self.tree.winfo_pointery() - self.tree.winfo_rooty()
            if self.tree.identify_row(ry) != item:
                return   # the pointer left the row without a drag
        except Exception:
            return
        if type_column:
            self.start_rename_type(item)
        else:
            self.start_rename(item)

    def _cancel_slow_rename(self, event=None):
        """Drop a pending slow-click rename.

        Called the moment the mouse moves with the button down, when a drag
        actually starts, and when the list loses focus (you dropped into
        another program).  Without this the 650 ms timer fires in the middle of
        a drag and the row under the pointer opens for editing — which is what
        put the bottom file of a multi-selection into rename mode."""
        if event is not None and getattr(self, "_press_xy", None):
            # Ignore the pixel of jitter that every click produces.
            try:
                dx = abs(event.x_root - self._press_xy[0])
                dy = abs(event.y_root - self._press_xy[1])
                if dx < 4 and dy < 4:
                    return
            except Exception:
                pass
        if self._rename_after:
            try:
                self.after_cancel(self._rename_after)
            except Exception:
                pass
            self._rename_after = None

    def _on_right_click(self, event):
        if self.archive_ctx is not None:
            self._archive_context_menu(event)
            return "break"
        # Right-click on a column header sorts FOLDERS (left-click sorts files).
        # This lets you keep files newest-first while folders stay A→Z.
        try:
            region = self.tree.identify_region(event.x, event.y)
        except Exception:
            region = ""
        if region in ("heading", "separator"):
            col_id = self.tree.identify_column(event.x)   # "#0", "#1", …
            col = self._colid_to_name(col_id)
            if col:
                self._sort_dirs_by(col)
            return "break"

        item = self.tree.identify_row(event.y)
        if item:
            # Only move the cursor when the click lands outside the current
            # selection — otherwise a right-click would collapse a multi-select
            if item not in self.tree.selection():
                self.tree.selection_set(item)
            self.manager._activate_side(self.side, set_focus=False)
            self.manager.build_sendto_menu()
            self.manager.build_tags_menu()
            self.manager.build_folder_sort_menu()
            self.manager.context_menu.post(event.x_root, event.y_root)
        else:
            # Empty space under the list: a small menu for the folder you are IN
            # (this is where the per-folder sort override lives — DEL 45).
            self.manager.show_empty_area_menu(self, event)

    def _archive_context_menu(self, event):
        """Small, self-contained menu while browsing inside an archive —
        only the operations that actually make sense on a virtual entry."""
        item = self.tree.identify_row(event.y)
        if item and item not in self.tree.selection():
            self.tree.selection_set(item)
        self.manager._activate_side(self.side, set_focus=False)

        fmt   = (self.archive_ctx or {}).get("fmt", "")
        menu  = tk.Menu(self, tearoff=0)
        fname = self._fullname(item) if item else None
        menu.add_command(
            label="Open / enter",
            command=(lambda: self.archive_activate(fname, False, False))
                    if fname else None,
            state="normal" if fname else "disabled")
        menu.add_separator()
        menu.add_command(label="Copy to other panel   (F5)",
                         command=self.manager.copy_files)
        menu.add_command(label="Move to other panel   (F6)",
                         command=self.manager.move_files,
                         state="normal" if fmt in PACK_FORMATS else "disabled")
        menu.add_command(label="Delete from archive   (Del)",
                         command=self.manager.delete_files,
                         state="normal" if fmt in PACK_FORMATS else "disabled")
        menu.add_separator()
        menu.add_command(label="✕  Exit archive", command=self.exit_archive)
        menu.tk_popup(event.x_root, event.y_root)

    def _first_file_iid(self):
        """The iid of the topmost FILE row — the one just under the last
        folder — in whatever order the panel is sorted right now.  None when
        the folder holds nothing but folders."""
        for iid in self.tree.get_children():
            if self.tree.item(iid, "text") == "..":
                continue
            try:
                if self.tree.set(iid, "type") != "Folder":
                    return iid
            except Exception:
                continue
        return None

    def _on_home_key(self, event=None):
        """Home / Ctrl+Home — jump to the first row.

        Press it AGAIN, standing on that first row, and the cursor drops to
        the topmost FILE: the row just below the last folder.  That is the
        "Home, Home" move — one key, no scrolling past a hundred sub-folders,
        and a third press takes you back to the top.
        """
        kids = self.tree.get_children()
        if not kids:
            return "break"
        target = kids[0]
        # "Home, Home" — the SECOND press drops to the topmost file.  The test
        # used to be "is the cursor already on row 0?", which is NOT the same
        # question: after a Tab into a panel that is standing on the ".." dots
        # the cursor is ALREADY on row 0, so the very first Home press counted
        # as the second one and jumped to the first file.  Press Enter after
        # that and you have started a program when you meant to go up.
        # (revAP — reported as "instead of Enter I press Home, and the cursor
        # moves to the top file... sometimes".)  It now takes a real previous
        # HOME PRESS — recent, and still standing on the same row — and every
        # other way of placing the cursor clears that stamp.
        last_iid, last_when = getattr(self, "_home_stamp", ("", 0.0))
        repeat = (self.tree.focus() == kids[0]
                  and last_iid == kids[0]
                  and (_time.time() - last_when) <= 5.0)
        if repeat:
            first_file = self._first_file_iid()
            if first_file:
                target = first_file
                self._home_stamp = ("", 0.0)
                try:
                    self.manager._flash_status(
                        "Topmost file  —  press Home again for the top of "
                        "the list.", 2500)
                except Exception:
                    pass
        else:
            self._home_stamp = (kids[0], _time.time())
        try:
            self.manager._ct("HOME-KEY",
                             f"panel={self.side} -> {self._fullname(target)!r} "
                             f"(counted as a second press: {repeat})")
        except Exception:
            pass
        self.tree.see(target)
        self.tree.selection_set(target)
        self.tree.focus(target)
        return "break"

    def _on_end_key(self, event=None):
        """End / Ctrl+End — jump to the last row."""
        kids = self.tree.get_children()
        if kids:
            last = kids[-1]
            self.tree.see(last)
            self.tree.selection_set(last)
            self.tree.focus(last)
        return "break"

    def _visible_rows(self) -> int:
        """How many rows fit in the tree right now — the step for Page Up/Down."""
        try:
            rh = int(ttk.Style().lookup("Treeview", "rowheight") or 0) or 18
            h  = self.tree.winfo_height()
            # Leave one row of overlap so you keep your bearings between pages.
            return max(1, (h // rh) - 1)
        except Exception:
            return 15

    def _page_move(self, direction: int, step: int, mark: bool = False):
        """Move the keyboard cursor *step* rows up (direction=-1) or down (+1),
        keeping it on-screen so you always see where you are.  Shared by plain
        Page Up/Down (a window-full) and the fixed Ctrl+/Shift+Page jumps.

        mark=True red-marks EVERY row the cursor travels over — the row it
        started on, the row it lands on and everything in between — which is
        what Shift+Page does (same rule as Shift+Up / Shift+Down, one page at
        a time instead of one row).  '..' is never marked.  Marks are only
        ever added here, never removed, exactly like Shift+Up/Down and
        Shift+Home/End; Ctrl+N (or numpad -) clears them."""
        kids = list(self.tree.get_children())
        if not kids:
            return "break"
        cur = self.tree.focus() or (self.tree.selection()[0]
                                    if self.tree.selection() else kids[0])
        try:
            idx = kids.index(cur)
        except ValueError:
            idx = 0
        new = max(0, min(len(kids) - 1, idx + direction * max(1, step)))
        if mark:
            lo, hi = (idx, new) if idx <= new else (new, idx)
            for iid in kids[lo:hi + 1]:
                if self._fullname(iid) != "..":
                    self._add_mark(iid)
        tgt = kids[new]
        # see() scrolls the list so the cursor stays visible (your request:
        # the view follows the cursor, never leaving it off-screen).
        self.tree.see(tgt)
        self.tree.selection_set(tgt)
        self.tree.focus(tgt)
        # Landing ON a marked row must show the marked-cursor colour instead of
        # ttk's blue.  <<TreeviewSelect>> does this too, but only once the event
        # loop gets round to it — doing it here as well keeps the colours right
        # the instant the key is released.  (No-op when nothing is marked.)
        self._reconcile_marked_cursor()
        return "break"

    def _on_page_down(self, event=None):
        """Page Down — cursor down one visible page (window-full of rows)."""
        return self._page_move(+1, self._visible_rows())

    def _on_page_up(self, event=None):
        """Page Up — cursor up one visible page (window-full of rows)."""
        return self._page_move(-1, self._visible_rows())

    def _on_ctrl_page_down(self, event=None):
        """Ctrl+Page Down — fixed small jump down (CURSOR_JUMP_SMALL rows)."""
        return self._page_move(+1, CURSOR_JUMP_SMALL)

    def _on_ctrl_page_up(self, event=None):
        """Ctrl+Page Up — fixed small jump up (CURSOR_JUMP_SMALL rows)."""
        return self._page_move(-1, CURSOR_JUMP_SMALL)

    def _on_shift_page_down(self, event=None):
        """Shift+Page Down — big jump down (CURSOR_JUMP_BIG rows), MARKING
        every file and folder it passes on the way (Total-Commander style)."""
        return self._page_move(+1, CURSOR_JUMP_BIG, mark=True)

    def _on_shift_page_up(self, event=None):
        """Shift+Page Up — big jump up (CURSOR_JUMP_BIG rows), MARKING every
        file and folder it passes on the way (Total-Commander style)."""
        return self._page_move(-1, CURSOR_JUMP_BIG, mark=True)

    def _on_insert_key(self, event):
        """Insert — toggle the red mark on this row, then move down one step."""
        focused = self.tree.focus()
        if not focused:
            return "break"
        self._toggle_mark(focused)
        # Move cursor one step down; keep it visible via selection highlight
        children = list(self.tree.get_children())
        try:
            idx = children.index(focused)
        except ValueError:
            return "break"
        if idx + 1 < len(children):
            nxt = children[idx + 1]
            self.tree.focus(nxt)
            self.tree.selection_set(nxt)
            self.tree.see(nxt)
        return "break"

    def _on_shift_down(self, event):
        """Shift+Down — mark this row, then move the cursor down one step."""
        focused = self.tree.focus()
        if not focused:
            return "break"
        children = list(self.tree.get_children())
        try:
            idx = children.index(focused)
        except ValueError:
            return "break"
        self._add_mark(focused)
        if idx + 1 < len(children):
            nxt = children[idx + 1]
            self._add_mark(nxt)
            self.tree.focus(nxt)
            self.tree.selection_set(nxt)
            self.tree.see(nxt)
        return "break"

    def _on_shift_up(self, event):
        """Shift+Up — mark this row, then move the cursor up one step."""
        focused = self.tree.focus()
        if not focused:
            return "break"
        children = list(self.tree.get_children())
        try:
            idx = children.index(focused)
        except ValueError:
            return "break"
        self._add_mark(focused)
        if idx > 0:
            prv = children[idx - 1]
            self._add_mark(prv)
            self.tree.focus(prv)
            self.tree.selection_set(prv)
            self.tree.see(prv)
        return "break"

    def _on_select_all(self, event=None, kind="all"):
        """Mark rows (red), filtered by kind:
           'all'   → files and folders   (Ctrl+A, Ctrl+numpad*)
           'files' → files only, folders untouched (plain numpad*)
           'dirs'  → folders only, files untouched (Shift+numpad*)
           The '..' entry is never marked."""
        kids = list(self.tree.get_children())
        last = None
        for iid in kids:
            if self._fullname(iid) == "..":
                continue
            if kind != "all":
                is_dir = self.tree.set(iid, "type") == "Folder"
                if kind == "files" and is_dir:
                    continue
                if kind == "dirs" and not is_dir:
                    continue
            self._add_mark(iid)
            last = iid
        if last is not None:
            self.tree.focus(last)
            self.tree.selection_set(last)
            self.tree.see(last)
        try:
            self.manager._update_counts()
        except Exception:
            pass
        return "break"

    def _on_unmark_all(self, event=None, kind="all"):
        """Clear red marks, filtered by kind — same meaning as _on_select_all.
        'all' (Ctrl+N, Ctrl+numpad-) clears everything, exactly as before."""
        if kind == "all":
            targets = list(self._marked)
        else:
            want_dir = (kind == "dirs")
            targets = [iid for iid in self._marked
                       if self.tree.exists(iid)
                       and (self.tree.set(iid, "type") == "Folder") == want_dir]
        for iid in targets:
            self._clear_mark_tag(iid)
            self._marked.discard(iid)
        try:
            self.manager._update_counts()
        except Exception:
            pass
        return "break"

    def _on_toggle_select_all(self, event=None):
        """Numeric-keypad "*" — Total Commander's mark-everything key.

        One key, one toggle: mark everything that can be marked, or — if
        everything already is — clear all marks instead.  Ctrl+A / Ctrl+N
        stay exactly as they were for anyone who wants the two as separate
        keys; this just adds the single-key toggle on top.
        """
        kids = [iid for iid in self.tree.get_children()
                if self._fullname(iid) != ".."]
        if kids and all(iid in self._marked for iid in kids):
            return self._on_unmark_all(event)
        return self._on_select_all(event)

    # ── Real OS clipboard: Ctrl+C / Ctrl+X / Ctrl+V with actual files ──────
    # (helper functions clipboard_get_files / clipboard_set_files live with
    # the other Win32 helpers, just above "File panel (local)")

    def _os_clip_selection(self) -> list:
        """Full paths of the current selection, falling back to the cursor
        row — same "marked, else cursor" rule get_all_selected() already
        uses elsewhere, kept local here so a bare cursor row with nothing
        marked still lets Ctrl+C copy the ONE file under it."""
        paths = self.get_all_selected()
        if paths:
            return paths
        one = self.get_selected()
        return [one] if one else []

    def _on_copy_to_os_clipboard(self, event=None):
        """Ctrl+C — put the selection on the SYSTEM clipboard as real files,
        so Explorer (or anything else) can paste them.  Separate from
        SEL ▾ "Copy paths to clipboard", which is path TEXT, not files."""
        if self.is_remote:
            return "break"
        paths = self._os_clip_selection()
        if not paths:
            return "break"
        if clipboard_set_files(paths, cut=False):
            self.manager._flash_status(
                f"{len(paths)} item(s) copied — Ctrl+V here or in any other "
                "program.")
        return "break"

    def _on_cut_to_os_clipboard(self, event=None):
        """Ctrl+X — same, but marked as a Cut (Explorer's own "Preferred
        DropEffect" = Move), so pasting anywhere moves the files instead of
        copying them, exactly like a real Explorer Cut would."""
        if self.is_remote:
            return "break"
        paths = self._os_clip_selection()
        if not paths:
            return "break"
        if clipboard_set_files(paths, cut=True):
            self.manager._flash_status(
                f"{len(paths)} item(s) cut — paste anywhere to move them.")
        return "break"

    def _on_paste_from_os_clipboard(self, event=None):
        """Ctrl+V — files copied (or cut) in Explorer or any other program
        land in THIS panel's current folder, through the same queued
        copy/move engine F5/F6 use.  A Cut moves them and removes the
        originals, exactly as pasting into Explorer would."""
        if self.is_remote:
            messagebox.showinfo(
                "Paste", "This panel is FTP-mounted — files from the "
                "clipboard can only be pasted into a LOCAL panel.",
                parent=self)
            return "break"
        paths, is_cut = clipboard_get_files()
        paths = [p for p in paths if p and os.path.exists(p)]
        if not paths:
            return "break"
        if self.archive_ctx is not None:
            self.manager._add_to_archive(self, paths, move=is_cut)
            return "break"
        self.manager._copy_move_local(paths, self.current_path, move=is_cut)
        return "break"

    def _clear_marks_and_selection(self):
        self.manager._ct("CLEAR-MARKS-in", f"panel={self.side}", depth=2)
        try:
            self.__clear_marks_and_selection()
        finally:
            self.manager._ct("CLEAR-MARKS-out", f"panel={self.side}", depth=2)

    def __clear_marks_and_selection(self):
        """After a copy / move: drop the red marks and collapse any multi-row
        selection down to a SINGLE, clearly-visible cursor row — so you see where
        the cursor is, not a stale block of 'still marked' files.  The keyboard
        cursor (focus item) is kept so the arrow keys keep working from there."""
        for iid in list(self._marked):
            self._clear_mark_tag(iid)
        self._marked.clear()
        try:
            foc = self.tree.focus()
            if foc and self.tree.exists(foc):
                if self.manager.active_panel != self.side:
                    # An INACTIVE panel must never carry a real selection —
                    # that is the active panel's colour, and it would leave two
                    # rows claiming to be the cursor when Tab came back here.
                    self.manager._sync_inactive_cursor(self)
                else:
                    # Reduce the highlight to the one cursor row.
                    self.tree.selection_set(foc)
                    self.tree.see(foc)
            else:
                sel = self.tree.selection()
                if sel:
                    self.tree.selection_remove(*sel)
        except Exception:
            pass
        try:
            self.manager._update_counts()
        except Exception:
            pass

    def _on_shift_end(self, event=None):
        """Shift+End — mark from the current row down to the LAST row.
        (From the top row this marks everything, like a full select-all.)"""
        kids = list(self.tree.get_children())
        if not kids:
            return "break"
        focused = self.tree.focus() or kids[0]
        try:
            idx = kids.index(focused)
        except ValueError:
            idx = 0
        for iid in kids[idx:]:
            if self._fullname(iid) != "..":
                self._add_mark(iid)
        last = kids[-1]
        self.tree.focus(last)
        self.tree.selection_set(last)
        self.tree.see(last)
        return "break"

    def _on_shift_home(self, event=None):
        """Shift+Home — mark from the current row up to the FIRST row."""
        kids = list(self.tree.get_children())
        if not kids:
            return "break"
        focused = self.tree.focus() or kids[-1]
        try:
            idx = kids.index(focused)
        except ValueError:
            idx = len(kids) - 1
        for iid in kids[:idx + 1]:
            if self._fullname(iid) != "..":
                self._add_mark(iid)
        first = kids[0]
        self.tree.focus(first)
        self.tree.selection_set(first)
        self.tree.see(first)
        return "break"

    # ── Inline rename ─────────────────────────────────────────────────────

    def start_rename(self, item):
        """Inline rename of the base name (Name column)."""
        self._rename_after = None
        # The rename is scheduled via after(650, ...); a folder refresh in that
        # window can delete the row, so the iid may no longer exist.  Bail out
        # quietly instead of raising TclError ("Item ... not found").
        if not self.tree.exists(item):
            return
        base_text = self.tree.item(item, "text")   # displayed base name
        if base_text == "..":
            return
        fullname  = self._fullname(item)
        full_path = os.path.join(self.current_path, fullname)
        _, ext    = os.path.splitext(fullname)
        self._rename_data = {"old_path": full_path, "item": item,
                             "ext": ext, "field": "name"}

        try:
            x, y, width, height = self.tree.bbox(item, "#0")
        except Exception:
            return

        # Use tk.Entry (not ttk.Entry) so insertofftime/insertontime work
        entry = tk.Entry(self.tree,
                         bg="#2a2a3d", fg="#e0e0f0",
                         insertbackground="#e0e0f0",
                         relief="flat", bd=1,
                         insertofftime=0, insertontime=9999999)
        entry.place(x=x, y=y, width=width, height=height)
        entry.insert(0, base_text)
        entry.selection_range(0, tk.END)
        entry.focus_set()

        # Return commits AND stops here ("break") — otherwise the same Enter
        # bubbles up to the global <Return> binding and opens the file (F3)
        # right after the rename, which was maddening.
        entry.bind("<Return>",    lambda e: (self._finish_rename(entry), "break")[1])
        entry.bind("<Escape>",    lambda e: (self._cancel_rename(entry), "break")[1])
        entry.bind("<FocusOut>",  lambda e: self._finish_rename(entry))
        # TC-style: Up/Down commits rename and moves to next/prev item in rename mode
        entry.bind("<Down>",      lambda e: (self._rename_nav(entry, +1), "break")[1])
        entry.bind("<Up>",        lambda e: (self._rename_nav(entry, -1), "break")[1])
        # TAB crosses to the EXTENSION of the same file and stays in edit mode.
        # F2 only ever opened the name box, and the only way into the extension
        # was a slow click on the narrow Type column — not something you find
        # by looking.  Tab both ways is the way in (revBM).
        entry.bind("<Tab>",       lambda e: (self._rename_switch_field(entry, "type"), "break")[1])
        entry.bind("<Shift-Tab>", lambda e: (self._rename_switch_field(entry, "type"), "break")[1])
        self._rename_entry = entry
        # Store on manager so save_rename() still works if called externally
        self.manager.rename_item = entry
        self.manager.rename_data = self._rename_data

    def start_rename_type(self, item):
        """Inline rename of the extension (Type column)."""
        self._rename_after = None
        if not self.tree.exists(item):
            return   # row was refreshed away before the slow-click fired
        if item not in self._iid_to_fullname:
            return   # the row is gone
        # A FOLDER has no extension.  The old guard above was meant to keep
        # folders out, but _iid_to_fullname holds every row — folders and ".."
        # included — so it never did: a slow click on a folder's Type column
        # opened an empty edit box over the word "Folder" (revBM).
        if self.tree.set(item, "type") == "Folder":
            return
        fullname  = self._fullname(item)
        full_path = os.path.join(self.current_path, fullname)
        base, ext = os.path.splitext(fullname)
        self._rename_data = {"old_path": full_path, "item": item,
                             "ext": ext, "field": "type", "base": base}

        try:
            x, y, width, height = self.tree.bbox(item, "type")
        except Exception:
            return

        entry = tk.Entry(self.tree,
                         bg="#2a2a3d", fg="#e0e0f0",
                         insertbackground="#e0e0f0",
                         relief="flat", bd=1,
                         insertofftime=0, insertontime=9999999)
        entry.place(x=x, y=y, width=width, height=height)
        entry.insert(0, ext.lstrip("."))   # show "pdf", "py" etc. (no dot)
        entry.selection_range(0, tk.END)
        entry.focus_set()

        entry.bind("<Return>",   lambda e: (self._finish_rename(entry), "break")[1])
        entry.bind("<Escape>",   lambda e: (self._cancel_rename(entry), "break")[1])
        entry.bind("<FocusOut>", lambda e: self._finish_rename(entry))
        # Up/Down walk the list here too.  Editing the Type column had no such
        # bindings, so the arrows fell through to the tree and edit mode simply
        # ended — the same keyboard walk, dead in one of the two columns.
        entry.bind("<Down>",     lambda e: (self._rename_nav(entry, +1), "break")[1])
        entry.bind("<Up>",       lambda e: (self._rename_nav(entry, -1), "break")[1])
        # …and Tab crosses back to the NAME of the same file (revBM).
        entry.bind("<Tab>",       lambda e: (self._rename_switch_field(entry, "name"), "break")[1])
        entry.bind("<Shift-Tab>", lambda e: (self._rename_switch_field(entry, "name"), "break")[1])
        self._rename_entry = entry
        self.manager.rename_item = entry
        self.manager.rename_data = self._rename_data

    def _rename_switch_field(self, entry, want: str):
        """TAB inside a rename box: cross to the other half of the name.

        Name box ⇄ Type box on the SAME row, without ever leaving edit mode.
        The extension had no keyboard route at all before this — F2 opens the
        name, and the only way to the extension was a 650 ms slow click on a
        86-pixel-wide column.  Tab is the way in, and the same key is the way
        back (revBM).

        What is in the box is committed first, exactly as Up/Down does, and the
        row is then found again BY NAME: renaming `a.txt` to `z.txt` re-sorts
        the list, so the old position means nothing."""
        if not self._rename_data:
            return
        entry.unbind("<FocusOut>")
        raw      = entry.get().strip()
        old_path = self._rename_data["old_path"]
        field    = self._rename_data.get("field", "name")
        ext      = self._rename_data.get("ext", "")

        if field == "type":
            base     = self._rename_data.get(
                "base", os.path.splitext(os.path.basename(old_path))[0])
            new_name = base + (("." + raw.lstrip(".")) if raw else "")
        else:
            new_name = raw + ext if raw else ""

        # Tear the entry down before any conflict dialog can grab focus
        try:
            entry.destroy()
        except Exception:
            pass
        self._rename_entry = None
        self._rename_data  = None
        self.manager.rename_item = None
        self.manager.rename_data = None

        final = old_path
        if new_name:
            final = (self.manager.rename_path(old_path, new_name,
                                              parent=self.manager)
                     or old_path)

        self.refresh()
        target_name = os.path.basename(final)
        target = next((i for i in self.tree.get_children()
                       if self._fullname(i) == target_name), None)
        if target is None:
            return
        self.tree.selection_set(target)
        self.tree.focus(target)
        self.tree.see(target)
        reopen = (self.start_rename_type if want == "type"
                  else self.start_rename)
        # Small delay so the entry widget is placed after layout settles
        self.after(30, lambda i=target: reopen(i))

    def _rename_nav(self, entry, delta: int):
        """TC-style: commit rename, move cursor up/down, start rename on that item.

        THE ".." ROW IS SKIPPED, and that was the bug (revBI).  Rename a file
        so that it sorts somewhere else — `aaa` to `zzz` — and the row above
        the one you land on is the parent dots.  Stepping onto them called
        start_rename("..") which returns without a word, so edit mode simply
        never came back and the whole keyboard walk down a folder died.  It
        looked random because it only happened after a rename that MOVED the
        file in the sort order."""
        if not self._rename_data:
            return
        # 1. Find position of current item in the tree BEFORE rename
        current_item = self._rename_data["item"]
        children = list(self.tree.get_children())
        try:
            idx = children.index(current_item)
        except ValueError:
            self._finish_rename(entry)
            return

        # 2. Step in the wanted direction to the next REAL row.  ".." is not a
        #    thing you can rename, so it is stepped over rather than landed on.
        target_idx = idx + delta
        while (0 <= target_idx < len(children)
               and self._fullname(children[target_idx]) == ".."):
            target_idx += delta
        if target_idx < 0 or target_idx >= len(children):
            # Already at top/bottom — just commit, no further rename
            self._finish_rename(entry)
            return

        # 3. Remember the FULL name of the target item before we refresh
        target_fullname = self._fullname(children[target_idx])
        target_pos      = target_idx

        # 4. Perform the rename (same logic as _finish_rename but without triggering FocusOut)
        entry.unbind("<FocusOut>")
        raw      = entry.get().strip()
        old_path = self._rename_data["old_path"]
        field    = self._rename_data.get("field", "name")
        ext      = self._rename_data.get("ext", "")

        if field == "type":
            base     = self._rename_data.get("base", os.path.splitext(os.path.basename(old_path))[0])
            new_ext  = ("." + raw.lstrip(".")) if raw else ""
            new_name = base + new_ext
        else:
            new_name = raw + ext if raw else ""

        # Tear the entry down before any conflict dialog can grab focus
        try:
            entry.destroy()
        except Exception:
            pass
        self._rename_entry = None
        self._rename_data  = None
        self.manager.rename_item = None
        self.manager.rename_data = None

        # Conflict-aware rename (Overwrite old / Backup-rename old / Rename new)
        if new_name:
            self.manager.rename_path(old_path, new_name, parent=self.manager)

        # 5. Refresh preserving sort; then find the target again BY NAME — the
        #    rename may have re-sorted the whole list, so its old index means
        #    nothing.  If the name is gone (it was the file just renamed, or
        #    something else moved it), fall back to whatever row now stands in
        #    that position, still never the dots.  Landing SOMEWHERE beats
        #    quietly dropping out of edit mode, which is what used to happen.
        self.refresh()
        kids   = list(self.tree.get_children())
        target = next((i for i in kids
                       if self._fullname(i) == target_fullname), None)
        if target is None and kids:
            pos = max(0, min(target_pos, len(kids) - 1))
            target = kids[pos]
            while target is not None and self._fullname(target) == "..":
                pos += 1 if delta > 0 else -1
                target = kids[pos] if 0 <= pos < len(kids) else None
        if target is None:
            return
        self.tree.selection_set(target)
        self.tree.focus(target)
        self.tree.see(target)
        # Re-open the SAME column you were editing: walking down the Type
        # column must not silently drop you into the Name column.
        reopen = (self.start_rename_type if field == "type"
                  else self.start_rename)
        # Small delay so the entry widget is placed after layout settles
        self.after(30, lambda i=target: reopen(i))

    def _finish_rename(self, entry):
        if not self._rename_data:
            return
        raw      = entry.get().strip()
        old_path = self._rename_data["old_path"]
        field    = self._rename_data.get("field", "name")
        ext      = self._rename_data.get("ext", "")

        if field == "type":
            # Editing the extension — keep the base name, apply new ext
            base     = self._rename_data.get("base", os.path.splitext(os.path.basename(old_path))[0])
            new_ext  = ("." + raw.lstrip(".")) if raw else ""
            new_name = base + new_ext
        else:
            # Editing the base name — keep the original extension
            new_name = raw + ext if raw else ""

        # Tear the entry down BEFORE any conflict dialog, so the entry's own
        # <FocusOut> cannot re-enter this method when the dialog grabs focus.
        try:
            entry.unbind("<FocusOut>")
        except Exception:
            pass
        try:
            entry.destroy()
        except Exception:
            pass
        self._rename_entry = None
        self._rename_data  = None
        self.manager.rename_item = None
        self.manager.rename_data = None

        # Conflict-aware rename (Overwrite old / Backup-rename old / Rename new)
        new_path = None
        if new_name:
            new_path = self.manager.rename_path(old_path, new_name,
                                                parent=self.manager)
        self.refresh()
        # The clash dialog ("Backup-rename old" …) is a Toplevel that takes the
        # keyboard, and closing it does NOT give it back: the row still looked
        # selected but the arrow keys did nothing until you pressed TAB twice.
        # Put the cursor on whatever the file is called now and hand the
        # keyboard straight back to the list.
        self._focus_row_by_name(os.path.basename(new_path or old_path))

    def _focus_row_by_name(self, name: str):
        """Put the cursor on the row with this full name and give the list the
        keyboard back.  Quietly does nothing when the row is not there."""
        try:
            target = None
            for iid in self.tree.get_children():
                if self._fullname(iid) == name:
                    target = iid
                    break
            if target is not None:
                self.tree.see(target)
                self.tree.selection_set(target)
                self.tree.focus(target)
            self.tree.focus_set()
        except Exception:
            pass

    def _cancel_rename(self, entry):
        try:
            entry.destroy()
        except Exception:
            pass
        self._rename_entry = None
        self._rename_data  = None
        self.manager.rename_item = None
        self.manager.rename_data = None
        # Escape killed the entry — without this the keyboard is left nowhere
        # and the arrow keys are dead until the list is clicked or TAB'd back.
        try:
            self.tree.focus_set()
        except Exception:
            pass

    # ── Navigation ────────────────────────────────────────────────────────

    def change_directory(self, path, select_name=None):
        self._marked.clear()
        # Leaving the folder also leaves the flat branch listing
        self.branch_mode = False
        if self.archive_ctx is not None:
            self.archive_ctx = None
            self._hide_archive_bar()
        self.current_path = os.path.abspath(path)
        self.refresh()
        # Find the item to select: prefer select_name (e.g. after go_up), else first row
        target_iid = None
        if select_name:
            for iid in self.tree.get_children():
                if self._fullname(iid) == select_name:
                    target_iid = iid
                    break
        if target_iid is None:
            first = self.tree.get_children()
            target_iid = first[0] if first else None
        if target_iid:
            self.tree.selection_set(target_iid)
            self.tree.focus(target_iid)
            self.tree.see(target_iid)
            # Pin it, so the auto-refresh poll cannot move the cursor a moment
            # after landing in a new folder (revAO).
            self._cursor_pin = (self._fullname(target_iid), _time.time())
        self._home_stamp = ("", 0.0)
        self.manager._ct("CHDIR", f"panel={self.side} -> {self.current_path} "
                                  f"(asked for {select_name!r})", depth=2)
        self.tree.focus_set()
        # Notify manager so the tab bar label updates
        if hasattr(self.manager, "_on_panel_navigate"):
            self.manager._on_panel_navigate(self.side, self.current_path)
        # Keep Quick View and the command prompt in step with the new folder
        if hasattr(self.manager, "sync_side_panels"):
            self.manager.sync_side_panels()

    def go_up(self):
        child_name = os.path.basename(self.current_path)
        self.change_directory(os.path.dirname(self.current_path),
                              select_name=child_name)

    def go_root(self):
        self.change_directory(os.path.splitdrive(self.current_path)[0] + "\\")

    # ── Browsing INSIDE an archive (Enter / double-click descends like a
    #    folder — Total-Commander style) ────────────────────────────────

    def enter_archive(self, path: str):
        """Descend into the archive at *path* as if it were a folder."""
        try:
            entries = archive_list(path)
        except ArchiveError as exc:
            _archive_error_box(self, exc)
            return
        self._marked.clear()
        self.branch_mode = False
        self.archive_ctx = {
            "archive_path": os.path.abspath(path),
            "real_path":    self.current_path,   # real folder to return to
            "subpath":      "",                  # dir inside the archive
            "entries":      entries,
            "fmt":          archive_format(path),
        }
        self._refresh_archive_view()
        self.tree.focus_set()

    def exit_archive(self):
        """Leave archive-browsing mode and go back to the real folder that
        contained it — with the cursor back ON the archive you just left,
        exactly like '..' out of a real folder (revAC).  Landing on the first
        row instead meant losing your place in a long folder every time you
        peeked inside a zip."""
        if self.archive_ctx is None:
            return
        real     = self.archive_ctx["real_path"]
        arc_name = os.path.basename(self.archive_ctx["archive_path"])
        self.archive_ctx = None
        self._hide_archive_bar()
        self.change_directory(real, select_name=arc_name)

    def archive_go_up(self):
        """'..' inside the archive — one level up, or out of the archive
        entirely once already at its root."""
        ctx = self.archive_ctx
        if ctx is None:
            return
        if ctx["subpath"]:
            ctx["subpath"] = (ctx["subpath"].rsplit("/", 1)[0]
                              if "/" in ctx["subpath"] else "")
            self._marked.clear()
            self._refresh_archive_view()
        else:
            self.exit_archive()

    def archive_activate(self, fullname: str, shift: bool = False,
                         ctrl: bool = False):
        """Enter / double-click on a row while browsing inside an archive."""
        ctx = self.archive_ctx
        if ctx is None:
            return
        if fullname == "..":
            self.archive_go_up()
            return
        sub    = ctx["subpath"]
        prefix = sub + "/" if sub else ""
        inner  = prefix + fullname
        is_dir = any(
            _norm_member(e.name) == _norm_member(inner) and e.is_dir
            or _norm_member(e.name).startswith(_norm_member(inner) + "/")
            for e in ctx["entries"]
        )
        if is_dir:
            ctx["subpath"] = inner
            self._marked.clear()
            self._refresh_archive_view()
        else:
            self._open_archived_file(inner, shift, ctrl)

    def _open_archived_file(self, inner_name: str, shift: bool = False,
                            ctrl: bool = False):
        """Extract one file from the archive to a temp folder and open it,
        the same way Enter/double-click opens a real file."""
        ctx = self.archive_ctx
        tmp = tempfile.mkdtemp(prefix="fm_archview_")
        try:
            archive_extract_members(ctx["archive_path"], tmp, [inner_name])
        except ArchiveError as exc:
            _archive_error_box(self, exc)
            return
        local = os.path.join(tmp, *inner_name.split("/"))
        if os.path.isfile(local):
            self.manager._open_file_activated(local, shift, ctrl)
        else:
            messagebox.showinfo("Archive", "Could not extract that file.", parent=self)

    def _archive_display_path(self) -> str:
        ctx = self.archive_ctx
        name = os.path.basename(ctx["archive_path"])
        sub  = ctx["subpath"]
        return f"📦 {name}" + (f"  ›  {sub}" if sub else "")

    def _show_archive_bar(self):
        self._archive_bar_lbl.configure(text=self._archive_display_path())
        if not self._archive_bar.winfo_manager():
            self._archive_bar.pack(side="top", fill="x", before=self.tree)

    def _hide_archive_bar(self):
        if self._archive_bar.winfo_manager():
            self._archive_bar.pack_forget()

    def _refresh_archive_view(self):
        """Populate the tree from archive_ctx — folders and files at the
        current subpath only, exactly like a real directory listing."""
        ctx = self.archive_ctx
        # Marks are remembered by NAME across the rebuild, exactly as refresh()
        # does for a real folder.  Before this, _marked kept the iids of rows
        # that had just been deleted: every navigation path clears the set
        # first, but an IN-PLACE refresh (the one after copying files out of
        # the zip) does not — and the stale iids then crashed
        # _clear_marks_and_selection().  Safe to restore by name because
        # enter_archive / archive_go_up / archive_activate all clear the marks
        # before they change subpath, so nothing can leak between folders.
        prev_marked_names = {self._fullname(iid) for iid in self._marked
                             if self.tree.exists(iid)}
        self._marked.clear()
        self.tree.delete(*self.tree.get_children())
        self._iid_to_fullname.clear()
        self._show_archive_bar()

        sub    = ctx["subpath"]
        prefix = sub + "/" if sub else ""
        dirs_seen: dict = {}
        files: list = []
        for e in ctx["entries"]:
            name = _norm_member(e.name)
            if not name.startswith(prefix):
                continue
            rest = name[len(prefix):]
            if not rest:
                continue
            if "/" in rest:
                dirs_seen.setdefault(rest.split("/", 1)[0], True)
            elif e.is_dir:
                dirs_seen.setdefault(rest, True)
            else:
                files.append((rest, e))

        up_iid = self.tree.insert("", "end", text="..",
                                  values=("", "", "", "", "", ""), tags=("dir",))
        self._iid_to_fullname[up_iid] = ".."

        for d in sorted(dirs_seen, key=str.lower):
            iid = self.tree.insert("", "end", text=d,
                                   values=("Folder", "", "", "", "", ""),
                                   tags=("dir",))
            self._iid_to_fullname[iid] = d

        for fname, e in sorted(files, key=lambda t: t[0].lower()):
            ext = os.path.splitext(fname)[1].lstrip(".").upper()
            iid = self.tree.insert("", "end", text=fname,
                                   values=(f"{ext} file" if ext else "File",
                                           "", _human_size(e.size), e.modified,
                                           "", ""))
            self._iid_to_fullname[iid] = fname

        # Put the marks back on the rows that carry the same names
        if prev_marked_names:
            is_active_panel = (self.manager.active_panel == self.side)
            for iid in self.tree.get_children():
                nm = self._fullname(iid)
                if nm != ".." and nm in prev_marked_names:
                    self._marked.add(iid)
                    self._set_mark_tag(iid, active=is_active_panel)

        first = self.tree.get_children()
        if first:
            self.tree.selection_set(first[0])
            self.tree.focus(first[0])

    def archive_selected_inner_names(self) -> list:
        """Archive-internal paths (forward-slash) for the marked / selected
        rows, while archive_ctx is active — files as themselves, folders as
        prefixes (their full contents are pulled in by _member_matches)."""
        ctx = self.archive_ctx
        if ctx is None:
            return []
        sub    = ctx["subpath"]
        prefix = sub + "/" if sub else ""
        iids = list(self._marked) if self._marked else list(self.tree.selection())
        if not iids:
            cur = self.tree.focus()
            if cur:
                iids = [cur]
        names = []
        for iid in iids:
            fname = self._fullname(iid)
            if fname and fname != "..":
                names.append(prefix + fname)
        return names

    def get_selected(self):
        # Prefer explicitly marked items; fall back to tree cursor
        if self._marked:
            for iid in self.tree.get_children():
                if iid in self._marked:
                    fname = self._fullname(iid)
                    if fname != "..":
                        return os.path.join(self.current_path, fname)
            return None
        sel = self.tree.selection()
        if sel:
            fname = self._fullname(sel[0])
            if fname == "..":
                return None
            return os.path.join(self.current_path, fname)
        return None

    def get_all_selected(self):
        """Return full paths for all marked (or cursor-selected) items, excluding '..'."""
        if self._marked:
            source = [iid for iid in self.tree.get_children() if iid in self._marked]
        else:
            source = list(self.tree.selection())
        paths = []
        for iid in source:
            fname = self._fullname(iid)
            if fname != "..":
                p = os.path.join(self.current_path, fname)
                # Skip rows whose file no longer exists (e.g. it was just moved
                # away but the list has not refreshed yet).  This stops a stray
                # click-drag of stale rows from raising a "Drag & Drop – error".
                if os.path.exists(p):
                    paths.append(p)
        return paths

    def focus_set(self):
        self.tree.focus_set()

    # ── Drag-and-drop (requires tkinterdnd2) ──────────────────────────────

    def _setup_dnd(self):
        """Register the treeview as a DnD source AND target."""
        if not _HAS_DND:
            return
        try:
            # Drop target: accept files dragged from Explorer / other apps
            self.tree.drop_target_register(_DND_FILES)
            self.tree.dnd_bind("<<Drop>>",      self._on_dnd_drop)
            self.tree.dnd_bind("<<DropEnter>>", self._on_dnd_enter)
            self.tree.dnd_bind("<<DropLeave>>", self._on_dnd_leave)
            # Drag source: left-button drag sends files to other programs
            self.tree.drag_source_register(1, _DND_FILES)
            self.tree.dnd_bind("<<DragInitCmd>>", self._on_drag_init)
            self.tree.dnd_bind("<<DragEndCmd>>",  self._on_drag_end)
        except Exception as exc:
            _log(f"DnD setup failed for {self.side} panel: {exc}")

    # ── drag-OUT (we are the source) ──────────────────────────────────────

    def _on_drag_init(self, event):
        """Return selected paths when user starts dragging from this panel."""
        # A drag has definitely begun — no slow-click rename may fire now.
        self._cancel_slow_rename()
        paths = self.get_all_selected()
        # ttk.Treeview collapses a multi-row selection to the clicked row on
        # ButtonPress — which happens before this drag starts — so a plain
        # Ctrl/Shift multi-selection would otherwise drag only one file.  When
        # nothing is explicitly marked and the press landed on a row that was
        # part of a bigger selection, rebuild the full list from the snapshot.
        if not self._marked and len(self._drag_sel_snapshot) > 1:
            cur = self.tree.selection()
            if not cur or cur[0] in self._drag_sel_snapshot:
                snap = set(self._drag_sel_snapshot)
                paths = []
                for iid in self.tree.get_children():
                    if iid in snap:
                        fname = self._fullname(iid)
                        if fname != "..":
                            p = os.path.join(self.current_path, fname)
                            if os.path.exists(p):
                                paths.append(p)
        # Never start a drag carrying files that no longer exist — a stray
        # click-drag right after a move would otherwise drop non-existent paths
        # and pop a "Drag & Drop – error".
        paths = [p for p in paths if os.path.exists(p)]
        if not paths:
            return   # cancel drag
        # Mark that we are the active drag source so the drop handler can
        # distinguish internal (panel→panel) from external drops.
        self.manager._dnd_source_side = self.side
        # tkinterdnd2 expects: (action, type, data)
        # Wrap paths in braces so spaces in folder names are handled.
        data = " ".join(f"{{{p}}}" for p in paths)
        return ("copy", _DND_FILES, data)

    def _on_drag_end(self, event):
        """Called when a drag we initiated has ended (dropped or cancelled)."""
        self.manager._dnd_source_side = None

    # ── drag-IN (we are the target) ───────────────────────────────────────

    def _on_dnd_enter(self, event):
        """Highlight panel border while a drag hovers over it."""
        try:
            self.tree.configure(style="DnDHover.Treeview")
        except Exception:
            pass

    def _on_dnd_leave(self, event):
        """Remove hover highlight when drag leaves."""
        try:
            self.tree.configure(style="Treeview")
        except Exception:
            pass

    def _on_dnd_drop(self, event):
        """Files dropped onto this panel – copy or move them here."""
        self._on_dnd_leave(event)   # reset highlight
        if getattr(self, "is_remote", False):
            messagebox.showinfo(
                "Drag & Drop",
                "Drop onto FTP panel is not supported.", parent=self)
            return

        paths = self._dnd_parse_paths(event.data)
        if not paths:
            return

        source_side = getattr(self.manager, "_dnd_source_side", None)
        # One drop consumes the flag.  If a drag ever fails to report its end,
        # the NEXT drop — quite possibly a real one from Explorer — must not
        # inherit a stale "this came from the left panel".
        try:
            self.manager._dnd_source_side = None
        except Exception:
            pass

        # A drop back into the list the drag started in is NOT an operation —
        # it is what an ordinary click looks like when the hand moved a couple
        # of pixels.  Explorer ignores exactly the same gesture.  Doing a copy
        # here meant copying a file on top of itself, and THAT is what raised
        # the "Drag & Drop – error" (very often naming a file another program
        # had open) when all the user wanted was to give this panel the focus.
        if source_side is not None and source_side == self.side:
            return

        # Dropped onto a panel that is INSIDE an archive: add to the archive.
        if self.archive_ctx is not None:
            move = False
            if source_side is not None:                  # panel → panel
                choice = self._dnd_ask_copy_move(len(paths))
                if choice is None:
                    return
                move = (choice == "move")
            self.manager._add_to_archive(self, paths, move=move)
            return

        dest = self.current_path
        try:
            dest_key = os.path.normcase(os.path.abspath(dest))
        except Exception:
            dest_key = os.path.normcase(dest)
        # Same reasoning for anything that already lives in this folder, no
        # matter which window it was dragged from: dropping a file where it
        # already is does nothing.
        staying = []
        for p in paths:
            try:
                parent = os.path.normcase(os.path.dirname(os.path.abspath(p)))
            except Exception:
                parent = ""
            if parent != dest_key:
                staying.append(p)
        if not staying:
            self._flash_panel_status("Already in this folder — nothing to do.")
            return
        paths = staying

        is_internal = (source_side is not None and source_side != self.side)

        if is_internal:
            # Panel → panel drop: ask Copy or Move
            choice = self._dnd_ask_copy_move(len(paths))
            if choice is None:
                return
            move = (choice == "move")
        else:
            # External drop (from Explorer, desktop, etc.): always Copy
            move = False

        # Hand the transfer to the task queue rather than copying on the spot.
        # The queue owns name clashes, locked files, cancel / pause / throttle
        # and the progress display — the old inline shutil loop had none of
        # that, froze the whole window on a big file, and turned every Windows
        # error number into a raw error box.
        self.manager._copy_move_local(paths, dest, move=move)

    def _flash_panel_status(self, message: str, ms: int = 2000):
        """Say something in the status bar without a popup (used where the old
        code showed an error box for a non-event)."""
        try:
            self.manager._flash_status(message, ms)
        except Exception:
            pass

    # ── helpers ───────────────────────────────────────────────────────────

    @staticmethod
    def _dnd_parse_paths(data: str) -> list:
        """Parse tkinterdnd2 path string → list of real paths.
        Handles both {path with spaces} and plain/path formats."""
        if not data:
            return []
        # Extract {…} groups first, then fall back to whitespace-split tokens
        paths = []
        remaining = data
        while True:
            m = _re.search(r'\{([^}]+)\}', remaining)
            if not m:
                break
            paths.append(m.group(1))
            remaining = remaining[:m.start()] + remaining[m.end():]
        # Any remaining tokens (no-space paths)
        for token in remaining.split():
            token = token.strip()
            if token:
                paths.append(token)
        return [p for p in paths if os.path.exists(p)]

    @staticmethod
    def _dnd_ask_copy_move(n: int):
        """Small dialog: returns 'copy', 'move', or None (cancel)."""
        result = [None]
        dlg = tk.Toplevel()
        dlg.title("Drag & Drop")
        dlg.resizable(False, False)
        dlg.grab_set()
        dlg.focus_force()

        noun = f"{n} item(s)" if n > 1 else "1 item"
        ttk.Label(dlg, text=f"What do you want to do with {noun}?",
                  padding=(16, 12, 16, 8)).pack()

        btn_row = ttk.Frame(dlg, padding=(12, 0, 12, 14))
        btn_row.pack()

        def _pick(v):
            result[0] = v
            dlg.destroy()

        ttk.Button(btn_row, text="Copy",   width=12,
                   command=lambda: _pick("copy")).pack(side="left", padx=4)
        ttk.Button(btn_row, text="Move",   width=12,
                   command=lambda: _pick("move")).pack(side="left", padx=4)
        ttk.Button(btn_row, text="Cancel", width=10,
                   command=lambda: _pick(None)).pack(side="left", padx=4)

        dlg.bind("<Escape>", lambda e: _pick(None))
        dlg.wait_window()
        return result[0]

class FTPPanel(ttk.Frame):

    def __init__(self, parent, side, manager: EditorFrame, site: dict):
        super().__init__(parent)
        self.manager   = manager
        self.side      = side
        self.is_remote = True

        self.protocol = (site.get("protocol") or "FTP").upper()
        self.host     = site.get("host", "")
        self.port     = int(site.get("port", 21) or 21)
        self.user     = site.get("user", "")
        self.password = site.get("password", "")
        self.current_path = site.get("remote_path") or "/"

        if self.protocol == "SFTP":
            messagebox.showinfo("Info", "SFTP requires Paramiko. Let us know if you need it added.")
            raise RuntimeError("SFTP not implemented")

        self.ftp = FTP_TLS() if self.protocol == "FTPS" else FTP()
        self.ftp.connect(self.host, self.port, timeout=15)
        self.ftp.login(self.user, self.password)
        if self.protocol == "FTPS":
            self.ftp.prot_p()
        self.ftp.set_pasv(True)
        try:
            self.ftp.cwd(self.current_path)
        except Exception:
            self.current_path = self.ftp.pwd()

        self.tree = ttk.Treeview(
            self, columns=("type", "size", "modified"), selectmode="browse"
        )
        self.tree.heading("#0",       text=self.host, anchor="w")
        self.tree.heading("type",     text="Type",     anchor="w")
        self.tree.heading("size",     text="Size",     anchor="e")
        self.tree.heading("modified", text="Modified", anchor="w")
        self.tree.column("#0",       stretch=True, width=320)
        self.tree.column("type",     width=80,  anchor="w")
        self.tree.column("size",     width=90,  anchor="e")
        self.tree.column("modified", width=140, anchor="w")

        scroll = ttk.Scrollbar(self, orient="vertical", command=self.tree.yview)
        self.tree.configure(yscrollcommand=scroll.set)
        # Scrollbar first so it is never clipped when the panel is narrow.
        scroll.pack(side="right", fill="y")
        self.tree.pack(side="left", fill="both", expand=True)

        self.tree.bind("<Double-1>", self._on_double_click)
        self.tree.bind("<Button-3>", self._on_right_click)
        self.tree.bind("<FocusIn>",  lambda e: manager._activate_side(side, set_focus=False))

        self.refresh()

    def _listdir(self):
        def _mlsd():
            rows = []
            for name, facts in self.ftp.mlsd():
                typ = facts.get("type", "file")
                size = facts.get("size", "")
                mod  = facts.get("modify", "")
                if mod and len(mod) >= 14:
                    mod = f"{mod[0:4]}-{mod[4:6]}-{mod[6:8]} {mod[8:10]}:{mod[10:12]}"
                rows.append((name, typ == "dir", size, mod))
            return rows

        def _nlst():
            rows = []
            for n in self.ftp.nlst():
                if n in (".", ".."):
                    continue
                cur = self.ftp.pwd()
                is_dir = False
                try:
                    self.ftp.cwd(n)
                    is_dir = True
                    self.ftp.cwd(cur)
                except error_perm:
                    pass
                rows.append((n, is_dir, "", ""))
            return rows

        try:
            return _mlsd()
        except Exception:
            return _nlst()

    def refresh(self):
        self.tree.delete(*self.tree.get_children())
        if self.current_path not in ("/", ""):
            self.tree.insert("", "end", text="..", values=("Folder", "", ""))
        rows  = self._listdir()
        dirs  = sorted([r for r in rows if r[1]])
        files = sorted([r for r in rows if not r[1]])
        for name, is_dir, size, mod in dirs + files:
            self.tree.insert("", "end", text=name,
                             values=("Folder" if is_dir else "File", size, mod))

    def _on_double_click(self, event):
        # The row UNDER THE POINTER, not tree.selection() — see the local
        # panel's _on_double_click for why the two drift apart (revBQ).
        item = self.tree.identify_row(event.y) if hasattr(event, "y") else ""
        if not item:
            return "break"
        self.tree.selection_set(item)
        self.tree.focus(item)
        name = self.tree.item(item, "text")
        if name == "..":
            self.go_up()
            return
        vals = self.tree.item(item, "values")
        if vals and vals[0] == "Folder":
            try:
                self.ftp.cwd(name)
                self.current_path = self.ftp.pwd()
                self.refresh()
                self.manager._update_disk_info()
            except Exception as exc:
                messagebox.showerror("FTP error", f"Could not change directory: {exc}")
        else:
            self.manager.view_file()

    def _on_right_click(self, event):
        item = self.tree.identify_row(event.y)
        if item:
            self.tree.selection_set(item)
            self.manager.context_menu.post(event.x_root, event.y_root)

    def change_directory(self, path):
        try:
            self.ftp.cwd(path)
            self.current_path = self.ftp.pwd()
            self.refresh()
            self.manager._update_disk_info()
        except Exception as exc:
            messagebox.showerror("FTP error", f"Could not change directory: {exc}")

    def go_up(self):
        try:
            self.ftp.cwd("..")
            self.current_path = self.ftp.pwd()
            self.refresh()
            self.manager._update_disk_info()
        except Exception as exc:
            messagebox.showerror("FTP error", f"Could not go up: {exc}")

    def go_root(self):
        try:
            self.ftp.cwd("/")
            self.current_path = self.ftp.pwd()
            self.refresh()
            self.manager._update_disk_info()
        except Exception as exc:
            messagebox.showerror("FTP error", f"Could not go to root: {exc}")

    def get_selected(self):
        sel = self.tree.selection()
        if not sel:
            return None
        name = self.tree.item(sel[0], "text")
        if name == "..":
            return None
        vals   = self.tree.item(sel[0], "values")
        is_dir = bool(vals and vals[0] == "Folder")
        full   = self.current_path.rstrip("/") + "/" + name
        return (full, is_dir)

    def download_file(self, remote_path: str, local_path: str):
        with open(local_path, "wb") as fh:
            self.ftp.retrbinary(f"RETR {Path(remote_path).name}", fh.write)

    def upload_file(self, local_path: str):
        with open(local_path, "rb") as fh:
            self.ftp.storbinary(f"STOR {Path(local_path).name}", fh)
        self.refresh()

    def delete_path(self, remote_path: str, is_dir: bool):
        name = Path(remote_path).name
        self.ftp.rmd(name) if is_dir else self.ftp.delete(name)
        self.refresh()

    def mkdir(self, name: str):
        self.ftp.mkd(name)
        self.refresh()

    def rename_path(self, old_path: str, new_name: str):
        self.ftp.rename(Path(old_path).name, new_name)
        self.refresh()

    def focus_set(self):
        self.tree.focus_set()


# ══════════════════════════════════════════════════════════════════════════
#  FTP client window
# ══════════════════════════════════════════════════════════════════════════

class FTPClientWindow(tk.Toplevel):

    def __init__(self, manager: EditorFrame):
        super().__init__(manager)
        self.manager      = manager
        self.ftp          = None
        self.current_remote = "/"
        self.sites        = _load_sites()

        _setup_toplevel(self, "FTP Client", manager)
        self.geometry("960x580")
        self.resizable(True, True)
        # Override Escape so it only closes, not manager
        self.bind("<Escape>", lambda e: self._on_close())

        # ── Top bar ──────────────────────────────────────────────────────
        top = ttk.Frame(self)
        top.pack(fill="x", padx=6, pady=6)

        ttk.Label(top, text="Site:").pack(side="left")
        self.site_var = tk.StringVar()
        self.site_box = ttk.Combobox(top, textvariable=self.site_var, width=40, state="readonly")
        self.site_box.pack(side="left", padx=4)
        self._reload_sites_combo()

        ttk.Button(top, text="New",    command=self.add_site).pack(side="left", padx=2)
        ttk.Button(top, text="Edit",   command=self.edit_site).pack(side="left", padx=2)
        ttk.Button(top, text="Delete", command=self.delete_site).pack(side="left", padx=2)
        ttk.Button(top, text="Connect",command=self.connect).pack(side="left", padx=8)
        ttk.Button(top, text="Open in left panel",
                   command=lambda: self._mount("left")).pack(side="left", padx=8)
        ttk.Button(top, text="Open in right panel",
                   command=lambda: self._mount("right")).pack(side="left", padx=2)

        self.local_label = ttk.Label(
            self, text=f"Local: {manager.get_active_panel().current_path}"
        )
        self.local_label.pack(fill="x", padx=6)

        # ── Remote tree ───────────────────────────────────────────────────
        mid = ttk.Frame(self)
        mid.pack(fill="both", expand=True, padx=6, pady=6)

        self.remote_tree = ttk.Treeview(
            mid, columns=("type", "size", "modified"), selectmode="browse"
        )
        self.remote_tree.heading("#0",       text="Name",     anchor="w")
        self.remote_tree.heading("type",     text="Type",     anchor="w")
        self.remote_tree.heading("size",     text="Size",     anchor="e")
        self.remote_tree.heading("modified", text="Modified", anchor="w")
        self.remote_tree.column("#0",       width=420, anchor="w")
        self.remote_tree.column("type",     width=80,  anchor="w")
        self.remote_tree.column("size",     width=90,  anchor="e")
        self.remote_tree.column("modified", width=140, anchor="w")
        self.remote_tree.pack(fill="both", expand=True, side="left")
        self.remote_tree.bind("<Double-1>", self._on_remote_double)

        scroll = ttk.Scrollbar(mid, orient="vertical", command=self.remote_tree.yview)
        self.remote_tree.configure(yscrollcommand=scroll.set)
        scroll.pack(side="right", fill="y")

        # ── Button bar ────────────────────────────────────────────────────
        btns = ttk.Frame(self)
        btns.pack(fill="x", padx=6, pady=6)
        ttk.Button(btns, text="Up",          command=self._remote_up).pack(side="left", padx=2)
        ttk.Button(btns, text="Refresh",     command=self._list_remote).pack(side="left", padx=2)
        ttk.Button(btns, text="Download",    command=self._download_selected).pack(side="left", padx=8)
        ttk.Button(btns, text="Upload…",     command=self._upload_file).pack(side="left", padx=2)
        ttk.Button(btns, text="New folder",  command=self._remote_mkdir).pack(side="left", padx=2)
        ttk.Button(btns, text="Rename",      command=self._remote_rename).pack(side="left", padx=2)
        ttk.Button(btns, text="Delete",      command=self._remote_delete).pack(side="left", padx=2)

        self.status = ttk.Label(self, text="Not connected", relief="sunken")
        self.status.pack(fill="x")

        self.protocol("WM_DELETE_WINDOW", self._on_close)

    # ── Site management ───────────────────────────────────────────────────

    def _reload_sites_combo(self):
        names = [s.get("name", "") for s in self.sites]
        self.site_box["values"] = names
        if names:
            self.site_box.current(0)

    def add_site(self):
        data = self._site_form()
        if data:
            self.sites.append(data)
            _save_sites(self.sites)
            self._reload_sites_combo()

    def edit_site(self):
        idx = self.site_box.current()
        if idx < 0:
            return
        data = self._site_form(self.sites[idx])
        if data:
            self.sites[idx] = data
            _save_sites(self.sites)
            self._reload_sites_combo()

    def delete_site(self):
        idx = self.site_box.current()
        if idx < 0:
            return
        if _ask_yes_no("Confirm", "Delete the selected site?"):
            del self.sites[idx]
            _save_sites(self.sites)
            self._reload_sites_combo()

    def _site_form(self, initial=None):
        win = tk.Toplevel(self)
        _setup_toplevel(win, "FTP Site", self)
        win.resizable(False, False)

        fields = [
            ("Name",                    "name"),
            ("Protocol (FTP/FTPS/SFTP)","protocol"),
            ("Host",                    "host"),
            ("Port",                    "port"),
            ("Username",                "user"),
            ("Password",                "password"),
            ("Remote path",             "remote_path"),
            ("Local path",              "local_path"),
        ]
        entries = {}
        for i, (label, key) in enumerate(fields):
            ttk.Label(win, text=label).grid(row=i, column=0, sticky="e", padx=6, pady=4)
            if key == "protocol":
                e = ttk.Combobox(win, values=["FTP", "FTPS", "SFTP"], state="readonly")
                e.set((initial or {}).get(key, "FTP"))
            else:
                show = "*" if key == "password" else None
                # tk.Entry, not ttk.Entry: only the classic widget can have a
                # steady caret (see _no_blink).
                e    = _mk_entry(win, show=show) if show else _mk_entry(win)
                if initial and initial.get(key) is not None and key != "password":
                    e.insert(0, str(initial.get(key, "")))
            e.grid(row=i, column=1, sticky="we", padx=6, pady=4)
            entries[key] = e
        win.columnconfigure(1, weight=1)

        result = {}

        def _ok():
            try:
                result["name"]        = entries["name"].get().strip()
                result["protocol"]    = entries["protocol"].get().strip() or "FTP"
                result["host"]        = entries["host"].get().strip()
                result["port"]        = int(entries["port"].get().strip() or
                                            (990 if result["protocol"] == "FTPS" else 21))
                result["user"]        = entries["user"].get().strip()
                result["password"]    = entries["password"].get()
                result["remote_path"] = entries["remote_path"].get().strip() or "/"
                result["local_path"]  = entries["local_path"].get().strip()
                if not result["name"] or not result["host"]:
                    raise ValueError("Name and host are required.")
            except Exception as exc:
                messagebox.showerror("Error", f"Invalid fields: {exc}")
                return
            win.destroy()

        def _cancel():
            result.clear()
            win.destroy()

        frm = ttk.Frame(win)
        frm.grid(row=len(fields), column=0, columnspan=2, sticky="e", pady=6, padx=6)
        ttk.Button(frm, text="Cancel", command=_cancel).pack(side="right", padx=4)
        ttk.Button(frm, text="OK",     command=_ok).pack(side="right", padx=4)

        win.wait_window()
        return result or None

    # ── Connection ────────────────────────────────────────────────────────

    def connect(self):
        idx = self.site_box.current()
        if idx < 0:
            messagebox.showwarning("Info", "Please select a site first.")
            return
        site     = self.sites[idx]
        proto    = (site.get("protocol") or "FTP").upper()
        host     = site.get("host", "")
        port     = int(site.get("port", 21) or 21)
        user     = site.get("user", "")
        password = site.get("password", "")
        remote   = site.get("remote_path") or "/"
        local    = site.get("local_path") or self.manager.get_active_panel().current_path

        try:
            if self.ftp:
                try:
                    self.ftp.quit()
                except Exception:
                    pass
                self.ftp = None

            if proto == "FTPS":
                ftp = FTP_TLS()
                ftp.connect(host, port, timeout=15)
                ftp.login(user, password)
                ftp.prot_p()
                ftp.set_pasv(True)
            elif proto == "FTP":
                ftp = FTP()
                ftp.connect(host, port, timeout=15)
                ftp.login(user, password)
                ftp.set_pasv(True)
            else:
                messagebox.showinfo("Info", "SFTP requires Paramiko. Let us know if you need it.")
                return

            ftp.cwd(remote)
            self.ftp = ftp
            self.current_remote = self.ftp.pwd()
            self.local_label.config(text=f"Local: {local}")
            self.status.config(text=f"Connected: {host}:{port}  |  {self.current_remote}")
            self._list_remote()
            _log(f"FTP connected to {host}:{port}")
        except Exception as exc:
            self.status.config(text="Not connected")
            messagebox.showerror("FTP error", f"Could not connect: {exc}")

    # ── Remote listing ────────────────────────────────────────────────────

    def _list_remote(self):
        self.remote_tree.delete(*self.remote_tree.get_children())
        if not self.ftp:
            return
        if self.current_remote not in ("/", ""):
            self.remote_tree.insert("", "end", text="..", values=("Folder", "", ""))

        def _mlsd():
            rows = []
            for name, facts in self.ftp.mlsd():
                typ  = facts.get("type", "file")
                size = facts.get("size", "")
                mod  = facts.get("modify", "")
                if mod and len(mod) >= 14:
                    mod = f"{mod[0:4]}-{mod[4:6]}-{mod[6:8]} {mod[8:10]}:{mod[10:12]}"
                rows.append((name, "Folder" if typ == "dir" else "File", size, mod))
            return rows

        def _nlst():
            rows = []
            cur  = self.ftp.pwd()
            for n in self.ftp.nlst():
                if n in (".", ".."):
                    continue
                is_dir = False
                try:
                    self.ftp.cwd(n)
                    is_dir = True
                    self.ftp.cwd(cur)
                except error_perm:
                    pass
                rows.append((n, "Folder" if is_dir else "File", "", ""))
            return rows

        try:
            rows = _mlsd()
        except Exception:
            rows = _nlst()

        dirs  = [r for r in rows if r[1] == "Folder"]
        files = [r for r in rows if r[1] != "Folder"]
        for name, typ, size, mod in sorted(dirs) + sorted(files):
            self.remote_tree.insert("", "end", text=name, values=(typ, size, mod))

    def _on_remote_double(self, event):
        # The row UNDER THE POINTER, not remote_tree.selection() (revBQ).
        item = self.remote_tree.identify_row(event.y) if hasattr(event, "y") else ""
        if not item:
            return "break"
        self.remote_tree.selection_set(item)
        self.remote_tree.focus(item)
        name = self.remote_tree.item(item, "text")
        if name == "..":
            self._remote_up()
            return
        vals = self.remote_tree.item(item, "values")
        if vals and vals[0] == "Folder":
            try:
                self.ftp.cwd(name)
                self.current_remote = self.ftp.pwd()
                self.status.config(text=f"Connected  |  {self.current_remote}")
                self._list_remote()
            except Exception as exc:
                messagebox.showerror("FTP error", f"Could not change directory: {exc}")
        else:
            self._download_selected()

    def _remote_up(self):
        if not self.ftp:
            return
        try:
            self.ftp.cwd("..")
            self.current_remote = self.ftp.pwd()
            self.status.config(text=f"Connected  |  {self.current_remote}")
            self._list_remote()
        except Exception as exc:
            messagebox.showerror("FTP error", f"Could not go up: {exc}")

    def _local_dir(self):
        txt = self.local_label.cget("text")
        return (txt.split("Local:", 1)[1].strip()
                if "Local:" in txt
                else self.manager.get_active_panel().current_path)

    def _download_selected(self):
        if not self.ftp:
            return
        sel = self.remote_tree.selection()
        if not sel:
            return
        name = self.remote_tree.item(sel[0], "text")
        vals = self.remote_tree.item(sel[0], "values")
        if vals and vals[0] == "Folder":
            messagebox.showinfo("Info", "Folder download is not supported in this view.")
            return
        local_dir = self.manager.choose_save_path(self._local_dir(), name)
        os.makedirs(local_dir, exist_ok=True)
        dest = os.path.join(local_dir, name)

        # Try to get remote file size for a determinate bar
        total_bytes = 0
        try:
            total_bytes = self.ftp.size(name) or 0
        except Exception:
            pass

        prog = _ProgressDialog(self.manager, f"Downloading {name}…",
                               total=max(1, total_bytes), cancelable=True)
        if total_bytes == 0:
            prog._pb.configure(mode="indeterminate")
            prog._pb.start(12)

        def _worker():
            received = [0]
            def _cb(data):
                f.write(data)
                received[0] += len(data)
                if total_bytes > 0:
                    prog.post("progress", received[0], total_bytes, name)
            try:
                with open(dest, "wb") as f:
                    self.ftp.retrbinary(f"RETR {name}", _cb)
                self.manager.refresh_panels()
                self.manager.after(0, lambda: messagebox.showinfo(
                    "Done", f"Downloaded: {dest}"))
            except Exception as exc:
                self.manager.after(0, lambda e=exc: messagebox.showerror(
                    "FTP error", f"Download failed: {e}"))
            prog.post("done")

        threading.Thread(target=_worker, daemon=True).start()

    def _upload_file(self):
        path = filedialog.askopenfilename(
            title="Select file to upload", initialdir=self._local_dir()
        )
        if not path:
            return

        name        = os.path.basename(path)
        total_bytes = 0
        try:
            total_bytes = os.path.getsize(path)
        except Exception:
            pass

        prog = _ProgressDialog(self.manager, f"Uploading {name}…",
                               total=max(1, total_bytes), cancelable=False)

        def _worker():
            sent = [0]
            def _cb(data):
                sent[0] += len(data)
                if total_bytes > 0:
                    prog.post("progress", sent[0], total_bytes, name)
            try:
                with open(path, "rb") as fh:
                    self.ftp.storbinary(f"STOR {name}", fh,
                                        callback=_cb, blocksize=65536)
                self.after(0, self._list_remote)
                self.manager.after(0, lambda: messagebox.showinfo(
                    "Done", f"Uploaded: {name}"))
            except Exception as exc:
                self.manager.after(0, lambda e=exc: messagebox.showerror(
                    "FTP error", f"Upload failed: {e}"))
            prog.post("done")

        threading.Thread(target=_worker, daemon=True).start()

    def _remote_mkdir(self):
        if not self.ftp:
            return
        name = _ask_text(self, "New folder (FTP)", "Folder name:")
        if not name:
            return
        try:
            self.ftp.mkd(name)
            self._list_remote()
        except Exception as exc:
            messagebox.showerror("FTP error", f"Could not create folder: {exc}")

    def _remote_delete(self):
        if not self.ftp:
            return
        sel = self.remote_tree.selection()
        if not sel:
            return
        name = self.remote_tree.item(sel[0], "text")
        vals = self.remote_tree.item(sel[0], "values")
        try:
            self.ftp.rmd(name) if (vals and vals[0] == "Folder") else self.ftp.delete(name)
            self._list_remote()
        except Exception as exc:
            messagebox.showerror("FTP error", f"Could not delete: {exc}")

    def _remote_rename(self):
        if not self.ftp:
            return
        sel = self.remote_tree.selection()
        if not sel:
            return
        old     = self.remote_tree.item(sel[0], "text")
        new_name = _ask_text(self, "Rename (FTP)", "New name:", initial=old)
        if not new_name or new_name == old:
            return
        try:
            self.ftp.rename(old, new_name)
            self._list_remote()
        except Exception as exc:
            messagebox.showerror("FTP error", f"Could not rename: {exc}")

    def _mount(self, side: str):
        idx = self.site_box.current()
        if idx < 0:
            messagebox.showwarning("Info", "Please select a site first.")
            return
        site = self.sites[idx]
        try:
            self.manager.mount_ftp_panel(side, site)
            label = "left" if side == "left" else "right"
            messagebox.showinfo("Mounted", f"Opened in the {label} panel.")
        except Exception as exc:
            messagebox.showerror("Error", f"Could not mount FTP panel: {exc}")

    def _on_close(self):
        try:
            if self.ftp:
                self.ftp.quit()
        except Exception:
            pass
        self.destroy()


# ══════════════════════════════════════════════════════════════════════════
#  DEL 10 — Icon helper
# ══════════════════════════════════════════════════════════════════════════

def _set_window_icon(root: tk.Tk) -> None:
    """Set the window icon via both tkinter and Win32 WM_SETICON (Windows only)."""
    if platform.system() != "Windows":
        return
    # Works both as a .py and as a frozen .exe — always relative to the program
    if getattr(sys, "frozen", False):
        prog_name = Path(sys.executable).stem
    else:
        prog_name = Path(__file__).stem        # "File_manager"
    ico_path = APP_ROOT / "Icons" / f"{prog_name}.ico"
    if not ico_path.is_file():
        return

    # Channel 1: tkinter API
    try:
        root.iconbitmap(str(ico_path))
    except Exception:
        pass

    # Channel 2: Win32 WM_SETICON (covers taskbar + Alt-Tab)
    try:
        user32          = ctypes.windll.user32
        LR_LOADFROMFILE = 0x0010
        LR_DEFAULTSIZE  = 0x0040
        IMAGE_ICON      = 1
        WM_SETICON      = 0x0080
        hwnd = user32.FindWindowW(None, root.title())
        if not hwnd:
            return
        hbig = user32.LoadImageW(None, str(ico_path), IMAGE_ICON,  0,  0,
                                 LR_LOADFROMFILE | LR_DEFAULTSIZE)
        hsml = user32.LoadImageW(None, str(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


# ══════════════════════════════════════════════════════════════════════════
#  Network utilities  (ported from NetRadar – LAN scanner + drive favorites)
# ══════════════════════════════════════════════════════════════════════════

_NET_PORT_LABELS = {
    21: "FTP",  22: "SSH",    23: "Telnet",   25: "SMTP",
    53: "DNS",  80: "HTTP",  110: "POP3",    135: "RPC",
   139: "NetBIOS", 143: "IMAP", 443: "HTTPS", 445: "SMB",
   993: "IMAPS", 995: "POP3S", 1433: "MSSQL", 3306: "MySQL",
  3389: "RDP",  5900: "VNC",  5985: "WinRM", 8080: "HTTP-Alt",
}


def _net_encode_pw(pw: str) -> str:
    return base64.b64encode(pw.encode("utf-8")).decode("ascii") if pw else ""


def _net_decode_pw(enc: str) -> str:
    try:
        return base64.b64decode(enc.encode("ascii")).decode("utf-8") if enc else ""
    except Exception:
        return ""


def _net_load_favorites() -> list:
    try:
        if NET_FAVORITES_PATH.exists():
            return json.loads(NET_FAVORITES_PATH.read_text(encoding="utf-8"))
    except Exception:
        pass
    return []


def _net_save_favorites(favs: list):
    try:
        NET_FAVORITES_PATH.write_text(json.dumps(favs, indent=2), encoding="utf-8")
    except Exception:
        pass


# ── Saved sign-ins that heal themselves (2026-11-03) ─────────────────────────
# A computer on the network can answer and still show NO hard drives, because
# this Windows has no sign-in for it (typical after a Windows reinstall: the
# Credential Manager starts empty).  A sign-in typed once is therefore kept in
# TWO places: Windows' Credential Manager (so every program sees it) and
# Helpfiles\redigerare\net_logins.json (so File manager can put it back by
# itself if Windows loses it).  The password is only base64-obscured, the same
# as the saved favourites - it is not encryption.
NET_LOGINS_PATH = HELP_DIR / "net_logins.json"
_NET_SYS32 = os.path.join(os.environ.get("SystemRoot", r"C:\Windows"), "System32")
_NET_RESTORED: set = set()          # hosts whose saved sign-in was re-applied this run


class NetNeedsSignIn(RuntimeError):
    """The computer answers on the network but wants a user/password first."""


def _net_host_key(host: str) -> str:
    return (host or "").strip().strip("\\/").lower()


def _net_host_of_unc(path: str) -> str:
    p = (path or "").strip()
    if not p.startswith("\\\\"):
        return ""
    return p[2:].split("\\", 1)[0]


def _net_logins_load() -> dict:
    try:
        if NET_LOGINS_PATH.exists():
            data = json.loads(NET_LOGINS_PATH.read_text(encoding="utf-8"))
            if isinstance(data, dict):
                return data
    except Exception:
        pass
    return {}


def _net_logins_save(data: dict):
    try:
        NET_LOGINS_PATH.write_text(json.dumps(data, indent=2), encoding="utf-8")
    except Exception as exc:
        _log(f"Could not save net_logins.json: {exc}")


def _net_port_open(host: str, port: int = 445, timeout: float = 1.5) -> bool:
    """True if the computer answers on the SMB port (it is there, whatever
    Windows says about the share names)."""
    try:
        with socket.create_connection((host, port), timeout=timeout):
            return True
    except Exception:
        return False


def _net_run_sys(exe: str, args: list, timeout: int = 15):
    """Run a Windows tool by its full path (never by bare name)."""
    # stdin is closed on purpose: without it `net use` waits for a typed user
    # name on a hidden console and the call just hangs until the timeout.
    return subprocess.run([os.path.join(_NET_SYS32, exe)] + args,
                          capture_output=True, text=True, errors="replace",
                          stdin=subprocess.DEVNULL,
                          timeout=timeout, **_no_window_kwargs())


def _net_apply_login(host: str, user: str, pw: str, session: bool = True) -> bool:
    """Put the sign-in into Windows: Credential Manager entry (+ an IPC$
    session right now when *session*).  True if Windows accepted it."""
    host = host.strip().strip("\\/")
    if not host or not user:
        return False
    ok = True
    try:
        r = _net_run_sys("cmdkey.exe", [f"/add:{host}", f"/user:{user}",
                                        f"/pass:{pw}"], timeout=10)
        ok = (r.returncode == 0)
    except Exception as exc:
        _log(f"cmdkey failed for {host}: {exc}")
        ok = False
    if session:
        try:
            _net_run_sys("net.exe", ["use", f"\\\\{host}\\IPC$", "/delete", "/y"], 10)
            args = ["use", f"\\\\{host}\\IPC$"]
            if pw:
                args.append(pw)
            args.append(f"/user:{user}")
            r = _net_run_sys("net.exe", args, timeout=20)
            ok = (r.returncode == 0)
        except Exception as exc:
            _log(f"net use IPC$ failed for {host}: {exc}")
            ok = False
    return ok


def _net_sign_in(host: str, user: str, pw: str, remember: bool = True):
    """Sign in to *host* with a typed user/password.  Returns (ok, message).
    When it works and *remember* is set, the sign-in is saved for next time."""
    host = host.strip().strip("\\/")
    user = user.strip()
    if not host or not user:
        return False, "Enter the computer and a user name."
    if not _net_apply_login(host, user, pw, session=True):
        # The session failed - undo the credential so a wrong password is not kept.
        try:
            _net_run_sys("cmdkey.exe", [f"/delete:{host}"], 10)
        except Exception:
            pass
        return False, ("Windows refused that user/password for "
                       f"{host}.  Check the name and password on that computer.")
    if remember:
        logins = _net_logins_load()
        logins[_net_host_key(host)] = {"host": host, "user": user,
                                       "_pw": _net_encode_pw(pw)}
        _net_logins_save(logins)
    _NET_RESTORED.add(_net_host_key(host))
    return True, "Signed in."


def _net_restore_login(host: str, force: bool = False) -> bool:
    """If File manager has a saved sign-in for *host*, put it back into Windows
    (once per run unless *force*).  Cheap, and it is what makes the computer
    show its drives again after Windows forgot the sign-in."""
    key = _net_host_key(host)
    if not key or (key in _NET_RESTORED and not force):
        return False
    entry = _net_logins_load().get(key)
    if not entry or not entry.get("user"):
        return False
    _NET_RESTORED.add(key)
    return _net_apply_login(entry.get("host", host), entry["user"],
                            _net_decode_pw(entry.get("_pw", "")), session=True)


def _net_restore_all_logins():
    """At start-up: refill Windows' Credential Manager from the saved list.
    No network traffic (cmdkey only), so it is instant and works offline."""
    try:
        for entry in _net_logins_load().values():
            if entry.get("host") and entry.get("user"):
                _net_apply_login(entry["host"], entry["user"],
                                 _net_decode_pw(entry.get("_pw", "")),
                                 session=False)
    except Exception as exc:
        _log(f"Restoring saved network sign-ins failed: {exc}")


def _net_get_local_interfaces() -> list:
    interfaces = []
    try:
        out = subprocess.check_output(
            ["ipconfig", "/all"], text=True, errors="ignore",
            creationflags=subprocess.CREATE_NO_WINDOW,
        )
        current_name = "Unknown"
        ip = mask = ""
        for raw_line in out.splitlines():
            line = raw_line.rstrip()
            if line and line[0] not in (" ", "\t"):
                if ip and mask and not ip.startswith("169.254"):
                    try:
                        net = ipaddress.IPv4Network(f"{ip}/{mask}", strict=False)
                        interfaces.append({"name": current_name.strip(": "),
                                           "ip": ip, "mask": mask, "cidr": str(net)})
                    except Exception:
                        pass
                ip = mask = ""
                current_name = line.strip(": \t")
            else:
                s = line.strip()
                if s.lower().startswith("ipv4 address") and ":" in s:
                    ip = s.split(":")[-1].strip().split("(")[0].strip()
                elif s.lower().startswith("subnet mask") and ":" in s:
                    mask = s.split(":")[-1].strip()
        if ip and mask and not ip.startswith("169.254"):
            try:
                net = ipaddress.IPv4Network(f"{ip}/{mask}", strict=False)
                interfaces.append({"name": current_name.strip(": "),
                                   "ip": ip, "mask": mask, "cidr": str(net)})
            except Exception:
                pass
    except Exception:
        pass
    if not interfaces:
        try:
            s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
            s.connect(("8.8.8.8", 80))
            ip = s.getsockname()[0]
            s.close()
            interfaces.append({"name": "Default", "ip": ip,
                               "mask": "255.255.255.0",
                               "cidr": f"{ip.rsplit('.', 1)[0]}.0/24"})
        except Exception:
            pass
    return interfaces


def _net_ping(ip: str, timeout: float = 0.8) -> bool:
    try:
        ms = max(200, int(timeout * 1000))
        r  = subprocess.run(
            ["ping", "-n", "1", "-w", str(ms), ip],
            capture_output=True, text=True,
            creationflags=subprocess.CREATE_NO_WINDOW,
            timeout=timeout + 2.0,
        )
        return r.returncode == 0
    except Exception:
        return False


def _net_get_arp() -> dict:
    arp = {}
    try:
        out = subprocess.check_output(
            ["arp", "-a"], text=True, errors="ignore",
            creationflags=subprocess.CREATE_NO_WINDOW,
        )
        for line in out.splitlines():
            parts = line.split()
            if len(parts) >= 3:
                ip_s = parts[0].strip()
                mac_s = parts[1].strip()
                if ("-" in mac_s or ":" in mac_s) and len(mac_s) >= 11:
                    try:
                        ipaddress.ip_address(ip_s)
                        arp[ip_s] = mac_s.upper()
                    except Exception:
                        pass
    except Exception:
        pass
    return arp


def _net_resolve(ip: str, timeout: float = 1.5) -> str:
    old = socket.getdefaulttimeout()
    try:
        socket.setdefaulttimeout(timeout)
        host, _, _ = socket.gethostbyaddr(ip)
        return host
    except Exception:
        return ""
    finally:
        socket.setdefaulttimeout(old)


def _net_netbios(ip: str) -> str:
    try:
        out = subprocess.check_output(
            ["nbtstat", "-A", ip], text=True, errors="ignore",
            creationflags=subprocess.CREATE_NO_WINDOW, timeout=5,
        )
        for line in out.splitlines():
            s = line.strip()
            if "<00>" in s and "UNIQUE" in s.upper():
                return s.split()[0].strip()
    except Exception:
        pass
    return ""


def _net_check_ports(ip: str, ports: list, timeout: float = 0.5) -> list:
    open_ports = []
    for port in ports:
        try:
            with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
                s.settimeout(timeout)
                if s.connect_ex((ip, port)) == 0:
                    open_ports.append(port)
        except Exception:
            pass
    return open_ports


def _net_fmt_ports(open_ports: list) -> str:
    parts = []
    for p in sorted(open_ports):
        lbl = _NET_PORT_LABELS.get(p, "")
        parts.append(f"{p}/{lbl}" if lbl else str(p))
    return "  ".join(parts)


def _net_get_drive_info():
    import string as _str
    used = set()
    for letter in _str.ascii_uppercase:
        if os.path.exists(f"{letter}:\\"):
            used.add(letter.upper())
    mapped = []
    try:
        out = subprocess.check_output(
            ["net", "use"], text=True, errors="ignore",
            creationflags=subprocess.CREATE_NO_WINDOW,
        )
        for line in out.splitlines():
            parts = line.split()
            for i, p in enumerate(parts):
                if len(p) == 2 and p[1] == ":" and p[0].isalpha():
                    letter = p[0].upper()
                    used.add(letter)
                    unc = parts[i + 1] if i + 1 < len(parts) else ""
                    if unc.startswith("\\\\"):
                        mapped.append((f"{letter}:", unc))
                    break
    except Exception:
        pass
    available = [f"{l}:" for l in _str.ascii_uppercase[3:] if l not in used]
    return available, mapped


# `net use` spawns a process and can stall on a sick network, and the drive
# menu asks for it every time it opens.  A few seconds of cache keeps Alt+F1
# instant without ever showing stale information for long.
_NET_DRIVES_CACHE = {"when": 0.0, "value": ([], [])}


def _net_get_drive_info_cached(max_age: float = 5.0):
    now = _time.monotonic()
    if now - _NET_DRIVES_CACHE["when"] > max_age:
        try:
            _NET_DRIVES_CACHE["value"] = _net_get_drive_info()
        except Exception:
            _NET_DRIVES_CACHE["value"] = ([], [])
        _NET_DRIVES_CACHE["when"] = now
    return _NET_DRIVES_CACHE["value"]


def _net_connect_favorite(fav: dict, status_cb=None):
    """Connect one network drive favorite in a background thread.
    status_cb(msg, ok) is called on completion."""
    letter = fav.get("letter", "").strip()
    path   = fav.get("path",   "").strip()
    user   = fav.get("user",   "").strip()
    pw     = _net_decode_pw(fav.get("_pw", ""))

    if not letter or not path:
        if status_cb:
            status_cb("Missing drive letter or path", False)
        return

    def _run():
        if not user:
            # No sign-in on the favourite itself: use the one File manager saved
            # for this computer (puts it back into Windows if Windows lost it).
            _net_restore_login(_net_host_of_unc(path))
        try:
            _net_run_sys("net.exe", ["use", letter, "/delete", "/y"], 15)
        except Exception:
            pass
        cmd = ["use", letter, path, "/persistent:yes"]
        if user:
            cmd += [f"/user:{user}"]
            if pw:
                cmd += [pw]
        try:
            # Full path + closed stdin (2026-11-21): a favourite without a sign-in
            # used to make `net use` wait for typing on a hidden console.
            r   = _net_run_sys("net.exe", cmd, 45)
            ok  = r.returncode == 0
            out = (r.stdout + r.stderr).strip()
            msg = f"✔  {letter} connected" if ok else f"✘  {out or 'failed'}"
        except Exception as exc:
            ok  = False
            msg = f"✘  {exc}"
        _log(f"Network drive: {letter} → {path}  {'OK' if ok else 'FAIL'}")
        if status_cb:
            try:
                status_cb(msg, ok)
            except Exception:
                pass

    threading.Thread(target=_run, daemon=True).start()


class _NetScanEngine:
    """Three-phase LAN scanner: ping sweep → ARP enrichment → DNS/NetBIOS/ports."""

    def __init__(self, subnet, timeout, max_threads,
                 do_dns, do_nbt, do_ports, port_list,
                 on_host, on_progress, on_done):
        self.subnet      = subnet
        self.timeout     = timeout
        self.max_threads = max_threads
        self.do_dns      = do_dns
        self.do_nbt      = do_nbt
        self.do_ports    = do_ports
        self.port_list   = port_list
        self.on_host     = on_host
        self.on_progress = on_progress
        self.on_done     = on_done
        self._stop       = threading.Event()

    def start(self):
        threading.Thread(target=self._run, daemon=True).start()

    def stop(self):
        self._stop.set()

    def _run(self):
        try:
            net   = ipaddress.IPv4Network(self.subnet, strict=False)
            hosts = list(net.hosts())
            total = len(hosts)
            done  = 0
            alive = []

            def _ping_one(ip):
                return str(ip), _net_ping(str(ip), self.timeout)

            with concurrent.futures.ThreadPoolExecutor(
                    max_workers=self.max_threads) as ex:
                futs = {ex.submit(_ping_one, ip): ip for ip in hosts}
                for fut in concurrent.futures.as_completed(futs):
                    if self._stop.is_set():
                        break
                    done += 1
                    ip, up = fut.result()
                    if up:
                        alive.append(ip)
                    self.on_progress(done, total)

            arp   = _net_get_arp()
            total3 = len(alive)
            done3  = 0

            def _enrich(ip):
                h = {"ip": ip, "hostname": "", "netbios": "",
                     "mac": arp.get(ip, ""), "ports": [],
                     "ports_str": "", "status": "Online"}
                if self.do_dns:
                    h["hostname"]  = _net_resolve(ip, self.timeout)
                if self.do_nbt:
                    h["netbios"]   = _net_netbios(ip)
                if self.do_ports:
                    h["ports"]     = _net_check_ports(ip, self.port_list)
                    h["ports_str"] = _net_fmt_ports(h["ports"])
                return h

            with concurrent.futures.ThreadPoolExecutor(
                    max_workers=min(32, self.max_threads)) as ex:
                futs3 = {ex.submit(_enrich, ip): ip for ip in alive}
                for fut in concurrent.futures.as_completed(futs3):
                    if self._stop.is_set():
                        break
                    done3 += 1
                    self.on_progress(total - total3 + done3, total)
                    try:
                        self.on_host(fut.result())
                    except Exception:
                        pass
        except Exception as exc:
            _log(f"NetScan error: {exc}")
        finally:
            self.on_done()


# ══════════════════════════════════════════════════════════════════════════
#  Network window  (LAN scanner + network drive favorites)
# ══════════════════════════════════════════════════════════════════════════

class NetworkWindow(tk.Toplevel):
    """Floating window with two tabs: Scanner and Favorites."""

    def __init__(self, manager: "EditorFrame", tab: str = "scan"):
        super().__init__(manager)
        self.manager    = manager
        self._scanner   = None
        self._scanning  = False
        self._favorites = _net_load_favorites()

        _setup_toplevel(self, "Network", manager)
        self.geometry("940x600")
        self.resizable(True, True)
        self.bind("<Escape>", lambda e: self.destroy())

        self._nb = ttk.Notebook(self)
        self._nb.pack(fill="both", expand=True, padx=4, pady=4)

        self._tab_scan = ttk.Frame(self._nb)
        self._tab_fav  = ttk.Frame(self._nb)
        self._nb.add(self._tab_scan, text="  Scanner  ")
        self._nb.add(self._tab_fav,  text="  ★ Favorites  ")

        self._build_scan_tab()
        self._build_fav_tab()

        if tab == "fav":
            self._nb.select(self._tab_fav)

    # ── helpers ────────────────────────────────────────────────────────────

    @staticmethod
    def _nb_entry(parent, textvariable=None, width=20, **kw):
        """tk.Entry with no-blink cursor, always."""
        kw.update(insertofftime=0, insertontime=9999999)
        if textvariable:
            kw["textvariable"] = textvariable
        kw["width"] = width
        return tk.Entry(parent, **kw)

    # ── Scanner tab ────────────────────────────────────────────────────────

    def _build_scan_tab(self):
        tab = self._tab_scan

        # Row 1 – subnet / timeout / threads / checkboxes
        r1 = ttk.Frame(tab)
        r1.pack(fill="x", padx=6, pady=(6, 2))

        ttk.Label(r1, text="Subnet:").pack(side="left")
        self._var_subnet = tk.StringVar()
        self._nb_entry(r1, textvariable=self._var_subnet, width=20).pack(
            side="left", padx=(4, 12))

        ttk.Label(r1, text="Timeout s:").pack(side="left")
        self._var_timeout = tk.StringVar(value="0.8")
        self._nb_entry(r1, textvariable=self._var_timeout, width=5).pack(
            side="left", padx=(4, 12))

        ttk.Label(r1, text="Threads:").pack(side="left")
        self._var_threads = tk.StringVar(value="128")
        self._nb_entry(r1, textvariable=self._var_threads, width=5).pack(
            side="left", padx=(4, 12))

        self._var_dns   = tk.BooleanVar(value=True)
        self._var_nbt   = tk.BooleanVar(value=True)
        self._var_ports = tk.BooleanVar(value=True)
        for var, txt in [(self._var_dns,   "Resolve DNS"),
                         (self._var_nbt,   "NetBIOS names"),
                         (self._var_ports, "Check ports")]:
            ttk.Checkbutton(r1, text=txt, variable=var).pack(side="left", padx=4)

        # Row 2 – ports / action buttons
        r2 = ttk.Frame(tab)
        r2.pack(fill="x", padx=6, pady=(0, 4))

        ttk.Label(r2, text="Ports:").pack(side="left")
        self._var_portlist = tk.StringVar(value="22,80,135,139,443,445,3389,5985")
        self._nb_entry(r2, textvariable=self._var_portlist, width=36).pack(
            side="left", padx=(4, 12))

        self._btn_scan = ttk.Button(r2, text="▶  Scan",
                                    command=self._start_scan, width=12)
        self._btn_scan.pack(side="left", padx=2)
        self._btn_stop = ttk.Button(r2, text="■  Stop",
                                    command=self._stop_scan, width=10,
                                    state="disabled")
        self._btn_stop.pack(side="left", padx=2)
        ttk.Button(r2, text="ARP Quick-Scan",
                   command=self._arp_scan, width=16).pack(side="left", padx=8)
        ttk.Button(r2, text="Clear",
                   command=self._clear_scan, width=8).pack(side="right", padx=2)

        # Progress bar
        pr = ttk.Frame(tab)
        pr.pack(fill="x", padx=6, pady=(0, 2))
        self._prog_var = tk.DoubleVar(value=0)
        ttk.Progressbar(pr, variable=self._prog_var, maximum=100).pack(
            side="left", fill="x", expand=True)
        self._lbl_prog = ttk.Label(pr, text="Ready", width=32, anchor="w")
        self._lbl_prog.pack(side="left", padx=8)

        # Adapter info
        self._lbl_iface = ttk.Label(tab, text="Detecting adapters …", anchor="w")
        self._lbl_iface.pack(fill="x", padx=6, pady=(0, 2))

        # Results treeview
        cols = ("ip", "hostname", "netbios", "mac", "ports", "status")
        self._scan_tree = ttk.Treeview(
            tab, columns=cols, show="headings", selectmode="browse")
        for col, hdr, w in [
            ("ip",       "IP Address",  120),
            ("hostname", "Hostname",    170),
            ("netbios",  "NetBIOS",     130),
            ("mac",      "MAC",         130),
            ("ports",    "Open Ports",  200),
            ("status",   "Status",       70),
        ]:
            self._scan_tree.heading(col, text=hdr, anchor="w")
            self._scan_tree.column(col, width=w,  anchor="w")

        vsb = ttk.Scrollbar(tab, orient="vertical", command=self._scan_tree.yview)
        self._scan_tree.configure(yscrollcommand=vsb.set)
        vsb.pack(side="right", fill="y", padx=(0, 4))
        self._scan_tree.pack(fill="both", expand=True, padx=(6, 0), pady=(0, 4))
        self._scan_tree.bind("<Button-3>", self._scan_ctx_show)

        # Right-click context menu
        self._ctx = tk.Menu(self, tearoff=0)
        self._ctx.add_command(label="Copy IP",
                              command=lambda: self._scan_copy_col(0))
        self._ctx.add_command(label="Copy row",
                              command=self._scan_copy_row)
        self._ctx.add_separator()
        self._ctx.add_command(label="🖧  Show shares of this host …",
                              command=self._scan_show_shares)
        self._ctx.add_command(label="🖧  Show shares of ALL found hosts …",
                              command=self._scan_show_all_shares)
        self._ctx.add_command(label="🖴  Find drives (C$/D$…) & save with own letters …",
                              command=self._scan_find_drives)
        self._ctx.add_separator()
        self._ctx.add_command(label="Open in browser (HTTP)",
                              command=lambda: self._scan_browser("http"))
        self._ctx.add_command(label="Open in browser (HTTPS)",
                              command=lambda: self._scan_browser("https"))
        self._ctx.add_command(label="Open RDP",
                              command=self._scan_rdp)
        self._ctx.add_separator()
        self._ctx.add_command(label="Ping in terminal",
                              command=lambda: self._scan_terminal("ping -t"))
        self._ctx.add_command(label="Traceroute in terminal",
                              command=lambda: self._scan_terminal("tracert"))
        self._ctx.add_separator()
        self._ctx.add_command(label="★  Save as Favorite …",
                              command=self._scan_save_fav)

        self.after(80, self._detect_subnet)

    def _detect_subnet(self):
        ifaces = _net_get_local_interfaces()
        if ifaces:
            labels = [f"{i['name']}  {i['ip']}  ({i['cidr']})" for i in ifaces]
            self._lbl_iface.configure(text="  |  ".join(labels))
            for i in ifaces:
                if not i["ip"].startswith("127.") and not self._var_subnet.get():
                    self._var_subnet.set(i["cidr"])
                    break
        else:
            self._lbl_iface.configure(text="No adapters found")

    def _start_scan(self):
        if self._scanning:
            return
        subnet = self._var_subnet.get().strip()
        if not subnet:
            messagebox.showwarning("No Subnet",
                                   "Enter a subnet, e.g.  192.168.1.0/24",
                                   parent=self)
            return
        try:
            ipaddress.IPv4Network(subnet, strict=False)
        except ValueError as exc:
            messagebox.showerror("Invalid Subnet", str(exc), parent=self)
            return
        try:
            timeout     = float(self._var_timeout.get() or 0.8)
            max_threads = int(self._var_threads.get()   or 128)
        except ValueError:
            timeout = 0.8; max_threads = 128
        try:
            port_list = [int(p.strip())
                         for p in self._var_portlist.get().split(",")
                         if p.strip()]
        except Exception:
            port_list = [22, 80, 135, 139, 443, 445, 3389, 5985]

        self._clear_scan()
        self._scanning = True
        self._btn_scan.configure(state="disabled")
        self._btn_stop.configure(state="normal")
        self._lbl_prog.configure(text="Starting …")

        self._scanner = _NetScanEngine(
            subnet=subnet, timeout=timeout, max_threads=max_threads,
            do_dns=self._var_dns.get(), do_nbt=self._var_nbt.get(),
            do_ports=self._var_ports.get(), port_list=port_list,
            on_host=lambda h: self.after(0, self._insert_row, h),
            on_progress=lambda d, t: self.after(0, self._update_prog, d, t),
            on_done=lambda: self.after(0, self._scan_done),
        )
        self._scanner.start()

    def _stop_scan(self):
        if self._scanner:
            self._scanner.stop()
        self._btn_stop.configure(state="disabled")

    def _insert_row(self, host: dict):
        self._scan_tree.insert("", "end", values=(
            host["ip"], host["hostname"], host["netbios"],
            host["mac"], host["ports_str"], host["status"],
        ))

    def _update_prog(self, done: int, total: int):
        pct = done / total * 100 if total else 0
        self._prog_var.set(pct)
        self._lbl_prog.configure(text=f"{done}/{total}  ({pct:.0f}%)")

    def _scan_done(self):
        self._scanning = False
        self._btn_scan.configure(state="normal")
        self._btn_stop.configure(state="disabled")
        n = len(self._scan_tree.get_children())
        self._lbl_prog.configure(text=f"Done — {n} host(s) found")

    def _clear_scan(self):
        self._scan_tree.delete(*self._scan_tree.get_children())
        self._prog_var.set(0)
        self._lbl_prog.configure(text="Ready")

    def _arp_scan(self):
        self._clear_scan()
        self._lbl_prog.configure(text="Reading ARP cache …")
        def _run():
            arp = _net_get_arp()
            for ip, mac in sorted(arp.items()):
                self.after(0, lambda i=ip, m=mac: self._scan_tree.insert(
                    "", "end", values=(i, "", "", m, "", "ARP")))
            self.after(0, lambda: self._lbl_prog.configure(
                text=f"ARP done — {len(arp)} entr{'y' if len(arp) == 1 else 'ies'}"))
        threading.Thread(target=_run, daemon=True).start()

    def _selected_ip(self):
        sel = self._scan_tree.selection()
        if not sel:
            return None
        return self._scan_tree.item(sel[0], "values")[0]

    def _scan_ctx_show(self, event):
        item = self._scan_tree.identify_row(event.y)
        if item:
            self._scan_tree.selection_set(item)
            self._ctx.post(event.x_root, event.y_root)

    def _scan_copy_col(self, col_idx: int):
        sel = self._scan_tree.selection()
        if not sel:
            return
        val = self._scan_tree.item(sel[0], "values")[col_idx]
        self.clipboard_clear(); self.clipboard_append(val)

    def _scan_copy_row(self):
        sel = self._scan_tree.selection()
        if not sel:
            return
        self.clipboard_clear()
        self.clipboard_append("\t".join(self._scan_tree.item(sel[0], "values")))

    def _scan_show_shares(self):
        """Browse the shares of the highlighted host.

        The host name is preferred over the IP — SMB name resolution is more
        likely to succeed with it, and it reads better in the hotlist.
        """
        sel = self._scan_tree.selection()
        if not sel:
            return
        vals = self._scan_tree.item(sel[0], "values")
        ip   = vals[0] if vals else ""
        name = vals[1] if len(vals) > 1 else ""
        target = name.strip() if name and name.strip() not in ("-", "") else ip
        self.manager.open_shares(host=target)

    def _scan_find_drives(self):
        """Discover the hard drives on the highlighted host (admin C$/D$…
        shares) so each can be saved with its own drive letter."""
        sel = self._scan_tree.selection()
        if not sel:
            messagebox.showinfo("Drives", "Select a host in the scan list first.",
                                parent=self)
            return
        vals = self._scan_tree.item(sel[0], "values")
        ip   = vals[0] if vals else ""
        name = vals[1] if len(vals) > 1 else ""
        target = name.strip() if name and name.strip() not in ("-", "") else ip
        NetDrivesDialog(self, self.manager, host=target, net_win=self)

    def _scan_show_all_shares(self):
        """Browse the shares of every host in the scan result."""
        hosts = []
        for iid in self._scan_tree.get_children():
            vals = self._scan_tree.item(iid, "values")
            if not vals:
                continue
            name = vals[1].strip() if len(vals) > 1 else ""
            hosts.append(name if name and name not in ("-",) else vals[0])
        if not hosts:
            messagebox.showinfo("Shares", "Run a scan first.", parent=self)
            return
        self.manager.open_shares(hosts=hosts)

    def _scan_browser(self, scheme: str):
        ip = self._selected_ip()
        if ip:
            webbrowser.open(f"{scheme}://{ip}")

    def _scan_rdp(self):
        ip = self._selected_ip()
        if ip:
            try:
                subprocess.Popen(["mstsc", f"/v:{ip}"],
                                 creationflags=subprocess.CREATE_NO_WINDOW)
            except Exception as exc:
                messagebox.showerror("RDP", str(exc), parent=self)

    def _scan_terminal(self, cmd_prefix: str):
        ip = self._selected_ip()
        if ip:
            subprocess.Popen(f'start cmd /k {cmd_prefix} {ip}', shell=True)

    def _scan_save_fav(self):
        r"""Save a drive on the scanned host as a favourite.

        A host is only an IP — you can't map \\IP\ itself, you map a SHARE on
        it (\\IP\C$ …).  So this opens the drive finder, which lists the host's
        actual drives and lets you save each with its own letter.  (Use the
        Favorites tab ▸ Add Favorite to type a share path by hand.)"""
        ip = self._selected_ip()
        if not ip:
            messagebox.showinfo("Drives", "Select a host in the scan list first.",
                                parent=self)
            return
        NetDrivesDialog(self, self.manager, host=ip, net_win=self)

    # ── Favorites tab ──────────────────────────────────────────────────────

    def _build_fav_tab(self):
        tab = self._tab_fav

        hdr = ttk.Frame(tab)
        hdr.pack(fill="x", padx=6, pady=6)
        ttk.Button(hdr, text="⚡  Activate All",
                   command=self._activate_all).pack(side="right", padx=4)
        ttk.Button(hdr, text="＋  Add Favorite",
                   command=self._open_fav_dialog).pack(side="right", padx=4)
        ttk.Label(hdr,
                  text="Click  ▶ Connect  to mount a drive instantly.  "
                       "Favorites survive reboots (net_favorites.json).",
                  anchor="w").pack(side="left")

        ttk.Separator(tab, orient="horizontal").pack(fill="x", padx=6)

        canvas = tk.Canvas(tab, highlightthickness=0)
        scrl   = ttk.Scrollbar(tab, orient="vertical", command=canvas.yview)
        canvas.configure(yscrollcommand=scrl.set)
        scrl.pack(side="right", fill="y")
        canvas.pack(side="left", fill="both", expand=True, padx=(6, 0), pady=4)

        self._fav_inner    = ttk.Frame(canvas)
        self._fav_inner_id = canvas.create_window(
            (0, 0), window=self._fav_inner, anchor="nw")
        self._fav_inner.bind("<Configure>",
            lambda e: canvas.configure(scrollregion=canvas.bbox("all")))
        canvas.bind("<Configure>",
            lambda e: canvas.itemconfig(self._fav_inner_id, width=e.width))
        canvas.bind("<MouseWheel>",
            lambda e: canvas.yview_scroll(-1 * (e.delta // 120), "units"))

        self._fav_canvas    = canvas
        self._fav_st_labels: dict = {}
        self._render_favs()

    def _render_favs(self):
        for w in self._fav_inner.winfo_children():
            w.destroy()
        self._fav_st_labels.clear()

        if not self._favorites:
            ttk.Label(
                self._fav_inner,
                text=(
                    "No favorites yet.\n\n"
                    "Use  ＋ Add Favorite  to create one,\n"
                    "or right-click a host in the Scanner and choose  "
                    "★ Save as Favorite."
                ),
                justify="center",
            ).pack(pady=40)
            return

        for idx, fav in enumerate(self._favorites):
            self._render_fav_card(idx, fav)

    def _render_fav_card(self, idx: int, fav: dict):
        card = ttk.Frame(self._fav_inner, relief="groove")
        card.pack(fill="x", padx=6, pady=3)

        left = ttk.Frame(card)
        left.pack(side="left", fill="both", expand=True, padx=8, pady=6)

        name   = fav.get("name", "(unnamed)")
        letter = fav.get("letter", "?:")
        path   = fav.get("path", "")
        user   = fav.get("user", "")
        detail = f"{letter}  →  {path}"
        if user:
            detail += f"   (user: {user})"

        ttk.Label(left, text=f"★  {name}", font=("", 0, "bold")).pack(anchor="w")
        ttk.Label(left, text=detail).pack(anchor="w")

        st_lbl = ttk.Label(left, text="")
        st_lbl.pack(anchor="w")
        self._fav_st_labels[name] = st_lbl

        right = ttk.Frame(card)
        right.pack(side="right", padx=8, pady=6)
        ttk.Button(right, text="▶  Connect", width=12,
                   command=lambda f=fav, s=st_lbl: self._connect_fav(f, s)
                   ).pack(pady=2)
        ttk.Button(right, text="✎  Edit",    width=12,
                   command=lambda i=idx: self._open_fav_dialog(edit_idx=i)
                   ).pack(pady=2)
        ttk.Button(right, text="✖  Delete",  width=12,
                   command=lambda i=idx: self._delete_fav(i)
                   ).pack(pady=2)

    def _connect_fav(self, fav: dict, st_lbl=None):
        if st_lbl:
            st_lbl.configure(text="Connecting …")

        def _cb(msg, ok):
            if st_lbl:
                try:
                    st_lbl.after(0, lambda: st_lbl.configure(text=msg))
                except Exception:
                    pass

        _net_connect_favorite(fav, status_cb=_cb)

    def _activate_all(self):
        if not self._favorites:
            messagebox.showinfo("Favorites", "No favorites saved yet.", parent=self)
            return
        self._render_favs()
        for fav in self._favorites:
            key = fav.get("name", "")
            st  = self._fav_st_labels.get(key)
            self._connect_fav(fav, st)

    def _open_fav_dialog(self, prefill: dict = None, edit_idx: int = None):
        is_edit = edit_idx is not None
        if is_edit:
            prefill = self._favorites[edit_idx]

        dlg = tk.Toplevel(self)
        _setup_toplevel(dlg, "Edit Favorite" if is_edit else "Add Favorite", self)
        dlg.resizable(False, False)

        body = ttk.Frame(dlg, padding=12)
        body.pack(fill="x")

        def _row(r, label, key, show=None):
            ttk.Label(body, text=label, width=16, anchor="w").grid(
                row=r, column=0, sticky="w", pady=4)
            init_val = (prefill or {}).get(key, "")
            if key == "_pw":
                init_val = _net_decode_pw(init_val)
            var = tk.StringVar(value=init_val)
            e_kw = dict(insertofftime=0, insertontime=9999999)
            if show:
                e_kw["show"] = show
            e = tk.Entry(body, textvariable=var, width=32, **e_kw)
            e.grid(row=r, column=1, sticky="we", padx=(6, 0), pady=4)
            return var

        var_name   = _row(0, "Favorite name:", "name")
        var_path   = _row(1, "Share path:",    "path")
        var_user   = _row(2, "Username:",      "user")
        var_pw     = _row(3, "Password:",      "_pw",  show="●")

        # Drive letter combobox
        ttk.Label(body, text="Drive letter:", width=16, anchor="w").grid(
            row=4, column=0, sticky="w", pady=4)
        avail, _ = _net_get_drive_info()
        import string as _str
        all_letters = [f"{c}:" for c in _str.ascii_uppercase[3:]]
        letter_list = avail + [l for l in all_letters if l not in avail]
        pref_letter = (prefill or {}).get("letter", avail[0] if avail else "Z:")
        var_letter = tk.StringVar(value=pref_letter)
        ttk.Combobox(body, textvariable=var_letter, values=letter_list,
                     width=5, state="readonly").grid(
            row=4, column=1, sticky="w", padx=(6, 0), pady=4)

        body.columnconfigure(1, weight=1)

        lbl_st = ttk.Label(dlg, text="", anchor="w")
        lbl_st.pack(fill="x", padx=12, pady=(0, 4))

        def _save():
            name   = var_name.get().strip()
            letter = var_letter.get().strip()
            path   = var_path.get().strip()
            user   = var_user.get().strip()
            pw     = var_pw.get()
            if not name:
                lbl_st.configure(text="⚠  Favorite name is required.")
                return
            if not path.startswith("\\\\"):
                lbl_st.configure(
                    text="⚠  Share path must start with  \\\\server\\share")
                return
            fav = {"name": name, "letter": letter, "path": path,
                   "user": user, "_pw": _net_encode_pw(pw)}
            if is_edit:
                self._favorites[edit_idx] = fav
            else:
                if any(f["name"] == name for f in self._favorites):
                    lbl_st.configure(
                        text=f"⚠  A favorite named '{name}' already exists.")
                    return
                self._favorites.append(fav)
            _net_save_favorites(self._favorites)
            self._render_favs()
            dlg.destroy()

        btn_row = ttk.Frame(dlg, padding=(12, 6))
        btn_row.pack(fill="x")
        ttk.Button(btn_row, text="Save",   command=_save,       width=12).pack(side="left")
        ttk.Button(btn_row, text="Cancel", command=dlg.destroy, width=10).pack(side="right")

    def _delete_fav(self, idx: int):
        if 0 <= idx < len(self._favorites):
            name = self._favorites[idx].get("name", "this favorite")
            if _ask_yes_no("Delete", f"Delete  '{name}'?", parent=self):
                del self._favorites[idx]
                _net_save_favorites(self._favorites)
                self._render_favs()


# ══════════════════════════════════════════════════════════════════════════
#  DEL 20 — Archive engine  (ZIP / RAR / 7z / TAR / GZ / BZ2 / XZ / ISO / CAB)
# ══════════════════════════════════════════════════════════════════════════
#
# Strategy: use a pure-Python library when one is available, and fall back to
# 7z.exe (7-Zip command line) for everything else.  7-Zip alone covers every
# format we list, so a single external tool is enough for full support.

try:
    import py7zr as _py7zr
    _HAS_PY7ZR = True
except ImportError:
    _py7zr = None
    _HAS_PY7ZR = False

try:
    import rarfile as _rarfile
    _HAS_RARFILE = True
except ImportError:
    _rarfile = None
    _HAS_RARFILE = False

# Extension → logical archive format
ARCHIVE_FORMATS = {
    ".zip":   "zip",   ".jar":  "zip",   ".cbz": "zip",
    ".7z":    "7z",
    ".rar":   "rar",   ".cbr":  "rar",
    ".tar":   "tar",
    ".gz":    "tar.gz",   ".tgz":  "tar.gz",
    ".bz2":   "tar.bz2",  ".tbz":  "tar.bz2", ".tbz2": "tar.bz2",
    ".xz":    "tar.xz",   ".txz":  "tar.xz",
    ".iso":   "iso",
    ".cab":   "cab",
    # 7-Zip reads these too; they were simply never listed, so the program did
    # not recognise them as archives at all.
    ".arj":   "arj",
    ".lzh":   "lzh",   ".lha":  "lzh",
    ".ace":   "ace",
    ".z":     "z",
    ".zipx":  "zip",
}

# The pieces of a split archive.  They are archives as far as the program is
# concerned — pressing F10 on part 5 must work — but every one of them resolves
# to the FIRST part before anything is unpacked (see archive_start_of).
ARCHIVE_PART_RE = _re.compile(
    r"\.(?:r\d{2,}|z\d{2,}|\d{3,})$", _re.IGNORECASE)

# Formats this program can CREATE (reading covers more than writing)
PACK_FORMATS = ["zip", "7z", "tar", "tar.gz", "tar.bz2", "tar.xz"]

PACK_EXT = {
    "zip": ".zip", "7z": ".7z", "tar": ".tar",
    "tar.gz": ".tar.gz", "tar.bz2": ".tar.bz2", "tar.xz": ".tar.xz",
}


def _find_7z() -> str:
    """Locate 7z.exe — bundled copy first, then the usual install paths."""
    candidates = [
        APP_ROOT / "Helpfiles" / "redigerare" / "7z.exe",
        APP_ROOT / "Helpfiles" / "7z.exe",
        Path(r"C:\Program Files\7-Zip\7z.exe"),
        Path(r"C:\Program Files (x86)\7-Zip\7z.exe"),
    ]
    for c in candidates:
        if c.is_file():
            return str(c)
    found = shutil.which("7z") or shutil.which("7za")
    return found or ""


_SEVENZIP = None


def sevenzip_path() -> str:
    """Lookup of 7z.exe (empty string when not installed).

    Only a FOUND path is remembered.  The old version also remembered "not
    found", so 7-Zip installed (or 7z.exe dropped into Helpfiles/redigerare)
    while the program was running was ignored until the next start.  A miss
    costs a handful of is_file() calls, so looking again is free.
    """
    global _SEVENZIP
    if not _SEVENZIP or not os.path.isfile(_SEVENZIP):
        _SEVENZIP = _find_7z()
    return _SEVENZIP


def _no_window_kwargs() -> dict:
    """subprocess flags that keep console windows from flashing on Windows."""
    if platform.system() == "Windows":
        return {"creationflags": getattr(subprocess, "CREATE_NO_WINDOW", 0x08000000)}
    return {}


def archive_format(path: str) -> str:
    """Return the logical archive format for a path, or '' if not an archive."""
    low = str(path).lower()
    # Double extensions first, so .tar.gz does not read as a bare .gz
    for double, fmt in ((".tar.gz", "tar.gz"), (".tar.bz2", "tar.bz2"),
                        (".tar.xz", "tar.xz")):
        if low.endswith(double):
            return fmt
    return ARCHIVE_FORMATS.get(os.path.splitext(low)[1], "")


def is_archive(path: str) -> bool:
    if not os.path.isfile(path):
        return False
    if archive_format(path):
        return True
    # A piece of a split set (.r07, .z03, .002) — only when the set it belongs
    # to really starts somewhere else, so an ordinary "notes.001" is left alone.
    if not ARCHIVE_PART_RE.search(str(path)):
        return False

    def _n(p):
        try:
            return os.path.normcase(os.path.abspath(p))
        except Exception:
            return str(p)

    return _n(archive_start_of(path)) != _n(path)


# ══ DEL 20b — split archives ══════════════════════════════════════════════
#
# A release arrives as  movie.rar + movie.r00 … r42 , or  movie.part01.rar … ,
# or  movie.7z.001 … , or  movie.zip + movie.z01 … .  Three things follow from
# that, and all three are what a file manager without them gets wrong:
#   • the set is ONE job, started from ONE file (the others are read by the
#     extractor itself) — so dropping 43 files in must not make 43 jobs;
#   • it can only be unpacked when EVERY part has arrived — and while an FTP
#     client is still fetching one, the part is either missing or sitting
#     there as "movie.r37.part";
#   • an .sfv manifest, when the release ships one, is the authority on what
#     "every part" means — it can name the missing ones instead of letting
#     7-Zip fail with a number.

def archive_start_of(path: str) -> str:
    """The file an extractor should be pointed at for this (possibly split)
    archive.  Any part resolves to the first one; anything else is itself."""
    try:
        p      = Path(path)
        parent = p.parent
        ext    = p.suffix.lower()
        stem   = p.stem

        # RAR, old style:  base.rar + base.r00, base.r01 …
        if _re.match(r"^\.r\d{2,}$", ext):
            first = parent / (stem + ".rar")
            return str(first) if first.exists() else str(p)

        # RAR, new style:  base.part01.rar, base.part02.rar …
        if ext == ".rar":
            m = _re.search(r"\.part(\d+)$", stem, _re.IGNORECASE)
            if m and int(m.group(1)) != 1:
                base = stem[:m.start()]
                for cand in (f"{base}.part1.rar", f"{base}.part01.rar",
                             f"{base}.part001.rar"):
                    c = parent / cand
                    if c.exists():
                        return str(c)
            return str(p)

        # ZIP:  base.zip + base.z01, base.z02 …
        if _re.match(r"^\.z\d{2,}$", ext):
            first = parent / (stem + ".zip")
            return str(first) if first.exists() else str(p)

        # 7z:  base.7z.001, base.7z.002 …  (and plain base.001)
        if _re.match(r"^\.\d{3,}$", ext):
            whole = parent / p.stem            # movie.7z, from movie.7z.001
            if whole.exists() and archive_format(str(whole)):
                return str(whole)
            first = parent / (p.stem + ".001")  # the first volume itself
            if first.exists():
                return str(first)
            return str(p)

        return str(p)
    except Exception:
        return str(path)


def archive_part_files(start_path: str) -> list:
    """Every file that belongs to this archive set, the first one included.

    A single-file archive gives a one-item list.  Used to add up the real size
    of a job, and to take the whole set away when "delete after unpacking" is
    on — leaving 42 orphaned .r-files behind would be worse than not deleting
    at all."""
    out = []
    try:
        p      = Path(start_path)
        parent = p.parent
        stem   = p.stem
        ext    = p.suffix.lower()
        pats = []
        if ext == ".rar":
            m = _re.search(r"\.part(\d+)$", stem, _re.IGNORECASE)
            if m:
                base = stem[:m.start()]
                pats = [rf"^{_re.escape(base)}\.part\d+\.rar$"]
            else:
                pats = [rf"^{_re.escape(stem)}\.rar$",
                        rf"^{_re.escape(stem)}\.r\d{{2,}}$"]
        elif ext == ".zip":
            pats = [rf"^{_re.escape(stem)}\.zip$",
                    rf"^{_re.escape(stem)}\.z\d{{2,}}$"]
        elif _re.match(r"^\.\d{3,}$", ext):
            pats = [rf"^{_re.escape(stem)}\.\d{{3,}}$"]
        else:
            pats = [rf"^{_re.escape(p.name)}$"]
        for f in parent.iterdir():
            if f.is_file() and any(_re.match(pat, f.name, _re.IGNORECASE)
                                   for pat in pats):
                out.append(str(f))
    except Exception as exc:
        _log(f"archive_part_files({start_path}): {exc}")
    return sorted(out) or [start_path]


def _sfv_check(archive_path: str) -> list:
    """What the .sfv that covers this archive says is NOT in the folder.

    Returns one dict per such .sfv:  {"sfv": file name, "total": number of
    files it lists, "missing": [names]}.  Empty list = no .sfv covers this
    archive, or the release is whole.  (An .sfv is a LIST of the files that
    belong together; "missing" means files from that list, never the .sfv.)"""
    report = []
    try:
        parent = Path(archive_path).parent
        sfvs = list(parent.glob("*.sfv"))
        if not sfvs:
            return []
        me = os.path.basename(archive_path).lower()
        for sfv in sfvs:
            try:
                lines = sfv.read_text(encoding="latin-1",
                                      errors="replace").splitlines()
            except Exception:
                continue
            # revCJ: collect this .sfv's entries first.  A folder can hold
            # SEVERAL releases, each with its own .sfv; only the .sfv that
            # lists THIS archive may say what is missing for it.  Before, every
            # .sfv in the folder counted, so a neighbour release's missing
            # file kept this one waiting for ever.
            entries = []
            for line in lines:
                line = line.strip()
                if not line or line[0] in ";#":
                    continue
                parts = line.rsplit(None, 1)
                if not parts:
                    continue
                # Some tools quote names with spaces:  "my file.rar" 1A2B3C4D
                fname = parts[0].strip().strip('"').strip()
                if not fname:
                    continue
                crc = parts[1].strip().lower() if len(parts) > 1 else ""
                entries.append((fname, crc))
            if not any(os.path.basename(fn.replace("/", os.sep)).lower() == me
                       for fn, _crc in entries):
                continue
            missing = []
            for fname, crc in entries:
                f = parent / fname
                try:
                    if not f.exists():
                        missing.append(fname)
                    elif f.stat().st_size == 0 and crc.strip("0") != "":
                        # An empty file is only "missing" when the .sfv expects
                        # content; CRC 00000000 is what an empty file SHOULD be.
                        missing.append(fname)
                except OSError:
                    missing.append(fname)
            if missing:
                report.append({"sfv": sfv.name, "total": len(entries),
                               "missing": sorted(missing)})
    except Exception as exc:
        _log(f"_sfv_check({archive_path}): {exc}")
    return report


def _sfv_missing_files(archive_path: str) -> list:
    """Flat, sorted list of the files the covering .sfv lists but the folder
    lacks (see _sfv_check).  Empty when there is nothing missing."""
    return sorted({m for r in _sfv_check(archive_path) for m in r["missing"]})


def _part_file_ok(path) -> bool:
    """True when the file is there AND no "<name>.part" companion says an FTP
    client is still writing it."""
    p = Path(path)
    try:
        if not p.exists():
            return False
        return not (p.parent / (p.name + ".part")).exists()
    except OSError:
        return False


def archive_parts_ready(start_path: str) -> tuple:
    """(ready, reason).  False while a part of the set is missing or is still
    being downloaded; *reason* says which, in plain language."""
    try:
        p      = Path(start_path)
        parent = p.parent
        stem   = p.stem
        ext    = p.suffix.lower()

        # The manifest, when there is one, outranks whatever is on disk.
        sfv_report = _sfv_check(start_path)
        if sfv_report:
            r      = sfv_report[0]
            miss   = r["missing"]
            shown  = ", ".join(miss[:3])
            more   = f", +{len(miss) - 3} more" if len(miss) > 3 else ""
            return False, (f"{len(miss)} of {r['total']} files listed in "
                           f"{r['sfv']} are not here: {shown}{more}  "
                           f"[right-click: full list / Unpack anyway]")

        def _still_coming(pattern) -> str:
            for f in parent.iterdir():
                if _re.match(pattern + r"\.part$", f.name, _re.IGNORECASE):
                    return f.name[:-5]
                if _re.match(pattern, f.name, _re.IGNORECASE) and not _part_file_ok(f):
                    return f.name
            return ""

        if not _part_file_ok(p):
            return False, f"{p.name} is still being written"

        if ext == ".rar" and not _re.search(r"\.part\d+$", stem, _re.IGNORECASE):
            busy = _still_coming(rf"{_re.escape(stem)}\.r\d{{2,}}")
            if busy:
                return False, f"{busy} is still on its way"
        elif ext == ".rar":
            m = _re.search(r"\.part(\d+)$", stem, _re.IGNORECASE)
            base = stem[:m.start()] if m else stem
            busy = _still_coming(rf"{_re.escape(base)}\.part\d+\.rar")
            if busy:
                return False, f"{busy} is still on its way"
        elif ext == ".zip":
            busy = _still_coming(rf"{_re.escape(stem)}\.z\d{{2,}}")
            if busy:
                return False, f"{busy} is still on its way"
        elif _re.match(r"^\.\d{3,}$", ext):
            busy = _still_coming(rf"{_re.escape(stem)}\.\d{{3,}}")
            if busy:
                return False, f"{busy} is still on its way"

        return True, ""
    except Exception as exc:
        _log(f"archive_parts_ready({start_path}): {exc}")
        return True, ""          # never block a job over a bookkeeping error


class ArchiveError(Exception):
    """Raised when an archive cannot be read, extracted or created."""


class SevenZipMissing(ArchiveError):
    """7-Zip is needed for this archive and cannot be found.

    A separate class so the message box can offer to run the Ninite installer
    (see _archive_error_box) instead of only telling the user to go and get it.
    """


# The Ninite installer for 7-Zip.  Ninite always fetches the LATEST version,
# so a fresh PC (or a deleted 7-Zip) is one click away from working again.
NINITE_7ZIP = APP_ROOT / "Helpfiles" / "0---Ninite" / "7-zip.exe"


def _archive_error_box(parent, exc):
    """messagebox.showerror for an ArchiveError, with one extra: when 7-Zip is
    MISSING and the Ninite installer is in Helpfiles/0---Ninite, offer to run
    it, then watch for 7-Zip to appear and say so — no restart needed."""
    if not (isinstance(exc, SevenZipMissing) and NINITE_7ZIP.is_file()):
        messagebox.showerror("Archive", str(exc), parent=parent)
        return
    if not messagebox.askyesno(
            "7-Zip is missing",
            f"{exc}\n\nRun the Ninite installer now?\n{NINITE_7ZIP}\n\n"
            "Windows will ask for permission.  When the installation is done "
            "the program notices by itself — try the archive again after that.",
            parent=parent):
        return
    try:
        root = parent._root()     # outlives a dialog that closes right after
    except Exception:
        root = parent
    try:
        os.startfile(str(NINITE_7ZIP))    # ShellExecute: handles the UAC prompt
    except OSError as e2:
        messagebox.showerror("7-Zip", f"Could not start the installer:\n{e2}",
                             parent=root)
        return
    deadline = _time.monotonic() + 900

    def _watch():
        try:
            if not root.winfo_exists():
                return
            if sevenzip_path():
                messagebox.showinfo(
                    "7-Zip", "7-Zip is installed now.\nTry the archive again.",
                    parent=root)
                return
            if _time.monotonic() < deadline:
                root.after(2000, _watch)
        except Exception as e3:
            _log(f"7-Zip install watch stopped: {e3}")

    root.after(2000, _watch)


@dataclasses.dataclass
class ArchiveEntry:
    name: str
    size: int = 0
    modified: str = ""
    is_dir: bool = False


def archive_list(path: str) -> list:
    """List the contents of an archive as ArchiveEntry records."""
    fmt = archive_format(path)
    if not fmt:
        raise ArchiveError(f"Not a supported archive: {os.path.basename(path)}")

    try:
        if fmt == "zip":
            out = []
            with zipfile.ZipFile(path) as zf:
                for info in zf.infolist():
                    ts = ""
                    try:
                        ts = f"{datetime(*info.date_time):%Y-%m-%d %H:%M}"
                    except Exception:
                        pass
                    out.append(ArchiveEntry(info.filename, info.file_size, ts,
                                            info.is_dir()))
            return out

        if fmt.startswith("tar"):
            out = []
            with tarfile.open(path, "r:*") as tf:
                for m in tf.getmembers():
                    ts = ""
                    try:
                        ts = f"{datetime.fromtimestamp(m.mtime):%Y-%m-%d %H:%M}"
                    except Exception:
                        pass
                    out.append(ArchiveEntry(m.name, m.size, ts, m.isdir()))
            return out

        if fmt == "7z" and _HAS_PY7ZR:
            out = []
            with _py7zr.SevenZipFile(path, "r") as zf:
                for info in zf.list():
                    ts = ""
                    try:
                        ts = f"{info.creationtime:%Y-%m-%d %H:%M}" if info.creationtime else ""
                    except Exception:
                        pass
                    out.append(ArchiveEntry(info.filename,
                                            getattr(info, "uncompressed", 0) or 0,
                                            ts, info.is_directory))
            return out

        if fmt == "rar" and _HAS_RARFILE:
            out = []
            with _rarfile.RarFile(path) as rf:
                for info in rf.infolist():
                    ts = ""
                    try:
                        ts = f"{datetime(*info.date_time):%Y-%m-%d %H:%M}"
                    except Exception:
                        pass
                    out.append(ArchiveEntry(info.filename, info.file_size, ts,
                                            info.isdir()))
            return out
    except ArchiveError:
        raise
    except Exception as exc:
        # Fall through to 7z.exe — a corrupt-looking archive for one library is
        # often perfectly readable by 7-Zip.
        _log(f"archive_list native reader failed for {path}: {exc}")

    return _archive_list_7z(path)


def _archive_list_7z(path: str) -> list:
    """List an archive via `7z l -slt` (works for ISO, CAB, RAR, everything)."""
    exe = sevenzip_path()
    if not exe:
        raise SevenZipMissing(
            "7-Zip is required for this archive format.\n\n"
            "Install 7-Zip (https://www.7-zip.org) or place 7z.exe in\n"
            f"{APP_ROOT / 'Helpfiles' / 'redigerare'}")
    try:
        res = subprocess.run([exe, "l", "-slt", "-ba", path],
                             capture_output=True, text=True, errors="replace",
                             timeout=120, **_no_window_kwargs())
    except Exception as exc:
        raise ArchiveError(f"Could not run 7-Zip: {exc}")
    if res.returncode not in (0, 1):
        raise ArchiveError(f"7-Zip could not read the archive:\n{res.stderr.strip()}")

    entries, cur = [], {}
    for line in res.stdout.splitlines():
        line = line.rstrip()
        if not line:
            if cur.get("Path"):
                attr = cur.get("Attributes", "")
                try:
                    size = int(cur.get("Size", "0") or 0)
                except ValueError:
                    size = 0
                entries.append(ArchiveEntry(
                    cur["Path"], size, cur.get("Modified", "")[:16],
                    attr.startswith("D") or "D" in attr.split()[0:1]))
            cur = {}
            continue
        if " = " in line:
            k, v = line.split(" = ", 1)
            cur[k.strip()] = v.strip()
    if cur.get("Path"):
        try:
            size = int(cur.get("Size", "0") or 0)
        except ValueError:
            size = 0
        entries.append(ArchiveEntry(cur["Path"], size,
                                    cur.get("Modified", "")[:16],
                                    cur.get("Attributes", "").startswith("D")))
    return entries


# ── Date handling policy ──────────────────────────────────────────────────
#
# What a measurement of the current behaviour showed:
#   unpack ZIP     lost the original date (Python's zipfile does not restore
#                  timestamps) — every other format kept it.  Fixed below.
#   unpack TAR/GZ/7z, copy, move, rename   all kept the original date.
# Renaming and moving never touch a file's own date; that is the filesystem's
# doing, not ours, and there is nothing to configure.
#
# The archive helpers are module-level functions with no access to the
# settings object, so the chosen policy is mirrored here and refreshed by
# EditorFrame.apply_date_policy() whenever the settings change.
DATE_POLICY = {
    "unpack": True,      # keep the dates stored inside the archive
    "copy":   True,      # keep the source's date on the new copy
}


def _stamp_now(paths: list):
    """Set the modified time to now — used when dates are NOT being kept."""
    now = _time.time()
    for p in paths:
        try:
            if os.path.exists(p):
                os.utime(p, (now, now))
        except OSError:
            continue


def archive_extract(path: str, dest_dir: str, progress=None, polite=None) -> int:
    """Extract an archive into dest_dir.

    progress(current, total, name) may return False to request cancellation.
    polite() — when given — is called between members: the unpack is a
    background job and uses it to step aside for the person at the keyboard
    (and, for 7z, to run 7-Zip itself at idle priority instead of py7zr inside
    this process, which would hold the interpreter lock).
    Returns the number of members extracted.
    """
    fmt = archive_format(path)
    if not fmt:
        raise ArchiveError(f"Not a supported archive: {os.path.basename(path)}")
    os.makedirs(dest_dir, exist_ok=True)

    def _tick(i, total, name):
        if progress and progress(i, total, name) is False:
            raise ArchiveError("Cancelled by user")
        if polite:
            polite()

    # In-process py7zr cannot be asked to step aside; a 7-Zip child at idle
    # priority can.  Only when the exe exists — otherwise py7zr as before.
    use_exe_7z = bool(polite) and bool(sevenzip_path())

    keep_dates = DATE_POLICY.get("unpack", True)

    try:
        if fmt == "zip":
            with zipfile.ZipFile(path) as zf:
                infos = zf.infolist()
                for i, info in enumerate(infos, 1):
                    _tick(i, len(infos), info.filename)
                    out = zf.extract(info.filename, dest_dir)
                    # Python's zipfile does NOT restore timestamps, unlike
                    # tarfile and 7-Zip — without this, everything unpacked
                    # from a ZIP would carry today's date.
                    if keep_dates and not info.is_dir():
                        try:
                            ts = _time.mktime(tuple(info.date_time) + (0, 0, -1))
                            os.utime(out, (ts, ts))
                        except Exception:
                            pass
                return len(infos)

        if fmt.startswith("tar"):
            with tarfile.open(path, "r:*") as tf:
                members = tf.getmembers()
                safe = [m for m in members if _tar_member_is_safe(m)]
                skipped = len(members) - len(safe)
                if skipped:
                    _log(f"archive_extract: skipped {skipped} unsafe member(s) in {path}")
                for i, m in enumerate(safe, 1):
                    _tick(i, len(safe), m.name)
                    tf.extract(m, dest_dir)
                if not keep_dates:
                    _stamp_now([os.path.join(dest_dir, m.name) for m in safe])
                return len(safe)

        if fmt == "7z" and _HAS_PY7ZR and not use_exe_7z:
            with _py7zr.SevenZipFile(path, "r") as zf:
                _tick(0, 1, os.path.basename(path))
                names = zf.getnames()
                zf.extractall(path=dest_dir)
                if not keep_dates:
                    _stamp_now([os.path.join(dest_dir, n) for n in names])
                return len(names)

        if fmt == "rar" and _HAS_RARFILE:
            with _rarfile.RarFile(path) as rf:
                names = rf.namelist()
                for i, name in enumerate(names, 1):
                    _tick(i, len(names), name)
                    rf.extract(name, dest_dir)
                if not keep_dates:
                    _stamp_now([os.path.join(dest_dir, n) for n in names])
                return len(names)
    except ArchiveError:
        raise
    except Exception as exc:
        _log(f"archive_extract native path failed for {path}: {exc}")

    return _archive_extract_7z(path, dest_dir, progress, low_priority=bool(polite))


def _tar_member_is_safe(member) -> bool:
    """Reject absolute paths and ../ escapes (tar path-traversal protection)."""
    name = member.name.replace("\\", "/")
    if name.startswith("/") or os.path.isabs(name):
        return False
    if ".." in Path(name).parts:
        return False
    if member.issym() or member.islnk():
        # Links can point outside the destination — skip them
        return False
    return True


def _archive_extract_7z(path: str, dest_dir: str, progress=None,
                        low_priority: bool = False) -> int:
    """Extract via `7z x` (fallback for ISO / CAB / RAR without libraries).

    low_priority: run 7-Zip at IDLE priority (an unpack from the Task Queue —
    it takes every spare cycle, and none the moment you do something), and
    poll for ✖ Cancel while it runs so a cancel really stops it."""
    exe = sevenzip_path()
    if not exe:
        raise SevenZipMissing(
            "7-Zip is required for this archive format.\n\n"
            "Install 7-Zip (https://www.7-zip.org) or place 7z.exe in\n"
            f"{APP_ROOT / 'Helpfiles' / 'redigerare'}")
    if progress:
        progress(0, 1, os.path.basename(path))
    kw = _no_window_kwargs()
    if low_priority and platform.system() == "Windows":
        kw["creationflags"] = kw.get("creationflags", 0) | 0x00000040  # IDLE_PRIORITY_CLASS
    errfile = None
    try:
        if low_priority:
            errfile = tempfile.TemporaryFile()
            proc = subprocess.Popen(
                [exe, "x", path, f"-o{dest_dir}", "-y", "-bso0", "-bsp0"],
                stdout=subprocess.DEVNULL, stderr=errfile, **kw)
            started = _time.monotonic()
            while True:
                try:
                    proc.wait(timeout=0.4)
                    break
                except subprocess.TimeoutExpired:
                    pass
                if progress and progress(0, 1, os.path.basename(path)) is False:
                    try:
                        proc.kill()
                        proc.wait(timeout=10)
                    except Exception:
                        pass
                    raise ArchiveError("Cancelled by user")
                if _time.monotonic() - started > 6 * 3600:
                    proc.kill()
                    raise ArchiveError("7-Zip took more than 6 hours")
            errfile.seek(0)
            err_text = errfile.read().decode("utf-8", "replace").strip()
            if proc.returncode != 0:
                raise ArchiveError(f"7-Zip extraction failed:\n{err_text}")
        else:
            res = subprocess.run(
                [exe, "x", path, f"-o{dest_dir}", "-y", "-bso0", "-bsp0"],
                capture_output=True, text=True, errors="replace",
                timeout=3600, **kw)
            if res.returncode != 0:
                raise ArchiveError(f"7-Zip extraction failed:\n{res.stderr.strip()}")
    except ArchiveError:
        raise
    except Exception as exc:
        raise ArchiveError(f"Could not run 7-Zip: {exc}")
    finally:
        if errfile is not None:
            try:
                errfile.close()
            except Exception:
                pass
    if not DATE_POLICY.get("unpack", True):
        # 7-Zip restores the stored dates; undo that when the user wants
        # extracted files to carry today's date instead.
        try:
            _stamp_now([os.path.join(dest_dir, e.name)
                        for e in _archive_list_7z(path) if not e.is_dir])
        except Exception as exc:
            _log(f"Could not stamp extracted files with today's date: {exc}")
    if progress:
        progress(1, 1, os.path.basename(path))
    return 1


# ── Selective extraction / removal ──────────────────────────────────────
#
# Used by the in-panel archive browser (Enter / double-click descends INTO an
# archive like a folder — see FilePanel.enter_archive in DEL 08): Copy (F5)
# pulls out just the marked entries via archive_extract_members(); Move (F6)
# and Delete follow up with archive_delete_members() to remove them from a
# writable archive.  archive_extract() / archive_create() above are reused
# wherever possible so there is only one code path per format to keep working.

def _norm_member(name: str) -> str:
    return name.replace("\\", "/").rstrip("/")


def _member_matches(entry_name: str, wanted_prefixes: list) -> bool:
    """True when entry_name IS one of wanted_prefixes, or lives inside one of
    them (wanted_prefixes may name folders — every file below a selected
    folder must come along)."""
    n = _norm_member(entry_name)
    for w in wanted_prefixes:
        if n == w or n.startswith(w + "/"):
            return True
    return False


def _merge_move(src: str, dst: str):
    """Move *src* onto *dst*, merging folders and replacing what is in the way.

    Replacing rather than asking is deliberate: it is exactly what the plain
    extract this replaces already did (zipfile/tarfile/7-Zip all write straight
    over an existing file), so lifting the files out of the staging folder
    cannot change the outcome of a copy-out."""
    if os.path.isdir(src) and os.path.isdir(dst):
        for name in os.listdir(src):
            _merge_move(os.path.join(src, name), os.path.join(dst, name))
        try:
            os.rmdir(src)
        except OSError:
            pass
        return
    if os.path.exists(dst):
        try:
            if os.path.isdir(dst):
                shutil.rmtree(dst)
            else:
                os.remove(dst)
        except OSError as exc:
            raise ArchiveError(f"Could not replace {dst}: {exc}")
    parent = os.path.dirname(dst)
    if parent:
        os.makedirs(parent, exist_ok=True)
    shutil.move(src, dst)


def archive_extract_members(path: str, dest_dir: str, members: list,
                            progress=None, strip_prefix: str = "") -> int:
    """Extract only the given members from an archive.

    Each entry in *members* is an archive-internal path (forward slashes,
    matching ArchiveEntry.name) — a single file, or a folder whose full
    contents should come along.  Returns the number of FILES extracted.

    *strip_prefix* is the archive-internal folder you are STANDING IN when you
    copy out.  Every backend recreates a member's full internal path, so being
    inside "Icons/" and marking one file wrote  <dest>/Icons/<file>  — the
    sub-folder came along uninvited, which is not what marking a FILE means.
    With the prefix given, what lands at the destination is relative to where
    you stood: mark the file and you get the file; mark the folder (from
    outside it) and you get the folder.

    It is done by extracting into a scratch folder INSIDE dest_dir and lifting
    what sits under the prefix up out of it.  One code path for zip / tar / 7z
    / rar / the 7-Zip fallback instead of five, and because the scratch folder
    is on the destination's own volume the lift is a rename, not a second copy.
    """
    prefix = _norm_member(strip_prefix).strip("/")
    if not prefix:
        return _archive_extract_members_at(path, dest_dir, members, progress)

    os.makedirs(dest_dir, exist_ok=True)
    staging = os.path.join(
        dest_dir, f".fm-extract-{os.getpid()}-{int(_time.time())}")
    os.makedirs(staging, exist_ok=True)
    try:
        n = _archive_extract_members_at(path, staging, members, progress)
        under = os.path.join(staging, *prefix.split("/"))
        # If a backend flattened the paths anyway there is no prefix folder to
        # look under — take what is in the staging folder itself rather than
        # silently delivering nothing.
        lift_from = under if os.path.isdir(under) else staging
        for name in os.listdir(lift_from):
            _merge_move(os.path.join(lift_from, name),
                        os.path.join(dest_dir, name))
        return n
    finally:
        shutil.rmtree(staging, ignore_errors=True)


def _archive_extract_members_at(path: str, dest_dir: str, members: list,
                                progress=None) -> int:
    """The plain extract: every member keeps its full archive-internal path."""
    fmt = archive_format(path)
    if not fmt:
        raise ArchiveError(f"Not a supported archive: {os.path.basename(path)}")
    os.makedirs(dest_dir, exist_ok=True)
    wanted = [_norm_member(m) for m in members]

    def _tick(i, total, name):
        if progress and progress(i, total, name) is False:
            raise ArchiveError("Cancelled by user")

    keep_dates = DATE_POLICY.get("unpack", True)

    try:
        if fmt == "zip":
            with zipfile.ZipFile(path) as zf:
                infos = [i for i in zf.infolist()
                        if _member_matches(i.filename, wanted)]
                for i, info in enumerate(infos, 1):
                    _tick(i, len(infos), info.filename)
                    out = zf.extract(info.filename, dest_dir)
                    if keep_dates and not info.is_dir():
                        try:
                            ts = _time.mktime(tuple(info.date_time) + (0, 0, -1))
                            os.utime(out, (ts, ts))
                        except Exception:
                            pass
                return sum(1 for i in infos if not i.is_dir())

        if fmt.startswith("tar"):
            with tarfile.open(path, "r:*") as tf:
                cand = [m for m in tf.getmembers()
                       if _member_matches(m.name, wanted)]
                safe = [m for m in cand if _tar_member_is_safe(m)]
                for i, m in enumerate(safe, 1):
                    _tick(i, len(safe), m.name)
                    tf.extract(m, dest_dir)
                if not keep_dates:
                    _stamp_now([os.path.join(dest_dir, m.name) for m in safe])
                return sum(1 for m in safe if not m.isdir())

        if fmt == "7z" and _HAS_PY7ZR:
            with _py7zr.SevenZipFile(path, "r") as zf:
                names = [n for n in zf.getnames() if _member_matches(n, wanted)]
                if names:
                    zf.extract(path=dest_dir, targets=names)
                if not keep_dates:
                    _stamp_now([os.path.join(dest_dir, n) for n in names])
                return len(names)

        if fmt == "rar" and _HAS_RARFILE:
            with _rarfile.RarFile(path) as rf:
                names = [n for n in rf.namelist() if _member_matches(n, wanted)]
                for i, name in enumerate(names, 1):
                    _tick(i, len(names), name)
                    rf.extract(name, dest_dir)
                if not keep_dates:
                    _stamp_now([os.path.join(dest_dir, n) for n in names])
                return len(names)
    except ArchiveError:
        raise
    except Exception as exc:
        _log(f"archive_extract_members native path failed for {path}: {exc}")

    return _archive_extract_members_7z(path, dest_dir, members, progress)


def _archive_extract_members_7z(path: str, dest_dir: str, members: list,
                                progress=None) -> int:
    """Fallback: `7z x archive -odest member1 member2 …` — 7-Zip extracts a
    named folder's full contents recursively, so this covers files AND
    folders in one call, for whatever format 7-Zip itself can read (this is
    also the only path available for ISO / CAB)."""
    exe = sevenzip_path()
    if not exe:
        raise SevenZipMissing(
            "7-Zip is required for this archive format.\n\n"
            "Install 7-Zip (https://www.7-zip.org) or place 7z.exe in\n"
            f"{APP_ROOT / 'Helpfiles' / 'redigerare'}")
    if progress:
        progress(0, 1, os.path.basename(path))
    args = [exe, "x", path, f"-o{dest_dir}", "-y", "-bso0", "-bsp0"] + list(members)
    try:
        res = subprocess.run(args, capture_output=True, text=True, errors="replace",
                             timeout=3600, **_no_window_kwargs())
    except Exception as exc:
        raise ArchiveError(f"Could not run 7-Zip: {exc}")
    if res.returncode != 0:
        raise ArchiveError(f"7-Zip extraction failed:\n{res.stderr.strip()}")
    if progress:
        progress(1, 1, os.path.basename(path))
    return len(members)


def archive_delete_members(path: str, members: list, progress=None):
    """Remove the given members from a WRITABLE archive (zip / 7z / tar
    family) — powers Move / Delete out of the in-panel archive view.

    Works generically for every format this program can also CREATE: extract
    everything to a temp folder, delete the removed members from that copy,
    re-create the archive from what is left, and swap it in for the
    original.  RAR / ISO / CAB cannot be written by this program (7-Zip
    cannot write RAR; there is no ISO/CAB writer here either) and raise
    instead — those files can still be COPIED out, just not removed from the
    archive itself, the same limitation Total Commander has.
    """
    fmt = archive_format(path)
    if fmt not in PACK_FORMATS:
        raise ArchiveError(
            f"{fmt.upper()} archives are read-only here — files can be "
            "copied out, but not removed from this archive type.")

    wanted = [_norm_member(m) for m in members]
    tmp_extract = tempfile.mkdtemp(prefix="fm_archrw_x_")
    tmp_out_dir = tempfile.mkdtemp(prefix="fm_archrw_o_")
    try:
        archive_extract(path, tmp_extract, progress=progress)
        for e in archive_list(path):
            if not _member_matches(e.name, wanted):
                continue
            local = os.path.join(tmp_extract, *e.name.replace("\\", "/").split("/"))
            try:
                if e.is_dir:
                    shutil.rmtree(local, ignore_errors=True)
                elif os.path.isfile(local):
                    os.remove(local)
            except OSError:
                pass
        sources = [os.path.join(tmp_extract, n) for n in os.listdir(tmp_extract)]
        out_path = os.path.join(tmp_out_dir, os.path.basename(path))
        archive_create(out_path, sources, fmt=fmt, progress=progress)
        _replace_file(out_path, path)
    finally:
        shutil.rmtree(tmp_extract, ignore_errors=True)
        shutil.rmtree(tmp_out_dir, ignore_errors=True)


def _replace_file(src: str, dst: str):
    """Put *src* in place of *dst*.  os.replace is atomic but fails across
    drives (the old archive_delete_members built its new file in the temp
    folder, so an archive on another drive than %TEMP% could not be rewritten);
    shutil.move falls back to copy + delete."""
    try:
        os.replace(src, dst)
    except OSError:
        shutil.move(src, dst)


def archive_add_plan(sources: list, subpath: str = "") -> list:
    """What adding *sources* (files / folders on disk) at archive folder
    *subpath* would write: a list of (disk path, name inside the archive,
    is_empty_folder).  A folder comes along with everything under it."""
    prefix = _norm_member(subpath).strip("/")

    def _arc(rel: str) -> str:
        rel = _norm_member(rel)
        return f"{prefix}/{rel}" if prefix else rel

    plan = []
    for src in sources:
        src  = os.path.abspath(src)
        base = os.path.dirname(src)
        if os.path.isdir(src):
            for root, dirs, files in os.walk(src):
                if not files and not dirs:
                    plan.append((root, _arc(os.path.relpath(root, base)), True))
                for f in files:
                    full = os.path.join(root, f)
                    plan.append((full, _arc(os.path.relpath(full, base)), False))
        elif os.path.isfile(src):
            plan.append((src, _arc(os.path.basename(src)), False))
    return plan


def archive_add_members(path: str, plan: list, progress=None) -> int:
    """Add the files in *plan* (from archive_add_plan) to a WRITABLE archive,
    replacing members of the same name.  The archive file is only swapped for
    the new version once that is complete, so a cancel or a crash leaves the
    original untouched.

    zip      with no name clash the archive is copied and the copy appended to
             (fast, nothing already in it is recompressed); with a clash it is
             rebuilt member by member, minus the names being replaced.
    others   (7z / tar family) extract everything, lay the new files over it,
             re-create — the same route archive_delete_members takes.
    """
    fmt = archive_format(path)
    if fmt not in PACK_FORMATS:
        raise ArchiveError(
            f"{fmt.upper()} archives are read-only here — files can be "
            "copied out, but not added to this archive type.")
    if not plan:
        return 0
    total   = len(plan)
    replace = {a for _f, a, d in plan if not d}
    folder  = os.path.dirname(os.path.abspath(path))
    stamp   = f".fm-new-{os.getpid()}-{int(_time.time())}"

    def _tick(i, name):
        if progress and progress(i, total, name) is False:
            raise ArchiveError("Cancelled by user")

    if fmt == "zip":
        tmp = os.path.join(folder, os.path.basename(path) + stamp)

        def _write_new(zf, have):
            for i, (full, arc, is_dir) in enumerate(plan, 1):
                _tick(i, arc)
                if is_dir and (arc + "/") in have:
                    continue
                zf.write(full, arc)

        try:
            with zipfile.ZipFile(path) as zin:
                have = {_norm_member(n) for n in zin.namelist()}
                have |= set(zin.namelist())
            if replace & have:
                with zipfile.ZipFile(path) as zin, \
                        zipfile.ZipFile(tmp, "w", zipfile.ZIP_DEFLATED) as zout:
                    for info in zin.infolist():
                        if _norm_member(info.filename) in replace:
                            continue
                        ni = zipfile.ZipInfo(info.filename, info.date_time)
                        ni.compress_type = info.compress_type
                        ni.external_attr = info.external_attr
                        ni.comment       = info.comment
                        if info.is_dir():
                            zout.writestr(ni, b"")
                        else:
                            with zin.open(info) as rd, zout.open(
                                    ni, "w", force_zip64=info.file_size
                                    > zipfile.ZIP64_LIMIT) as wr:
                                shutil.copyfileobj(rd, wr, 1024 * 1024)
                    _write_new(zout, have)
            else:
                shutil.copy2(path, tmp)
                with zipfile.ZipFile(tmp, "a", zipfile.ZIP_DEFLATED) as zf:
                    _write_new(zf, have)
            _replace_file(tmp, path)
        finally:
            if os.path.exists(tmp):
                try:
                    os.remove(tmp)
                except OSError:
                    pass
        return sum(1 for _f, _a, d in plan if not d)

    tmp_extract = tempfile.mkdtemp(prefix="fm_archrw_x_")
    tmp_out_dir = tempfile.mkdtemp(prefix="fm_archrw_o_", dir=folder)
    try:
        archive_extract(path, tmp_extract)
        for i, (full, arc, is_dir) in enumerate(plan, 1):
            _tick(i, arc)
            target = os.path.join(tmp_extract, *arc.split("/"))
            if is_dir:
                os.makedirs(target, exist_ok=True)
                continue
            os.makedirs(os.path.dirname(target), exist_ok=True)
            shutil.copy2(full, target)
        top     = [os.path.join(tmp_extract, n) for n in os.listdir(tmp_extract)]
        out     = os.path.join(tmp_out_dir, os.path.basename(path))
        archive_create(out, top, fmt=fmt)
        _replace_file(out, path)
    finally:
        shutil.rmtree(tmp_extract, ignore_errors=True)
        shutil.rmtree(tmp_out_dir, ignore_errors=True)
    return sum(1 for _f, _a, d in plan if not d)


def archive_create(out_path: str, sources: list, fmt: str = "", progress=None):
    """Create an archive from a list of files / folders."""
    fmt = fmt or archive_format(out_path) or "zip"
    if fmt not in PACK_FORMATS:
        raise ArchiveError(f"Cannot create {fmt} archives (reading is supported).")

    # Build the (absolute path, name inside archive) list up front
    members = []
    for src in sources:
        src = os.path.abspath(src)
        base = os.path.dirname(src)
        if os.path.isdir(src):
            for root, _dirs, files in os.walk(src):
                for f in files:
                    full = os.path.join(root, f)
                    members.append((full, os.path.relpath(full, base)))
        elif os.path.isfile(src):
            members.append((src, os.path.basename(src)))
    total = len(members) or 1

    def _tick(i, name):
        if progress and progress(i, total, name) is False:
            raise ArchiveError("Cancelled by user")

    if fmt == "zip":
        with zipfile.ZipFile(out_path, "w", zipfile.ZIP_DEFLATED) as zf:
            for i, (full, arc) in enumerate(members, 1):
                _tick(i, arc)
                zf.write(full, arc)
        return len(members)

    if fmt.startswith("tar"):
        mode = {"tar": "w", "tar.gz": "w:gz",
                "tar.bz2": "w:bz2", "tar.xz": "w:xz"}[fmt]
        with tarfile.open(out_path, mode) as tf:
            for i, (full, arc) in enumerate(members, 1):
                _tick(i, arc)
                tf.add(full, arcname=arc)
        return len(members)

    if fmt == "7z":
        if _HAS_PY7ZR:
            with _py7zr.SevenZipFile(out_path, "w") as zf:
                for i, (full, arc) in enumerate(members, 1):
                    _tick(i, arc)
                    zf.write(full, arc)
            return len(members)
        exe = sevenzip_path()
        if not exe:
            raise ArchiveError("Creating 7z archives needs py7zr or 7-Zip installed.")
        if progress:
            progress(0, 1, os.path.basename(out_path))
        res = subprocess.run([exe, "a", "-t7z", out_path] + [s for s in sources],
                             capture_output=True, text=True, errors="replace",
                             timeout=3600, **_no_window_kwargs())
        if res.returncode != 0:
            raise ArchiveError(f"7-Zip could not create the archive:\n{res.stderr.strip()}")
        return len(members)

    raise ArchiveError(f"Unsupported pack format: {fmt}")


class ArchiveBrowser(tk.Toplevel):
    """Read-only browser for any supported archive, with extract buttons."""

    def __init__(self, parent, manager: "EditorFrame", path: str):
        super().__init__(parent)
        self.manager = manager
        self.path    = path
        self.fmt     = archive_format(path)
        self.entries: list = []

        self.configure(bg=C_BG)
        self.geometry("1120x580")
        _setup_toplevel(self, f"Archive — {os.path.basename(path)}", parent, modal=False)

        head = tk.Frame(self, bg=C_BG3)
        head.pack(fill="x")
        tk.Label(head, text=f"📦  {os.path.basename(path)}", bg=C_BG3, fg=C_ACCENT,
                 font=("Segoe UI", 11, "bold")).pack(side="left", padx=10, pady=6)
        self._info = tk.Label(head, text="Reading…", bg=C_BG3, fg=C_FG_DIM,
                              font=("Segoe UI", 9))
        self._info.pack(side="left", padx=6)

        cols = ("size", "modified")
        self.tree = ttk.Treeview(self, columns=cols, selectmode="extended")
        self.tree.heading("#0",       text="Name",     anchor="w")
        self.tree.heading("size",     text="Size",     anchor="e")
        self.tree.heading("modified", text="Modified", anchor="w")
        self.tree.column("#0", width=780, stretch=True)
        self.tree.column("size", width=110, anchor="e")
        self.tree.column("modified", width=140)
        sb = ttk.Scrollbar(self, orient="vertical", command=self.tree.yview)
        self.tree.configure(yscrollcommand=sb.set)
        self.tree.pack(side="left", fill="both", expand=True, padx=(8, 0), pady=8)
        sb.pack(side="left", fill="y", pady=8)

        btns = tk.Frame(self, bg=C_BG)
        btns.pack(side="right", fill="y", padx=8, pady=8)
        tk.Button(btns, text="Extract all…", width=16, bg="lightgreen", fg="black",
                  command=self._extract_all).pack(pady=3)
        tk.Button(btns, text="Extract here", width=16, bg="lightblue", fg="black",
                  command=self._extract_here).pack(pady=3)
        tk.Button(btns, text="Test archive", width=16, bg="white", fg="black",
                  command=self._test).pack(pady=3)
        tk.Button(btns, text="Close", width=16, bg="grey", fg="white",
                  command=self.destroy).pack(pady=(18, 3))

        self.after(50, self._load)

    def _load(self):
        try:
            self.entries = archive_list(self.path)
        except ArchiveError as exc:
            _archive_error_box(self, exc)
            self.destroy()
            return
        total = sum(e.size for e in self.entries if not e.is_dir)
        files = sum(1 for e in self.entries if not e.is_dir)
        self._info.configure(
            text=f"{self.fmt}   ·   {files} files   ·   {_human_size(total)} uncompressed")
        for e in sorted(self.entries, key=lambda x: (not x.is_dir, x.name.lower())):
            self.tree.insert("", "end", text=e.name,
                             values=("" if e.is_dir else _human_size(e.size),
                                     e.modified),
                             tags=("dir",) if e.is_dir else ())
        self.tree.tag_configure("dir", foreground=TC_INFO)

    def _extract_here(self):
        self._do_extract(os.path.dirname(self.path))

    def _extract_all(self):
        dest = filedialog.askdirectory(
            title="Extract to…", parent=self,
            initialdir=self.manager.get_active_panel().current_path)
        if dest:
            self._do_extract(dest)

    def _do_extract(self, dest: str):
        dlg = _ProgressDialog(self, f"Extracting {os.path.basename(self.path)}",
                              total=len(self.entries) or 1)

        def on_progress(i, total, name):
            dlg.post("progress", i, total, name)
            return not dlg.cancelled      # False here aborts the extraction

        def worker():
            try:
                archive_extract(self.path, dest, progress=on_progress)
                self.after(0, lambda: self._done(dlg, dest))
            except Exception as exc:
                self.after(0, lambda e=exc: self._fail(dlg, e))

        threading.Thread(target=worker, daemon=True).start()

    def _done(self, dlg, dest):
        dlg.post("done")
        self.manager.refresh_panels()
        _flash_ok(self, f"Extracted to\n{dest}", "Extracted")

    def _fail(self, dlg, exc):
        dlg.post("done")
        if "Cancelled" in str(exc):
            return
        messagebox.showerror("Extract failed", str(exc), parent=self)

    def _test(self):
        exe = sevenzip_path()
        if not exe:
            _archive_error_box(self, SevenZipMissing(
                "Testing needs 7-Zip installed.\n\n"
                "Install 7-Zip (https://www.7-zip.org) or place 7z.exe in\n"
                f"{APP_ROOT / 'Helpfiles' / 'redigerare'}"))
            return
        try:
            res = subprocess.run([exe, "t", self.path], capture_output=True,
                                 text=True, errors="replace", timeout=1800,
                                 **_no_window_kwargs())
            if res.returncode == 0:
                _flash_ok(self, "Archive tested OK — no errors found.", "Test")
            else:
                messagebox.showerror("Test archive",
                                     res.stdout[-2000:] or res.stderr[-2000:],
                                     parent=self)
        except Exception as exc:
            messagebox.showerror("Test archive", str(exc), parent=self)


# ══════════════════════════════════════════════════════════════════════════
#  DEL 21 — Multi-Rename tool  (Ctrl+M)
# ══════════════════════════════════════════════════════════════════════════

MULTIRENAME_HELP = """\
Placeholders for the name / extension templates
-----------------------------------------------
  [N]        Full original name (without extension)
  [N2-5]     Characters 2 to 5 of the original name
  [N3-]      From character 3 to the end
  [N-4]      The last 4 characters
  [E]        Original extension (without the dot)
  [C]        Counter — uses the Start / Step / Digits fields
  [C:10:2:4] Counter starting at 10, step 2, padded to 4 digits
  [P]        Name of the parent folder
  [Y] [M] [D]  Year / month / day of the file's modified date
  [h] [m] [s]  Hour / minute / second of the file's modified date
  [d]        Full date  (YYYY-MM-DD)
  [t]        Full time  (HH-MM-SS)
  [G]        File size in bytes

Search / replace
----------------
  Plain text by default.  Tick "Regular expression" to use regex, where the
  replacement may reference groups as \\1, \\2 …
  Search and replace run AFTER the templates have been applied.

Case
----
  Unchanged / lowercase / UPPERCASE / Title Case / First letter upper.

Safety
------
  The preview marks problems in red: duplicate target names, illegal
  characters, and names that already exist.  Rename stays disabled until
  every conflict is resolved.  "Undo last rename" reverts the whole batch.
"""


def _apply_name_template(template: str, path: str, index: int,
                         c_start: int, c_step: int, c_digits: int) -> str:
    """Expand the multi-rename placeholders for one file."""
    folder, filename = os.path.split(path)
    base, ext = os.path.splitext(filename)
    ext = ext.lstrip(".")
    try:
        st = os.stat(path)
        dt = datetime.fromtimestamp(st.st_mtime)
        size = st.st_size
    except Exception:
        dt, size = datetime.now(), 0

    def counter(m):
        start  = int(m.group(1)) if m.group(1) else c_start
        step   = int(m.group(2)) if m.group(2) else c_step
        digits = int(m.group(3)) if m.group(3) else c_digits
        return str(start + index * step).zfill(digits)

    def name_slice(m):
        """[N], [N2-5], [N3-], [N-4]"""
        spec = m.group(1)
        if not spec:
            return base
        if spec.startswith("-"):                      # [N-4] = last 4 chars
            try:
                return base[-int(spec[1:]):]
            except Exception:
                return base
        if "-" in spec:                               # [N2-5] or [N3-]
            a, _, b = spec.partition("-")
            try:
                start = max(0, int(a) - 1)
            except Exception:
                start = 0
            if b == "":
                return base[start:]
            try:
                return base[start:int(b)]
            except Exception:
                return base[start:]
        try:                                          # [N3] = single character
            i = int(spec) - 1
            return base[i] if 0 <= i < len(base) else ""
        except Exception:
            return base

    out = template
    out = _re.sub(r"\[C(?::(\d+))?(?::(\d+))?(?::(\d+))?\]", counter, out)
    out = _re.sub(r"\[N([\d\-]*)\]", name_slice, out)
    replacements = {
        "[E]": ext,
        "[P]": os.path.basename(folder),
        "[Y]": f"{dt:%Y}", "[M]": f"{dt:%m}", "[D]": f"{dt:%d}",
        "[h]": f"{dt:%H}", "[m]": f"{dt:%M}", "[s]": f"{dt:%S}",
        "[d]": f"{dt:%Y-%m-%d}", "[t]": f"{dt:%H-%M-%S}",
        "[G]": str(size),
    }
    for k, v in replacements.items():
        out = out.replace(k, v)
    return out


_ILLEGAL_NAME_CHARS = set('<>:"/\\|?*')


def _name_problem(name: str) -> str:
    """Return a short description of why a filename is invalid, or ''."""
    if not name.strip():
        return "empty name"
    bad = sorted(set(name) & _ILLEGAL_NAME_CHARS)
    if bad:
        return "illegal character " + " ".join(bad)
    if name.rstrip() != name or name.endswith("."):
        return "trailing space or dot"
    stem = os.path.splitext(name)[0].upper()
    if stem in {"CON", "PRN", "AUX", "NUL"} or _re.fullmatch(r"(COM|LPT)\d", stem):
        return "reserved Windows name"
    if len(name) > 255:
        return "name too long"
    return ""


class MultiRenameWindow(tk.Toplevel):
    """Total-Commander style batch rename with live preview and undo."""

    def __init__(self, manager: "EditorFrame", paths: list):
        super().__init__(manager)
        self.manager = manager
        self.paths   = [p for p in paths if os.path.exists(p)]
        self._last_batch: list = []      # [(new_path, old_path)] for undo

        self.configure(bg=C_BG)
        self.geometry("1000x680")
        _setup_toplevel(self, "Multi-Rename Tool", manager, modal=False)

        self._build_ui()
        self._update_preview()

    # ── UI ────────────────────────────────────────────────────────────────

    def _build_ui(self):
        top = tk.Frame(self, bg=C_BG3)
        top.pack(fill="x")
        tk.Label(top, text="✎  Multi-Rename Tool", bg=C_BG3, fg=C_ACCENT,
                 font=("Segoe UI", 12, "bold")).pack(side="left", padx=10, pady=7)
        tk.Label(top, text=f"{len(self.paths)} item(s) selected", bg=C_BG3,
                 fg=C_FG_DIM, font=("Segoe UI", 9)).pack(side="left")
        tk.Button(top, text="?  Placeholders", bg="white", fg="black",
                  command=self._show_help).pack(side="right", padx=8, pady=4)

        form = tk.Frame(self, bg=C_BG)
        form.pack(fill="x", padx=10, pady=(8, 4))

        # Row 1 — name / extension templates
        r1 = tk.Frame(form, bg=C_BG)
        r1.pack(fill="x", pady=2)
        tk.Label(r1, text="Name:", bg=C_BG, fg=C_FG, width=10,
                 anchor="w").pack(side="left")
        self.var_name = tk.StringVar(value="[N]")
        e = tk.Entry(r1, textvariable=self.var_name, bg=C_BG2, fg=C_FG,
                     insertbackground=C_FG,
                     insertofftime=0, insertontime=9999999)
        e.pack(side="left", fill="x", expand=True)
        tk.Label(r1, text="Extension:", bg=C_BG, fg=C_FG,
                 width=11, anchor="e").pack(side="left", padx=(8, 4))
        self.var_ext = tk.StringVar(value="[E]")
        e2 = tk.Entry(r1, textvariable=self.var_ext, width=14, bg=C_BG2, fg=C_FG,
                      insertbackground=C_FG,
                      insertofftime=0, insertontime=9999999)
        e2.pack(side="left")

        # Row 2 — search / replace
        r2 = tk.Frame(form, bg=C_BG)
        r2.pack(fill="x", pady=2)
        tk.Label(r2, text="Search:", bg=C_BG, fg=C_FG, width=10,
                 anchor="w").pack(side="left")
        self.var_search = tk.StringVar()
        e3 = tk.Entry(r2, textvariable=self.var_search, bg=C_BG2, fg=C_FG,
                      insertbackground=C_FG,
                      insertofftime=0, insertontime=9999999)
        e3.pack(side="left", fill="x", expand=True)
        tk.Label(r2, text="Replace:", bg=C_BG, fg=C_FG, width=11,
                 anchor="e").pack(side="left", padx=(8, 4))
        self.var_replace = tk.StringVar()
        e4 = tk.Entry(r2, textvariable=self.var_replace, bg=C_BG2, fg=C_FG,
                      insertbackground=C_FG,
                      insertofftime=0, insertontime=9999999)
        e4.pack(side="left", fill="x", expand=True)

        # Row 3 — options
        r3 = tk.Frame(form, bg=C_BG)
        r3.pack(fill="x", pady=(6, 2))
        self.var_regex = tk.BooleanVar(value=False)
        self.var_case_sensitive = tk.BooleanVar(value=False)
        tk.Checkbutton(r3, text="Regular expression", variable=self.var_regex,
                       bg=C_BG, fg=C_FG, selectcolor=C_BG2,
                       activebackground=C_BG, activeforeground=C_FG,
                       command=self._update_preview).pack(side="left")
        tk.Checkbutton(r3, text="Case sensitive", variable=self.var_case_sensitive,
                       bg=C_BG, fg=C_FG, selectcolor=C_BG2,
                       activebackground=C_BG, activeforeground=C_FG,
                       command=self._update_preview).pack(side="left", padx=(10, 0))

        tk.Label(r3, text="Case:", bg=C_BG, fg=C_FG).pack(side="left", padx=(20, 4))
        self.var_case = tk.StringVar(value="unchanged")
        case_cb = ttk.Combobox(r3, textvariable=self.var_case, width=16,
                               state="readonly",
                               values=["unchanged", "lowercase", "UPPERCASE",
                                       "Title Case", "First letter upper"])
        case_cb.pack(side="left")
        case_cb.bind("<<ComboboxSelected>>", lambda e: self._update_preview())

        # Row 4 — counter settings
        r4 = tk.Frame(form, bg=C_BG)
        r4.pack(fill="x", pady=2)
        tk.Label(r4, text="Counter:", bg=C_BG, fg=C_FG, width=10,
                 anchor="w").pack(side="left")
        self.var_cstart  = tk.StringVar(value="1")
        self.var_cstep   = tk.StringVar(value="1")
        self.var_cdigits = tk.StringVar(value="2")
        for label, var, w in (("Start", self.var_cstart, 6),
                              ("Step", self.var_cstep, 6),
                              ("Digits", self.var_cdigits, 4)):
            tk.Label(r4, text=label, bg=C_BG, fg=C_FG_DIM).pack(side="left", padx=(6, 2))
            ent = tk.Entry(r4, textvariable=var, width=w, bg=C_BG2, fg=C_FG,
                           insertbackground=C_FG,
                           insertofftime=0, insertontime=9999999)
            ent.pack(side="left")

        # Live preview on every keystroke
        for var in (self.var_name, self.var_ext, self.var_search,
                    self.var_replace, self.var_cstart, self.var_cstep,
                    self.var_cdigits):
            var.trace_add("write", lambda *_: self._update_preview())

        # Preset buttons
        r5 = tk.Frame(form, bg=C_BG)
        r5.pack(fill="x", pady=(6, 0))
        tk.Label(r5, text="Presets:", bg=C_BG, fg=C_FG_DIM,
                 width=10, anchor="w").pack(side="left")
        for label, nm, ex in (
                ("Name + number", "[N]_[C]", "[E]"),
                ("Number + name", "[C]_[N]", "[E]"),
                ("Date + name",   "[d]_[N]", "[E]"),
                ("Folder + number", "[P]_[C]", "[E]"),
                ("Reset",         "[N]",     "[E]")):
            tk.Button(r5, text=label, bg="white", fg="black",
                      font=("Segoe UI", 8),
                      command=lambda n=nm, x=ex: self._apply_preset(n, x)
                      ).pack(side="left", padx=2)

        # ── Preview list ──────────────────────────────────────────────────
        mid = tk.Frame(self, bg=C_BG)
        mid.pack(fill="both", expand=True, padx=10, pady=6)
        self.tree = ttk.Treeview(mid, columns=("new", "status"),
                                 selectmode="extended")
        self.tree.heading("#0",     text="Current name", anchor="w")
        self.tree.heading("new",    text="New name",     anchor="w")
        self.tree.heading("status", text="Status",       anchor="w")
        self.tree.column("#0",  width=340, stretch=True)
        self.tree.column("new", width=340, stretch=True)
        self.tree.column("status", width=170)
        sb = ttk.Scrollbar(mid, orient="vertical", command=self.tree.yview)
        self.tree.configure(yscrollcommand=sb.set)
        self.tree.pack(side="left", fill="both", expand=True)
        sb.pack(side="right", fill="y")
        self.tree.tag_configure("bad",       foreground=TC_BAD)
        self.tree.tag_configure("unchanged", foreground=TC_MUTED)
        self.tree.tag_configure("ok",        foreground=TC_OK)

        # ── Buttons ───────────────────────────────────────────────────────
        bot = tk.Frame(self, bg=C_BG)
        bot.pack(fill="x", padx=10, pady=(0, 10))
        self._status = tk.Label(bot, text="", bg=C_BG, fg=C_FG_DIM,
                                font=("Segoe UI", 9), anchor="w")
        self._status.pack(side="left", fill="x", expand=True)
        self._undo_btn = tk.Button(bot, text="↶  Undo last rename", bg="white",
                                   fg="black", state="disabled",
                                   command=self._undo)
        self._undo_btn.pack(side="right", padx=4)
        self._go_btn = tk.Button(bot, text="✔  Rename", bg="lightgreen",
                                 fg="black", width=14, command=self._do_rename)
        self._go_btn.pack(side="right", padx=4)
        tk.Button(bot, text="Close", bg="grey", fg="white", width=10,
                  command=self.destroy).pack(side="right", padx=4)

        # ENTER runs the rename, as everywhere else in the program
        self.bind("<Return>", lambda e: self._do_rename())

    def _apply_preset(self, name_tpl: str, ext_tpl: str):
        self.var_name.set(name_tpl)
        self.var_ext.set(ext_tpl)

    def _show_help(self):
        top = tk.Toplevel(self)
        top.configure(bg=C_BG)
        top.geometry("640x560")
        _setup_toplevel(top, "Multi-Rename — placeholders", self, modal=False)
        txt = tk.Text(top, bg=C_BG2, fg=C_FG, wrap="word", padx=12, pady=10,
                      font=("Consolas", 10),
                      insertofftime=0, insertontime=9999999)
        sb = ttk.Scrollbar(top, orient="vertical", command=txt.yview)
        txt.configure(yscrollcommand=sb.set)
        txt.pack(side="left", fill="both", expand=True)
        sb.pack(side="right", fill="y")
        txt.insert("1.0", MULTIRENAME_HELP)
        txt.configure(state="disabled")

    # ── Preview / rename ──────────────────────────────────────────────────

    def _int(self, var, default):
        try:
            return int(var.get())
        except Exception:
            return default

    def _compute(self) -> list:
        """Return [(old_path, new_name, problem)] for the current settings."""
        c_start  = self._int(self.var_cstart, 1)
        c_step   = self._int(self.var_cstep, 1)
        c_digits = self._int(self.var_cdigits, 2)
        name_tpl = self.var_name.get()
        ext_tpl  = self.var_ext.get()
        search   = self.var_search.get()
        replace  = self.var_replace.get()
        use_re   = self.var_regex.get()
        case_sen = self.var_case_sensitive.get()
        case_mode = self.var_case.get()

        rows = []
        for i, path in enumerate(self.paths):
            try:
                base = _apply_name_template(name_tpl, path, i, c_start, c_step, c_digits)
                ext  = _apply_name_template(ext_tpl, path, i, c_start, c_step, c_digits)
                new  = f"{base}.{ext}" if ext else base

                if search:
                    if use_re:
                        flags = 0 if case_sen else _re.IGNORECASE
                        new = _re.sub(search, replace, new, flags=flags)
                    elif case_sen:
                        new = new.replace(search, replace)
                    else:
                        # Case-insensitive plain replace
                        new = _re.sub(_re.escape(search), replace.replace("\\", "\\\\"),
                                      new, flags=_re.IGNORECASE)

                if case_mode == "lowercase":
                    new = new.lower()
                elif case_mode == "UPPERCASE":
                    new = new.upper()
                elif case_mode == "Title Case":
                    stem, dot, x = new.rpartition(".")
                    new = (stem.title() + dot + x) if dot else new.title()
                elif case_mode == "First letter upper":
                    new = new[:1].upper() + new[1:].lower() if new else new

                rows.append([path, new, _name_problem(new)])
            except _re.error as exc:
                rows.append([path, os.path.basename(path), f"regex error: {exc}"])
            except Exception as exc:
                rows.append([path, os.path.basename(path), f"error: {exc}"])

        # Duplicate detection (case-insensitive, per folder)
        seen = {}
        for row in rows:
            key = (os.path.dirname(row[0]).lower(), row[1].lower())
            seen.setdefault(key, []).append(row)
        for key, group in seen.items():
            if len(group) > 1:
                for row in group:
                    if not row[2]:
                        row[2] = "duplicate target name"

        # Collision with existing files that are not part of this batch
        batch = {p.lower() for p in self.paths}
        for row in rows:
            if row[2]:
                continue
            target = os.path.join(os.path.dirname(row[0]), row[1])
            if (target.lower() != row[0].lower() and os.path.exists(target)
                    and target.lower() not in batch):
                row[2] = "target already exists"
        return rows

    def _update_preview(self, *_):
        rows = self._compute()
        self.tree.delete(*self.tree.get_children())
        n_bad = n_changed = 0
        for old, new, problem in rows:
            cur = os.path.basename(old)
            if problem:
                tag, status = "bad", problem
                n_bad += 1
            elif new == cur:
                tag, status = "unchanged", "unchanged"
            else:
                tag, status = "ok", "will be renamed"
                n_changed += 1
            self.tree.insert("", "end", text=cur, values=(new, status), tags=(tag,))

        if n_bad:
            self._status.configure(
                text=f"{n_bad} problem(s) — fix them before renaming", fg="#ff6b6b")
            self._go_btn.configure(state="disabled")
        else:
            self._status.configure(
                text=f"{n_changed} file(s) will be renamed", fg=C_FG_DIM)
            self._go_btn.configure(state="normal" if n_changed else "disabled")

    def _do_rename(self):
        rows = [r for r in self._compute()
                if not r[2] and r[1] != os.path.basename(r[0])]
        if not rows:
            return
        if any(r[2] for r in self._compute()):
            return

        # Two-phase rename via temporary names, so swaps (a→b, b→a) work
        done, errors = [], []
        temps = []
        try:
            for old, new, _ in rows:
                tmp = os.path.join(os.path.dirname(old),
                                   f".fm_rename_{os.getpid()}_{len(temps)}.tmp")
                try:
                    os.rename(old, tmp)
                    temps.append((tmp, os.path.join(os.path.dirname(old), new), old))
                except Exception as exc:
                    errors.append(f"{os.path.basename(old)}: {exc}")
            for tmp, final, original in temps:
                try:
                    os.rename(tmp, final)
                    done.append((final, original))
                except Exception as exc:
                    errors.append(f"{os.path.basename(original)}: {exc}")
                    try:            # put it back under its old name
                        os.rename(tmp, original)
                    except Exception:
                        pass
        except Exception as exc:
            errors.append(str(exc))

        # Tags are keyed by path — take them along to the new names
        if done:
            try:
                self.manager.tagstore.remap([(old, new) for new, old in done])
            except Exception as exc:
                _log(f"Multi-rename: could not move tags: {exc}")

        self._last_batch = done
        self._undo_btn.configure(state="normal" if done else "disabled")
        self.paths = [d[0] for d in done] + [
            p for p in self.paths if p not in {d[1] for d in done}]
        self.manager.refresh_panels()
        self._update_preview()

        if errors:
            messagebox.showerror(
                "Rename",
                f"Renamed {len(done)} file(s).\n\nFailed:\n" + "\n".join(errors[:15]),
                parent=self)
        else:
            _flash_ok(self, f"Renamed {len(done)} file(s).", "Renamed")
        _log(f"Multi-rename: {len(done)} renamed, {len(errors)} errors")

    def _undo(self):
        if not self._last_batch:
            return
        restored, errors = 0, []
        for new_path, old_path in self._last_batch:
            try:
                if os.path.exists(new_path):
                    os.rename(new_path, old_path)
                    restored += 1
            except Exception as exc:
                errors.append(f"{os.path.basename(new_path)}: {exc}")
        try:
            self.manager.tagstore.remap([(new, old)
                                         for new, old in self._last_batch])
        except Exception as exc:
            _log(f"Multi-rename undo: could not move tags back: {exc}")
        self.paths = [b[1] for b in self._last_batch]
        self._last_batch = []
        self._undo_btn.configure(state="disabled")
        self.manager.refresh_panels()
        self._update_preview()
        if errors:
            messagebox.showerror("Undo", "\n".join(errors[:15]), parent=self)
        else:
            _flash_ok(self, f"Restored {restored} original name(s).", "Undo")


# ══════════════════════════════════════════════════════════════════════════
#  DEL 22 — File compare  (line diff and byte/hex diff)
# ══════════════════════════════════════════════════════════════════════════

def _read_text_lines(path: str, max_bytes: int = 20 * 1024 * 1024):
    """Read a file as text lines. Returns (lines, encoding) or raises."""
    with open(path, "rb") as fh:
        raw = fh.read(max_bytes)
    for enc in ("utf-8-sig", "utf-8", "cp1252", "latin-1"):
        try:
            return raw.decode(enc).splitlines(), enc
        except UnicodeDecodeError:
            continue
    return raw.decode("latin-1", "replace").splitlines(), "latin-1"


def _looks_binary(path: str) -> bool:
    """Heuristic: a NUL byte in the first 8 KB means binary."""
    try:
        with open(path, "rb") as fh:
            chunk = fh.read(8192)
        return b"\x00" in chunk
    except Exception:
        return False


class CompareFilesWindow(tk.Toplevel):
    """Side-by-side comparison of two files — text diff or byte/hex diff."""

    # Colours for the diff marking
    COL_SAME    = None
    COL_CHANGE  = "#4a4a22"     # changed line  (olive)
    COL_ADD     = "#1f3d24"     # only on this side (green)
    COL_DEL     = "#4a2222"     # missing on this side (red)
    COL_FILLER  = "#2a2a3d"     # padding to keep the sides aligned

    def __init__(self, manager: "EditorFrame", left: str, right: str):
        super().__init__(manager)
        self.manager = manager
        self.left    = left
        self.right   = right
        self._diff_positions: list = []   # line numbers of differences
        self._diff_idx = -1

        self.configure(bg=C_BG)
        self.geometry("1280x760")
        _setup_toplevel(self, "Compare files", manager, modal=False)

        self._build_ui()
        self.after(50, self._compare)

    def _build_ui(self):
        head = tk.Frame(self, bg=C_BG3)
        head.pack(fill="x")
        tk.Label(head, text="⇄  Compare files", bg=C_BG3, fg=C_ACCENT,
                 font=("Segoe UI", 12, "bold")).pack(side="left", padx=10, pady=7)

        self.var_mode = tk.StringVar(value="text")
        for label, val in (("Text (line by line)", "text"), ("Binary (hex)", "binary")):
            tk.Radiobutton(head, text=label, value=val, variable=self.var_mode,
                           bg=C_BG3, fg=C_FG, selectcolor=C_BG,
                           activebackground=C_BG3, activeforeground=C_FG,
                           command=self._compare).pack(side="left", padx=6)

        self.var_ignore_ws = tk.BooleanVar(value=False)
        tk.Checkbutton(head, text="Ignore whitespace", variable=self.var_ignore_ws,
                       bg=C_BG3, fg=C_FG, selectcolor=C_BG,
                       activebackground=C_BG3, activeforeground=C_FG,
                       command=self._compare).pack(side="left", padx=(12, 0))

        tk.Button(head, text="⇅  Swap sides", bg="white", fg="black",
                  command=self._swap).pack(side="right", padx=(4, 8), pady=4)
        tk.Button(head, text="▼ Next diff", bg="lightblue", fg="black",
                  command=lambda: self._jump(1)).pack(side="right", padx=2, pady=4)
        tk.Button(head, text="▲ Prev diff", bg="lightblue", fg="black",
                  command=lambda: self._jump(-1)).pack(side="right", padx=2, pady=4)

        # File name headers
        names = tk.Frame(self, bg=C_BG2)
        names.pack(fill="x")
        self._lbl_left = tk.Label(names, text="", bg=C_BG2, fg=C_FG, anchor="w",
                                  font=("Segoe UI", 9, "bold"))
        self._lbl_right = tk.Label(names, text="", bg=C_BG2, fg=C_FG, anchor="w",
                                   font=("Segoe UI", 9, "bold"))
        self._lbl_left.pack(side="left", fill="x", expand=True, padx=8, pady=3)
        self._lbl_right.pack(side="left", fill="x", expand=True, padx=8, pady=3)

        # Two synchronised text views
        body = tk.Frame(self, bg=C_BG)
        body.pack(fill="both", expand=True)

        self.txt_left  = tk.Text(body, wrap="none", bg=C_BG2, fg=C_FG,
                                 font=("Consolas", 9), padx=6, pady=4,
                                 insertofftime=0, insertontime=9999999)
        self.txt_right = tk.Text(body, wrap="none", bg=C_BG2, fg=C_FG,
                                 font=("Consolas", 9), padx=6, pady=4,
                                 insertofftime=0, insertontime=9999999)
        vsb = ttk.Scrollbar(body, orient="vertical", command=self._yview_both)
        hsb = ttk.Scrollbar(self, orient="horizontal", command=self._xview_both)

        self.txt_left.configure(yscrollcommand=self._on_yscroll,
                                xscrollcommand=hsb.set)
        self.txt_right.configure(yscrollcommand=self._on_yscroll,
                                 xscrollcommand=hsb.set)

        self.txt_left.pack(side="left", fill="both", expand=True)
        self.txt_right.pack(side="left", fill="both", expand=True)
        vsb.pack(side="right", fill="y")
        hsb.pack(fill="x")
        self._vsb = vsb

        for t in (self.txt_left, self.txt_right):
            t.tag_configure("change", background=self.COL_CHANGE)
            t.tag_configure("add",    background=self.COL_ADD)
            t.tag_configure("del",    background=self.COL_DEL)
            t.tag_configure("filler", background=self.COL_FILLER, foreground=C_FG_DIM)
            t.bind("<MouseWheel>", self._on_wheel)

        self._status = tk.Label(self, text="", bg=C_BG3, fg=C_FG_DIM, anchor="w",
                                font=("Segoe UI", 9))
        self._status.pack(fill="x", side="bottom")

    # ── Synchronised scrolling ────────────────────────────────────────────

    def _yview_both(self, *args):
        self.txt_left.yview(*args)
        self.txt_right.yview(*args)

    def _xview_both(self, *args):
        self.txt_left.xview(*args)
        self.txt_right.xview(*args)

    def _on_yscroll(self, first, last):
        self._vsb.set(first, last)
        # Keep both panes locked together
        self.txt_left.yview_moveto(first)
        self.txt_right.yview_moveto(first)

    def _on_wheel(self, event):
        delta = -1 * (event.delta // 120)
        self.txt_left.yview_scroll(delta, "units")
        self.txt_right.yview_scroll(delta, "units")
        return "break"

    def _swap(self):
        self.left, self.right = self.right, self.left
        self._compare()

    # ── Comparison ────────────────────────────────────────────────────────

    def _compare(self):
        self._lbl_left.configure(text=f"◀  {self.left}")
        self._lbl_right.configure(text=f"▶  {self.right}")
        for t in (self.txt_left, self.txt_right):
            t.configure(state="normal")
            t.delete("1.0", "end")
        self._diff_positions = []
        self._diff_idx = -1

        try:
            if self.var_mode.get() == "binary":
                self._compare_binary()
            else:
                self._compare_text()
        except Exception as exc:
            messagebox.showerror("Compare", f"Could not compare:\n{exc}", parent=self)
        for t in (self.txt_left, self.txt_right):
            t.configure(state="disabled")

    def _compare_text(self):
        if _looks_binary(self.left) or _looks_binary(self.right):
            self._status.configure(
                text="One of the files looks binary — switch to Binary (hex) mode "
                     "for a meaningful comparison.")
        a, enc_a = _read_text_lines(self.left)
        b, enc_b = _read_text_lines(self.right)

        if self.var_ignore_ws.get():
            key_a = [l.strip() for l in a]
            key_b = [l.strip() for l in b]
        else:
            key_a, key_b = a, b

        sm = difflib.SequenceMatcher(None, key_a, key_b, autojunk=False)
        row = 1
        n_change = n_add = n_del = 0

        def put(text_widget, num, text, tag):
            text_widget.insert("end", f"{num:>6} │ {text}\n" if num
                               else f"       │ {text}\n",
                               (tag,) if tag else ())

        for op, i1, i2, j1, j2 in sm.get_opcodes():
            if op == "equal":
                for k in range(i2 - i1):
                    put(self.txt_left,  i1 + k + 1, a[i1 + k], None)
                    put(self.txt_right, j1 + k + 1, b[j1 + k], None)
                    row += 1
            elif op == "replace":
                span = max(i2 - i1, j2 - j1)
                self._diff_positions.append(row)
                n_change += span
                for k in range(span):
                    if k < i2 - i1:
                        put(self.txt_left, i1 + k + 1, a[i1 + k], "change")
                    else:
                        put(self.txt_left, 0, "", "filler")
                    if k < j2 - j1:
                        put(self.txt_right, j1 + k + 1, b[j1 + k], "change")
                    else:
                        put(self.txt_right, 0, "", "filler")
                    row += 1
            elif op == "delete":
                self._diff_positions.append(row)
                n_del += i2 - i1
                for k in range(i2 - i1):
                    put(self.txt_left, i1 + k + 1, a[i1 + k], "del")
                    put(self.txt_right, 0, "", "filler")
                    row += 1
            elif op == "insert":
                self._diff_positions.append(row)
                n_add += j2 - j1
                for k in range(j2 - j1):
                    put(self.txt_left, 0, "", "filler")
                    put(self.txt_right, j1 + k + 1, b[j1 + k], "add")
                    row += 1

        ratio = sm.ratio()
        if not self._diff_positions:
            self._status.configure(
                text=f"The files are identical  ({len(a)} lines, {enc_a} / {enc_b})",
                fg="#7ee787")
        else:
            self._status.configure(
                text=(f"{len(self._diff_positions)} difference block(s)   ·   "
                      f"{n_change} changed, {n_add} only right, {n_del} only left   ·   "
                      f"{ratio:.1%} similar   ·   {enc_a} / {enc_b}"),
                fg=C_FG_DIM)

    def _compare_binary(self):
        CHUNK = 16
        LIMIT = 4 * 1024 * 1024        # cap the hex view at 4 MB per side
        with open(self.left, "rb") as fh:
            a = fh.read(LIMIT)
        with open(self.right, "rb") as fh:
            b = fh.read(LIMIT)

        def hex_row(data: bytes, off: int) -> str:
            chunk = data[off:off + CHUNK]
            hexs  = " ".join(f"{c:02X}" for c in chunk).ljust(CHUNK * 3 - 1)
            ascii_ = "".join(chr(c) if 32 <= c < 127 else "." for c in chunk)
            return f"{off:08X}  {hexs}  {ascii_}"

        n = max(len(a), len(b))
        rows = (n + CHUNK - 1) // CHUNK
        n_diff = 0
        for r in range(rows):
            off = r * CHUNK
            ca, cb = a[off:off + CHUNK], b[off:off + CHUNK]
            tag = None if ca == cb else "change"
            if tag:
                n_diff += 1
                self._diff_positions.append(r + 1)
            self.txt_left.insert("end", hex_row(a, off) + "\n",
                                 (tag,) if tag else ())
            self.txt_right.insert("end", hex_row(b, off) + "\n",
                                  (tag,) if tag else ())

        first_diff = next((i for i, (x, y) in enumerate(zip(a, b)) if x != y),
                          None)
        if first_diff is None and len(a) == len(b):
            self._status.configure(
                text=f"The files are byte-for-byte identical  ({_human_size(len(a))})",
                fg="#7ee787")
        else:
            where = (f"first difference at offset 0x{first_diff:X} ({first_diff})"
                     if first_diff is not None else "identical up to the shorter length")
            self._status.configure(
                text=(f"{n_diff} differing 16-byte row(s)   ·   {where}   ·   "
                      f"sizes {_human_size(len(a))} / {_human_size(len(b))}"),
                fg=C_FG_DIM)

    def _jump(self, direction: int):
        if not self._diff_positions:
            return
        self._diff_idx = (self._diff_idx + direction) % len(self._diff_positions)
        line = self._diff_positions[self._diff_idx]
        self.txt_left.see(f"{line}.0")
        self.txt_right.see(f"{line}.0")
        self._status.configure(
            text=f"Difference {self._diff_idx + 1} of {len(self._diff_positions)} "
                 f"— line {line}")


# ══════════════════════════════════════════════════════════════════════════
#  DEL 23 — Directory synchronize
# ══════════════════════════════════════════════════════════════════════════

SYNC_ONLY_LEFT   = "only left"
SYNC_ONLY_RIGHT  = "only right"
SYNC_LEFT_NEWER  = "left newer"
SYNC_RIGHT_NEWER = "right newer"
SYNC_DIFFERENT   = "different"
SYNC_EQUAL       = "equal"


def _file_hash(path: str, algo: str = "sha256", chunk: int = 1 << 20,
               cancel=None) -> str:
    """Hash a file in chunks. `cancel` is a callable returning True to abort."""
    if algo == "crc32":
        crc = 0
        with open(path, "rb") as fh:
            while True:
                if cancel and cancel():
                    return ""
                data = fh.read(chunk)
                if not data:
                    break
                crc = zlib.crc32(data, crc)
        return f"{crc & 0xFFFFFFFF:08X}"
    h = hashlib.new(algo)
    with open(path, "rb") as fh:
        while True:
            if cancel and cancel():
                return ""
            data = fh.read(chunk)
            if not data:
                break
            h.update(data)
    return h.hexdigest()


class SyncWindow(tk.Toplevel):
    """Compare two folder trees and copy only what differs."""

    def __init__(self, manager: "EditorFrame", left_dir: str, right_dir: str):
        super().__init__(manager)
        self.manager = manager
        self.rows: list = []           # dicts describing each compared file
        self._stop = threading.Event()
        self._busy = False

        self.configure(bg=C_BG)
        self.geometry("1180x720")
        _setup_toplevel(self, "Synchronize directories", manager, modal=False)

        self.var_left  = tk.StringVar(value=left_dir)
        self.var_right = tk.StringVar(value=right_dir)
        self.var_recursive = tk.BooleanVar(value=True)
        self.var_by_content = tk.BooleanVar(value=False)
        self.var_filter = tk.StringVar(value="*")

        self._build_ui()
        self.bind("<Return>", lambda e: self._start_compare())

    def _build_ui(self):
        head = tk.Frame(self, bg=C_BG3)
        head.pack(fill="x")
        tk.Label(head, text="⇆  Synchronize directories", bg=C_BG3, fg=C_ACCENT,
                 font=("Segoe UI", 12, "bold")).pack(side="left", padx=10, pady=7)

        # Folder pickers
        picks = tk.Frame(self, bg=C_BG)
        picks.pack(fill="x", padx=10, pady=(8, 2))
        for label, var in (("Left:", self.var_left), ("Right:", self.var_right)):
            row = tk.Frame(picks, bg=C_BG)
            row.pack(fill="x", pady=2)
            tk.Label(row, text=label, bg=C_BG, fg=C_FG, width=7,
                     anchor="w").pack(side="left")
            ent = tk.Entry(row, textvariable=var, bg=C_BG2, fg=C_FG,
                           insertbackground=C_FG,
                           insertofftime=0, insertontime=9999999)
            ent.pack(side="left", fill="x", expand=True)
            tk.Button(row, text="…", width=3, bg="white", fg="black",
                      command=lambda v=var: self._browse(v)).pack(side="left", padx=4)

        # Options
        opt = tk.Frame(self, bg=C_BG)
        opt.pack(fill="x", padx=10, pady=(4, 6))
        tk.Checkbutton(opt, text="Include subfolders", variable=self.var_recursive,
                       bg=C_BG, fg=C_FG, selectcolor=C_BG2,
                       activebackground=C_BG, activeforeground=C_FG).pack(side="left")
        tk.Checkbutton(opt, text="Compare by content (slower, exact)",
                       variable=self.var_by_content,
                       bg=C_BG, fg=C_FG, selectcolor=C_BG2,
                       activebackground=C_BG, activeforeground=C_FG).pack(side="left", padx=(12, 0))
        tk.Label(opt, text="Filter:", bg=C_BG, fg=C_FG).pack(side="left", padx=(20, 4))
        tk.Entry(opt, textvariable=self.var_filter, width=14, bg=C_BG2, fg=C_FG,
                 insertbackground=C_FG,
                 insertofftime=0, insertontime=9999999).pack(side="left")
        tk.Button(opt, text="▶  Compare", bg="lightgreen", fg="black", width=12,
                  command=self._start_compare).pack(side="right")
        tk.Button(opt, text="■  Stop", bg="white", fg="black", width=8,
                  command=lambda: self._stop.set()).pack(side="right", padx=4)

        # Show/hide filters for the result list
        show = tk.Frame(self, bg=C_BG2)
        show.pack(fill="x", padx=10)
        tk.Label(show, text="Show:", bg=C_BG2, fg=C_FG_DIM).pack(side="left", padx=(6, 4), pady=3)
        self.show_vars = {}
        for status, label in ((SYNC_ONLY_LEFT, "Only left →"),
                              (SYNC_ONLY_RIGHT, "← Only right"),
                              (SYNC_LEFT_NEWER, "Left newer →"),
                              (SYNC_RIGHT_NEWER, "← Right newer"),
                              (SYNC_DIFFERENT, "Different"),
                              (SYNC_EQUAL, "Equal")):
            v = tk.BooleanVar(value=status != SYNC_EQUAL)
            self.show_vars[status] = v
            tk.Checkbutton(show, text=label, variable=v, bg=C_BG2, fg=C_FG,
                           selectcolor=C_BG, activebackground=C_BG2,
                           activeforeground=C_FG,
                           command=self._render).pack(side="left", padx=3)

        # Result list
        mid = tk.Frame(self, bg=C_BG)
        mid.pack(fill="both", expand=True, padx=10, pady=6)
        cols = ("lsize", "ldate", "status", "rsize", "rdate")
        self.tree = ttk.Treeview(mid, columns=cols, selectmode="extended")
        self.tree.heading("#0",     text="✓  Relative path", anchor="w")
        self.tree.heading("lsize",  text="Left size",  anchor="e")
        self.tree.heading("ldate",  text="Left date",  anchor="w")
        self.tree.heading("status", text="Status",     anchor="center")
        self.tree.heading("rsize",  text="Right size", anchor="e")
        self.tree.heading("rdate",  text="Right date", anchor="w")
        self.tree.column("#0", width=420, stretch=True)
        self.tree.column("lsize", width=90, anchor="e")
        self.tree.column("ldate", width=130)
        self.tree.column("status", width=110, anchor="center")
        self.tree.column("rsize", width=90, anchor="e")
        self.tree.column("rdate", width=130)
        sb = ttk.Scrollbar(mid, orient="vertical", command=self.tree.yview)
        self.tree.configure(yscrollcommand=sb.set)
        self.tree.pack(side="left", fill="both", expand=True)
        sb.pack(side="right", fill="y")
        self.tree.tag_configure(SYNC_ONLY_LEFT,   foreground=TC_OK)
        self.tree.tag_configure(SYNC_ONLY_RIGHT,  foreground=TC_INFO)
        self.tree.tag_configure(SYNC_LEFT_NEWER,  foreground=TC_WARN)
        self.tree.tag_configure(SYNC_RIGHT_NEWER, foreground=TC_WARN2)
        self.tree.tag_configure(SYNC_DIFFERENT,   foreground=TC_BAD)
        self.tree.tag_configure(SYNC_EQUAL,       foreground=TC_MUTED)
        self.tree.bind("<space>",    self._toggle_checked)
        self.tree.bind("<Double-1>", self._on_double)

        # Actions
        bot = tk.Frame(self, bg=C_BG)
        bot.pack(fill="x", padx=10, pady=(0, 10))
        self._status = tk.Label(bot, text="Choose two folders and press Compare.",
                                bg=C_BG, fg=C_FG_DIM, anchor="w")
        self._status.pack(side="left", fill="x", expand=True)
        tk.Button(bot, text="Check all", bg="white", fg="black",
                  command=lambda: self._set_all(True)).pack(side="left", padx=2)
        tk.Button(bot, text="Uncheck all", bg="white", fg="black",
                  command=lambda: self._set_all(False)).pack(side="left", padx=2)
        tk.Button(bot, text="Close", bg="grey", fg="white", width=9,
                  command=self.destroy).pack(side="right", padx=4)
        tk.Button(bot, text="←  Copy right to left", bg="lightblue", fg="black",
                  command=lambda: self._synchronize("left")).pack(side="right", padx=4)
        tk.Button(bot, text="Copy left to right  →", bg="lightgreen", fg="black",
                  command=lambda: self._synchronize("right")).pack(side="right", padx=4)

    def _browse(self, var):
        d = filedialog.askdirectory(title="Choose folder", parent=self,
                                    initialdir=var.get() or os.path.expanduser("~"))
        if d:
            var.set(d)

    # ── Comparison ────────────────────────────────────────────────────────

    def _start_compare(self):
        if self._busy:
            return
        left, right = self.var_left.get(), self.var_right.get()
        if not os.path.isdir(left) or not os.path.isdir(right):
            messagebox.showerror("Synchronize",
                                 "Both sides must be existing folders.", parent=self)
            return
        self._busy = True
        self._stop.clear()
        self.rows = []
        self.tree.delete(*self.tree.get_children())
        self._status.configure(text="Comparing…", fg=C_ACCENT)
        threading.Thread(target=self._compare_worker,
                         args=(left, right), daemon=True).start()

    def _walk(self, root: str) -> dict:
        """Map relative path (lower-case key) → (real relative path, size, mtime)."""
        out = {}
        pattern = self.var_filter.get().strip() or "*"
        if self.var_recursive.get():
            walker = os.walk(root)
        else:
            try:
                names = [n for n in os.listdir(root)
                         if os.path.isfile(os.path.join(root, n))]
            except OSError:
                names = []
            walker = [(root, [], names)]
        for dirpath, _dirs, files in walker:
            if self._stop.is_set():
                break
            for name in files:
                if pattern != "*" and not fnmatch.fnmatch(name.lower(), pattern.lower()):
                    continue
                full = os.path.join(dirpath, name)
                rel  = os.path.relpath(full, root)
                try:
                    st = os.stat(full)
                except OSError:
                    continue
                out[rel.lower()] = (rel, st.st_size, st.st_mtime)
        return out

    def _compare_worker(self, left: str, right: str):
        try:
            lmap = self._walk(left)
            rmap = self._walk(right)
            by_content = self.var_by_content.get()
            rows = []
            for key in sorted(set(lmap) | set(rmap)):
                if self._stop.is_set():
                    break
                l = lmap.get(key)
                r = rmap.get(key)
                if l and not r:
                    status = SYNC_ONLY_LEFT
                elif r and not l:
                    status = SYNC_ONLY_RIGHT
                else:
                    same_size = l[1] == r[1]
                    dt = l[2] - r[2]
                    if by_content and same_size:
                        try:
                            lh = _file_hash(os.path.join(left, l[0]), "sha256",
                                            cancel=self._stop.is_set)
                            rh = _file_hash(os.path.join(right, r[0]), "sha256",
                                            cancel=self._stop.is_set)
                            status = SYNC_EQUAL if lh == rh and lh else SYNC_DIFFERENT
                        except Exception:
                            status = SYNC_DIFFERENT
                    elif same_size and abs(dt) <= 2:
                        # 2-second tolerance covers FAT/NTFS timestamp rounding
                        status = SYNC_EQUAL
                    elif dt > 2:
                        status = SYNC_LEFT_NEWER
                    elif dt < -2:
                        status = SYNC_RIGHT_NEWER
                    else:
                        status = SYNC_DIFFERENT
                rows.append({
                    "rel":    (l or r)[0],
                    "status": status,
                    "lsize":  l[1] if l else None,
                    "ldate":  l[2] if l else None,
                    "rsize":  r[1] if r else None,
                    "rdate":  r[2] if r else None,
                    "checked": status != SYNC_EQUAL,
                })
            self.rows = rows
            self.after(0, self._render)
        except Exception as exc:
            self.after(0, lambda e=exc: messagebox.showerror(
                "Synchronize", f"Comparison failed:\n{e}", parent=self))
        finally:
            self._busy = False

    def _render(self):
        self.tree.delete(*self.tree.get_children())
        counts = {}
        shown = 0
        for i, row in enumerate(self.rows):
            counts[row["status"]] = counts.get(row["status"], 0) + 1
            if not self.show_vars[row["status"]].get():
                continue
            shown += 1
            mark = "☑" if row["checked"] else "☐"
            arrow = {SYNC_ONLY_LEFT: "→", SYNC_LEFT_NEWER: "→",
                     SYNC_ONLY_RIGHT: "←", SYNC_RIGHT_NEWER: "←",
                     SYNC_DIFFERENT: "≠", SYNC_EQUAL: "="}[row["status"]]
            self.tree.insert(
                "", "end", iid=str(i), text=f"{mark}  {row['rel']}",
                values=(_human_size(row["lsize"]) if row["lsize"] is not None else "",
                        f"{datetime.fromtimestamp(row['ldate']):%Y-%m-%d %H:%M}"
                        if row["ldate"] else "",
                        f"{arrow} {row['status']}",
                        _human_size(row["rsize"]) if row["rsize"] is not None else "",
                        f"{datetime.fromtimestamp(row['rdate']):%Y-%m-%d %H:%M}"
                        if row["rdate"] else ""),
                tags=(row["status"],))
        summary = "   ·   ".join(f"{k}: {v}" for k, v in sorted(counts.items()))
        self._status.configure(
            text=f"{shown} of {len(self.rows)} shown   ·   {summary}" if self.rows
            else "No files found.", fg=C_FG_DIM)

    def _toggle_checked(self, event=None):
        for iid in self.tree.selection():
            row = self.rows[int(iid)]
            row["checked"] = not row["checked"]
        self._render()
        return "break"

    def _on_double(self, event=None):
        """Double-click a differing pair to open it in the compare window."""
        sel = self.tree.selection()
        if not sel:
            return
        row = self.rows[int(sel[0])]
        lp = os.path.join(self.var_left.get(), row["rel"])
        rp = os.path.join(self.var_right.get(), row["rel"])
        if os.path.isfile(lp) and os.path.isfile(rp):
            CompareFilesWindow(self.manager, lp, rp)
        else:
            self.rows[int(sel[0])]["checked"] = not row["checked"]
            self._render()

    def _set_all(self, value: bool):
        for row in self.rows:
            if self.show_vars[row["status"]].get():
                row["checked"] = value
        self._render()

    # ── Synchronizing ─────────────────────────────────────────────────────

    def _synchronize(self, direction: str):
        """direction 'right' = left→right, 'left' = right→left."""
        left, right = self.var_left.get(), self.var_right.get()
        jobs = []
        for row in self.rows:
            if not row["checked"]:
                continue
            st = row["status"]
            if direction == "right":
                # Anything that exists on the left and differs on the right
                if st in (SYNC_ONLY_LEFT, SYNC_LEFT_NEWER, SYNC_DIFFERENT,
                          SYNC_RIGHT_NEWER):
                    if row["lsize"] is None:
                        continue
                    jobs.append((os.path.join(left, row["rel"]),
                                 os.path.join(right, row["rel"])))
            else:
                if st in (SYNC_ONLY_RIGHT, SYNC_RIGHT_NEWER, SYNC_DIFFERENT,
                          SYNC_LEFT_NEWER):
                    if row["rsize"] is None:
                        continue
                    jobs.append((os.path.join(right, row["rel"]),
                                 os.path.join(left, row["rel"])))
        if not jobs:
            messagebox.showinfo("Synchronize",
                                "Nothing checked to copy in that direction.",
                                parent=self)
            return

        target = right if direction == "right" else left
        if not _ask_yes_no(
                "Synchronize",
                f"Copy {len(jobs)} file(s) to\n{target}\n\n"
                "Existing files will be overwritten. Continue?", parent=self):
            return

        dlg = _ProgressDialog(self, "Synchronizing", total=len(jobs))

        def worker():
            copied, errors = 0, []
            for i, (src, dst) in enumerate(jobs, 1):
                if dlg.cancelled:
                    break
                dlg.post("progress", i, len(jobs), os.path.basename(src))
                try:
                    os.makedirs(os.path.dirname(dst), exist_ok=True)
                    shutil.copy2(src, dst)
                    copied += 1
                except Exception as exc:
                    errors.append(f"{os.path.basename(src)}: {exc}")
            dlg.post("done")
            self.after(0, lambda: self._sync_done(copied, errors))

        threading.Thread(target=worker, daemon=True).start()

    def _sync_done(self, copied: int, errors: list):
        self.manager.refresh_panels()
        if errors:
            messagebox.showerror(
                "Synchronize",
                f"Copied {copied} file(s).\n\nFailed:\n" + "\n".join(errors[:15]),
                parent=self)
        else:
            _flash_ok(self, f"Copied {copied} file(s).", "Synchronized")
        self._start_compare()      # refresh the comparison


# ══════════════════════════════════════════════════════════════════════════
#  DEL 24 — Duplicate finder
# ══════════════════════════════════════════════════════════════════════════

class DuplicateFinderWindow(tk.Toplevel):
    """Find duplicate files by size + content hash (optionally by name)."""

    def __init__(self, manager: "EditorFrame", start_dir: str):
        super().__init__(manager)
        self.manager = manager
        self._stop   = threading.Event()
        self._busy   = False
        self.groups: list = []          # [[path, path, …], …]

        self.configure(bg=C_BG)
        self.geometry("1080x700")
        _setup_toplevel(self, "Find duplicate files", manager, modal=False)

        self.var_dir1 = tk.StringVar(value=start_dir)
        self.var_dir2 = tk.StringVar(value="")
        self.var_method = tk.StringVar(value="content")
        self.var_min_size = tk.StringVar(value="1")
        self.var_filter = tk.StringVar(value="*")
        self.var_ignore_ext = tk.BooleanVar(value=False)

        self._build_ui()
        self.bind("<Return>", lambda e: self._start())

    def _build_ui(self):
        head = tk.Frame(self, bg=C_BG3)
        head.pack(fill="x")
        tk.Label(head, text="⧉  Find duplicate files", bg=C_BG3, fg=C_ACCENT,
                 font=("Segoe UI", 12, "bold")).pack(side="left", padx=10, pady=7)

        form = tk.Frame(self, bg=C_BG)
        form.pack(fill="x", padx=10, pady=8)
        for label, var, hint in (
                ("Folder:", self.var_dir1, ""),
                ("Also compare with:", self.var_dir2, "(optional second folder)")):
            row = tk.Frame(form, bg=C_BG)
            row.pack(fill="x", pady=2)
            tk.Label(row, text=label, bg=C_BG, fg=C_FG, width=17,
                     anchor="w").pack(side="left")
            tk.Entry(row, textvariable=var, bg=C_BG2, fg=C_FG,
                     insertbackground=C_FG,
                     insertofftime=0, insertontime=9999999).pack(
                side="left", fill="x", expand=True)
            tk.Button(row, text="…", width=3, bg="white", fg="black",
                      command=lambda v=var: self._browse(v)).pack(side="left", padx=4)
            if hint:
                tk.Label(row, text=hint, bg=C_BG, fg=C_FG_DIM,
                         font=("Segoe UI", 8, "italic")).pack(side="left", padx=4)

        opt = tk.Frame(form, bg=C_BG)
        opt.pack(fill="x", pady=(8, 2))
        tk.Label(opt, text="Match by:", bg=C_BG, fg=C_FG).pack(side="left")
        for label, val in (("Content (hash)", "content"),
                           ("Name + size", "name_size"),
                           ("Name only", "name")):
            tk.Radiobutton(opt, text=label, value=val, variable=self.var_method,
                           bg=C_BG, fg=C_FG, selectcolor=C_BG2,
                           activebackground=C_BG, activeforeground=C_FG,
                           command=self._method_changed).pack(side="left", padx=4)
        tk.Checkbutton(opt, text="Ignore extension", variable=self.var_ignore_ext,
                       bg=C_BG, fg=C_FG, selectcolor=C_BG2,
                       activebackground=C_BG,
                       activeforeground=C_FG).pack(side="left", padx=(10, 0))

        # ── Fuzzy matching — finds what exact hashing cannot ──────────────
        fuzz = tk.Frame(form, bg=C_BG)
        fuzz.pack(fill="x", pady=(4, 2))
        tk.Label(fuzz, text="Or find similar:", bg=C_BG, fg=C_ACCENT).pack(side="left")
        for label, val in (("Images (same picture, any size)", "image"),
                           ("Audio (same track, any bitrate)", "audio")):
            tk.Radiobutton(fuzz, text=label, value=val, variable=self.var_method,
                           bg=C_BG, fg=C_FG, selectcolor=C_BG2,
                           activebackground=C_BG, activeforeground=C_FG,
                           command=self._method_changed).pack(side="left", padx=4)

        self.var_tolerance = tk.IntVar(value=88)
        self._tol_frame = tk.Frame(form, bg=C_BG)
        self._tol_frame.pack(fill="x", pady=(2, 2))
        tk.Label(self._tol_frame, text="Similarity:", bg=C_BG,
                 fg=C_FG).pack(side="left")
        self._tol_scale = tk.Scale(
            self._tol_frame, from_=70, to=100, orient="horizontal",
            variable=self.var_tolerance, bg=C_BG, fg=C_FG, troughcolor=C_BG2,
            highlightthickness=0, length=260, showvalue=False,
            command=lambda v: self._update_tol_label())
        self._tol_scale.pack(side="left", padx=6)
        self._tol_lbl = tk.Label(self._tol_frame, text="", bg=C_BG, fg=C_FG_DIM,
                                 font=("Segoe UI", 9), width=42, anchor="w")
        self._tol_lbl.pack(side="left")
        self._update_tol_label()
        self._method_changed()

        opt2 = tk.Frame(form, bg=C_BG)
        opt2.pack(fill="x", pady=2)
        tk.Label(opt2, text="Min size (KB):", bg=C_BG, fg=C_FG).pack(side="left")
        tk.Entry(opt2, textvariable=self.var_min_size, width=8, bg=C_BG2, fg=C_FG,
                 insertbackground=C_FG,
                 insertofftime=0, insertontime=9999999).pack(side="left", padx=4)
        tk.Label(opt2, text="Filter:", bg=C_BG, fg=C_FG).pack(side="left", padx=(14, 4))
        tk.Entry(opt2, textvariable=self.var_filter, width=14, bg=C_BG2, fg=C_FG,
                 insertbackground=C_FG,
                 insertofftime=0, insertontime=9999999).pack(side="left")
        tk.Button(opt2, text="▶  Search", bg="lightgreen", fg="black", width=12,
                  command=self._start).pack(side="right")
        tk.Button(opt2, text="■  Stop", bg="white", fg="black", width=8,
                  command=lambda: self._stop.set()).pack(side="right", padx=4)

        mid = tk.Frame(self, bg=C_BG)
        mid.pack(fill="both", expand=True, padx=10, pady=6)
        self.tree = ttk.Treeview(mid, columns=("size", "modified", "folder"),
                                 selectmode="extended")
        self.tree.heading("#0",       text="File",     anchor="w")
        self.tree.heading("size",     text="Size",     anchor="e")
        self.tree.heading("modified", text="Modified", anchor="w")
        self.tree.heading("folder",   text="Folder",   anchor="w")
        self.tree.column("#0", width=320, stretch=True)
        self.tree.column("size", width=90, anchor="e")
        self.tree.column("modified", width=130)
        self.tree.column("folder", width=420)
        sb = ttk.Scrollbar(mid, orient="vertical", command=self.tree.yview)
        self.tree.configure(yscrollcommand=sb.set)
        self.tree.pack(side="left", fill="both", expand=True)
        sb.pack(side="right", fill="y")
        self.tree.tag_configure("group",  foreground=TC_INFO,
                                font=("Segoe UI", 9, "bold"))
        self.tree.tag_configure("keep",   foreground=TC_OK)
        self.tree.bind("<Double-1>", self._on_double)

        bot = tk.Frame(self, bg=C_BG)
        bot.pack(fill="x", padx=10, pady=(0, 10))
        self._status = tk.Label(bot, text="Ready.", bg=C_BG, fg=C_FG_DIM, anchor="w")
        self._status.pack(side="left", fill="x", expand=True)
        tk.Button(bot, text="Select all but newest", bg="white", fg="black",
                  command=lambda: self._auto_select("newest")).pack(side="left", padx=2)
        tk.Button(bot, text="Select all but oldest", bg="white", fg="black",
                  command=lambda: self._auto_select("oldest")).pack(side="left", padx=2)
        tk.Button(bot, text="Close", bg="grey", fg="white", width=9,
                  command=self.destroy).pack(side="right", padx=4)
        tk.Button(bot, text="🗑  Delete selected", bg="#ff8888", fg="black",
                  command=self._delete_selected).pack(side="right", padx=4)
        tk.Button(bot, text="Compare selected two", bg="lightblue", fg="black",
                  command=self._compare_two).pack(side="right", padx=4)

    def _browse(self, var):
        d = filedialog.askdirectory(title="Choose folder", parent=self,
                                    initialdir=var.get() or os.path.expanduser("~"))
        if d:
            var.set(d)

    # ── Fuzzy options ─────────────────────────────────────────────────────

    def _is_fuzzy(self) -> bool:
        return self.var_method.get() in ("image", "audio")

    def _method_changed(self):
        """The similarity slider only means anything for the fuzzy methods."""
        state = "normal" if self._is_fuzzy() else "disabled"
        try:
            self._tol_scale.configure(state=state)
            self._tol_lbl.configure(fg=C_FG_DIM if self._is_fuzzy() else C_SEP)
        except Exception:
            pass
        self._update_tol_label()

    def _update_tol_label(self):
        pct = self.var_tolerance.get()
        if not self._is_fuzzy():
            self._tol_lbl.configure(
                text="(only used by the two “find similar” methods)")
            return
        if self.var_method.get() == "image":
            bits = round((100 - pct) / 100 * 64)
            hint = ("near-identical" if pct >= 95 else
                    "same picture, rescaled" if pct >= 85 else
                    "loose — expect some false matches")
            self._tol_lbl.configure(
                text=f"{pct}%  —  up to {bits} of 64 bits differ · {hint}")
        else:
            hint = ("near-identical" if pct >= 95 else
                    "same track, different encoding" if pct >= 85 else
                    "loose — expect some false matches")
            self._tol_lbl.configure(text=f"{pct}%  —  {hint}")

    # ── Scanning ──────────────────────────────────────────────────────────

    def _start(self):
        if self._busy:
            return
        roots = [d for d in (self.var_dir1.get(), self.var_dir2.get())
                 if d and os.path.isdir(d)]
        if not roots:
            messagebox.showerror("Duplicates", "Choose at least one existing folder.",
                                 parent=self)
            return
        self._busy = True
        self._stop.clear()
        self.groups = []
        self.tree.delete(*self.tree.get_children())
        self._status.configure(text="Scanning…", fg=C_ACCENT)
        threading.Thread(target=self._worker, args=(roots,), daemon=True).start()

    def _worker(self, roots: list):
        try:
            try:
                min_size = int(float(self.var_min_size.get()) * 1024)
            except Exception:
                min_size = 0
            pattern = self.var_filter.get().strip() or "*"
            method  = self.var_method.get()

            files = []
            seen_paths = set()
            for root in roots:
                for dirpath, _dirs, names in os.walk(root):
                    if self._stop.is_set():
                        break
                    for name in names:
                        if pattern != "*" and not fnmatch.fnmatch(name.lower(),
                                                                  pattern.lower()):
                            continue
                        full = os.path.join(dirpath, name)
                        key = os.path.normcase(os.path.abspath(full))
                        if key in seen_paths:
                            continue      # the two roots overlap
                        seen_paths.add(key)
                        try:
                            size = os.path.getsize(full)
                        except OSError:
                            continue
                        if size < min_size:
                            continue
                        files.append((full, size, name))

            self.after(0, lambda n=len(files): self._status.configure(
                text=f"Scanned {n} files — grouping…", fg=C_ACCENT))

            if method in ("image", "audio"):
                groups = self._fuzzy_groups(files, method)
                if groups is None:      # cancelled or unavailable
                    return
                groups.sort(key=lambda g: -sum(os.path.getsize(p)
                                               for p in g if os.path.exists(p)))
                self.groups = groups
                _ui_call(self, self._render)
                return

            buckets = {}
            if method == "name":
                for full, size, name in files:
                    key = os.path.splitext(name)[0].lower() \
                        if self.var_ignore_ext.get() else name.lower()
                    buckets.setdefault(key, []).append(full)
            elif method == "name_size":
                for full, size, name in files:
                    stem = os.path.splitext(name)[0].lower() \
                        if self.var_ignore_ext.get() else name.lower()
                    buckets.setdefault((stem, size), []).append(full)
            else:
                # Group by size first — only hash files that share a size,
                # which is what makes this fast on large trees.
                by_size = {}
                for full, size, name in files:
                    by_size.setdefault(size, []).append(full)
                candidates = [(s, g) for s, g in by_size.items() if len(g) > 1]
                total = sum(len(g) for _s, g in candidates)
                done = 0
                for size, group in candidates:
                    if self._stop.is_set():
                        break
                    for full in group:
                        if self._stop.is_set():
                            break
                        done += 1
                        if done % 25 == 0:
                            self.after(0, lambda d=done, t=total:
                                       self._status.configure(
                                           text=f"Hashing {d} / {t} …", fg=C_ACCENT))
                        try:
                            h = _file_hash(full, "sha256", cancel=self._stop.is_set)
                        except Exception:
                            continue
                        if h:
                            buckets.setdefault((size, h), []).append(full)

            groups = [sorted(g) for g in buckets.values() if len(g) > 1]
            groups.sort(key=lambda g: -sum(os.path.getsize(p)
                                           for p in g if os.path.exists(p)))
            self.groups = groups
            self.after(0, self._render)
        except Exception as exc:
            self.after(0, lambda e=exc: messagebox.showerror(
                "Duplicates", f"Search failed:\n{e}", parent=self))
        finally:
            self._busy = False

    def _fuzzy_groups(self, files: list, method: str):
        """Fingerprint the candidates and group whatever looks alike.

        Returns None when the search was cancelled or is not possible.
        """
        wanted = IMAGE_HASH_EXTS if method == "image" else AUDIO_HASH_EXTS
        candidates = [(p, s, n) for (p, s, n) in files
                      if os.path.splitext(n)[1].lower() in wanted]
        if not candidates:
            _ui_call(self, lambda: self._status.configure(
                text=f"No {'image' if method == 'image' else 'audio'} files "
                     f"found in that folder.", fg=TC_WARN))
            return None

        if method == "audio" and not ffmpeg_path():
            _ui_call(self, lambda: messagebox.showinfo(
                "Similar audio",
                "Matching audio needs ffmpeg.\n\n"
                "Put ffmpeg.exe in Helpfiles/1---Movie/ beside the program, "
                "or anywhere on the PATH.", parent=self))
            _ui_call(self, lambda: self._status.configure(
                text="ffmpeg not found — audio matching unavailable.", fg=TC_BAD))
            return None

        prints = []
        total = len(candidates)
        for i, (path, _size, _name) in enumerate(candidates, 1):
            if self._stop.is_set():
                return None
            if i % 5 == 0 or method == "audio":
                _ui_call(self, lambda i=i, t=total: self._status.configure(
                    text=f"Fingerprinting {i} / {t} …", fg=C_ACCENT))
            try:
                fp = image_phash(path) if method == "image" else audio_fingerprint(path)
            except RuntimeError as exc:      # missing library / tool
                _ui_call(self, lambda e=exc: messagebox.showerror(
                    "Find similar", str(e), parent=self))
                return None
            except Exception as exc:
                _log(f"Fingerprint failed for {path}: {exc}")
                continue
            # An image hash is an int (0 = unreadable); an audio fingerprint is
            # an array, which must not be truth-tested directly.
            usable = (fp != 0) if method == "image" else (
                fp is not None and len(fp) > 0)
            if usable:
                prints.append((path, fp))

        if len(prints) < 2:
            _ui_call(self, lambda: self._status.configure(
                text="Not enough readable files to compare.", fg=TC_WARN))
            return []

        pct = self.var_tolerance.get()
        _ui_call(self, lambda n=len(prints): self._status.configure(
            text=f"Comparing {n} fingerprints …", fg=C_ACCENT))

        if method == "image":
            max_bits = round((100 - pct) / 100 * 64)

            def similar(a, b):
                return hamming(a[1], b[1]) <= max_bits
        else:
            threshold = pct / 100.0

            def similar(a, b):
                return audio_similarity(a[1], b[1]) >= threshold

        if self._stop.is_set():
            return None
        groups = group_by_similarity(prints, similar)
        return [sorted(p for p, _fp in g) for g in groups]

    def _render(self):
        self.tree.delete(*self.tree.get_children())
        fuzzy = self._is_fuzzy()
        word = "similar" if fuzzy else "copies"
        wasted = 0
        for gi, group in enumerate(self.groups):
            sizes = []
            for p in group:
                try:
                    sizes.append(os.path.getsize(p))
                except OSError:
                    sizes.append(0)
            # Keeping the biggest copy is what frees the least; that is the
            # honest figure. For exact duplicates it is the same either way.
            group_waste = sum(sizes) - max(sizes) if sizes else 0
            wasted += group_waste
            parent = self.tree.insert(
                "", "end", iid=f"g{gi}",
                text=f"⧉  {len(group)} {word} — {os.path.basename(group[0])}",
                values=(_human_size(max(sizes) if sizes else 0), "",
                        f"keeping one frees {_human_size(group_waste)}"),
                open=True, tags=("group",))
            for pi, path in enumerate(group):
                try:
                    st = os.stat(path)
                    mod = f"{datetime.fromtimestamp(st.st_mtime):%Y-%m-%d %H:%M}"
                    sz = _human_size(st.st_size)
                except OSError:
                    mod, sz = "", ""
                self.tree.insert(parent, "end", iid=f"g{gi}f{pi}",
                                 text=os.path.basename(path),
                                 values=(sz, mod, os.path.dirname(path)))
        self._status.configure(
            text=(f"{len(self.groups)} duplicate group(s)   ·   "
                  f"{_human_size(wasted)} could be freed"
                  if self.groups else "No duplicates found."),
            fg="#ffd479" if self.groups else "#7ee787")

    def _paths_for(self, iid: str) -> list:
        """Full path(s) behind a tree row."""
        if iid.startswith("g") and "f" in iid:
            gi, _, pi = iid[1:].partition("f")
            try:
                return [self.groups[int(gi)][int(pi)]]
            except (ValueError, IndexError):
                return []
        if iid.startswith("g"):
            try:
                return list(self.groups[int(iid[1:])])
            except (ValueError, IndexError):
                return []
        return []

    def _on_double(self, event=None):
        sel = self.tree.selection()
        if not sel:
            return
        paths = self._paths_for(sel[0])
        if len(paths) == 1 and os.path.isfile(paths[0]):
            # Jump the active panel to the file's folder
            panel = self.manager.get_active_panel()
            panel.change_directory(os.path.dirname(paths[0]),
                                   select_name=os.path.basename(paths[0]))

    def _auto_select(self, keep: str):
        """Select every copy except the newest / oldest in each group."""
        to_select = []
        for gi, group in enumerate(self.groups):
            stamped = []
            for pi, path in enumerate(group):
                try:
                    stamped.append((os.path.getmtime(path), pi))
                except OSError:
                    stamped.append((0, pi))
            stamped.sort()
            keep_pi = stamped[-1][1] if keep == "newest" else stamped[0][1]
            for _mt, pi in stamped:
                if pi != keep_pi:
                    to_select.append(f"g{gi}f{pi}")
        self.tree.selection_set(to_select)
        self._status.configure(
            text=f"{len(to_select)} file(s) selected — "
                 f"keeping the {keep} copy in each group", fg="#ffd479")

    def _compare_two(self):
        files = []
        for iid in self.tree.selection():
            files.extend(self._paths_for(iid))
        files = [f for f in files if os.path.isfile(f)]
        if len(files) != 2:
            messagebox.showinfo("Compare",
                                "Select exactly two files to compare.", parent=self)
            return
        CompareFilesWindow(self.manager, files[0], files[1])

    def _delete_selected(self):
        paths = []
        for iid in self.tree.selection():
            if iid.startswith("g") and "f" in iid:
                paths.extend(self._paths_for(iid))
        paths = [p for p in dict.fromkeys(paths) if os.path.isfile(p)]
        if not paths:
            messagebox.showinfo("Delete",
                                "Select the individual copies you want to delete\n"
                                "(not the group heading).", parent=self)
            return

        # Refuse to wipe out every copy in a group
        for gi, group in enumerate(self.groups):
            chosen = [p for p in paths if p in group]
            if chosen and len(chosen) == len(group):
                messagebox.showerror(
                    "Delete",
                    f"You selected every copy in the group\n"
                    f"'{os.path.basename(group[0])}'.\n\n"
                    "Leave at least one copy in each group.", parent=self)
                return

        if not _ask_yes_no(
                "Delete duplicates",
                f"Move {len(paths)} file(s) to the Recycle Bin?\n\n"
                + "\n".join(os.path.basename(p) for p in paths[:12])
                + ("\n…" if len(paths) > 12 else ""), parent=self):
            return

        failed = EditorFrame._send_to_recycle_bin(paths)
        deleted = len(paths) - len(failed)
        # Drop the deleted files out of the groups, then re-render
        gone = {p for p in paths if p not in failed}
        self.groups = [[p for p in g if p not in gone] for g in self.groups]
        self.groups = [g for g in self.groups if len(g) > 1]
        self._render()
        self.manager.refresh_panels()
        if failed:
            messagebox.showerror("Delete",
                                 f"Deleted {deleted}.\n\nCould not delete:\n"
                                 + "\n".join(failed[:12]), parent=self)
        else:
            _flash_ok(self, f"Deleted {deleted} duplicate(s).", "Deleted")


# ══════════════════════════════════════════════════════════════════════════
#  DEL 25 — Quick View panel  (Ctrl+Q)
# ══════════════════════════════════════════════════════════════════════════

_QV_TEXT_EXTS = {
    ".txt", ".log", ".md", ".nfo", ".ini", ".cfg", ".conf", ".json", ".xml",
    ".csv", ".tsv", ".yaml", ".yml", ".py", ".pyw", ".js", ".ts", ".css",
    ".html", ".htm", ".bat", ".cmd", ".ps1", ".sh", ".c", ".h", ".cpp", ".hpp",
    ".cs", ".java", ".sql", ".reg", ".srt", ".sub", ".vtt", ".diff", ".patch",
    ".gitignore", ".toml", ".env", ".properties", ".m3u", ".sfv", ".md5",
}


class QuickViewPanel(ttk.Frame):
    """Live preview pane that follows the cursor in the active file panel.

    Modes: auto (pick by file type), text, hex, image.  Everything is loaded
    on a background thread and capped in size, so moving the cursor quickly
    through a folder of huge files never freezes the UI.
    """

    MAX_TEXT_BYTES = 512 * 1024      # read at most 512 KB for the text view
    MAX_HEX_BYTES  = 64 * 1024       # 64 KB of hex is already 4000 rows

    def __init__(self, panes: ttk.Panedwindow, manager: "EditorFrame"):
        super().__init__(panes)
        self.panes   = panes
        self.manager = manager
        self.visible = False
        self._current: str | None = None
        self._token   = 0             # cancels stale background loads
        self._photo   = None          # keep a reference or Tk garbage-collects it

        self.var_mode = tk.StringVar(value=manager.settings.get("quickview_mode", "auto"))

        self._build_ui()

    def _build_ui(self):
        bar = tk.Frame(self, bg=C_BG3)
        bar.pack(fill="x")
        tk.Label(bar, text="👁", bg=C_BG3, fg=C_ACCENT,
                 font=("Segoe UI", 10)).pack(side="left", padx=(6, 2))
        self._title = tk.Label(bar, text="Quick View", bg=C_BG3, fg=C_FG,
                               font=("Segoe UI", 9, "bold"), anchor="w")
        self._title.pack(side="left", fill="x", expand=True)
        tk.Button(bar, text="✕", bg=C_BG3, fg=C_FG, relief="flat", padx=4,
                  command=self.hide).pack(side="right")

        mode_bar = tk.Frame(self, bg=C_BG2)
        mode_bar.pack(fill="x")
        for label, val in (("Auto", "auto"), ("Text", "text"),
                           ("Hex", "hex"), ("Image", "image")):
            tk.Radiobutton(mode_bar, text=label, value=val, variable=self.var_mode,
                           bg=C_BG2, fg=C_FG, selectcolor=C_BG,
                           activebackground=C_BG2, activeforeground=C_FG,
                           font=("Segoe UI", 8),
                           command=self._mode_changed).pack(side="left", padx=1)

        # Text / hex view
        self._text_frame = tk.Frame(self, bg=C_BG2)
        self.text = tk.Text(self._text_frame, wrap="none", bg=C_BG2, fg=C_FG,
                            font=("Consolas", 9), padx=6, pady=4,
                            insertofftime=0, insertontime=9999999)
        vsb = ttk.Scrollbar(self._text_frame, orient="vertical", command=self.text.yview)
        hsb = ttk.Scrollbar(self._text_frame, orient="horizontal", command=self.text.xview)
        self.text.configure(yscrollcommand=vsb.set, xscrollcommand=hsb.set)
        vsb.pack(side="right", fill="y")
        hsb.pack(side="bottom", fill="x")
        self.text.pack(side="left", fill="both", expand=True)
        self.text.configure(state="disabled")

        # Image view
        self._img_frame = tk.Frame(self, bg=C_BG)
        self.img_label = tk.Label(self._img_frame, bg=C_BG, fg=C_FG_DIM,
                                  text="", anchor="center")
        self.img_label.pack(fill="both", expand=True)

        self._text_frame.pack(fill="both", expand=True)

        self._info = tk.Label(self, text="", bg=C_BG3, fg=C_FG_DIM, anchor="w",
                              font=("Segoe UI", 8))
        self._info.pack(fill="x", side="bottom")

        # Re-fit the image whenever the pane is resized
        self._img_frame.bind("<Configure>", self._on_resize)

    # ── Show / hide ───────────────────────────────────────────────────────

    def show(self):
        if self.visible:
            return
        try:
            self.panes.add(self, weight=0)
            width = max(200, int(self.manager.settings.get("quickview_width", 380)))
            # The sash cannot be positioned until the pane has been laid out,
            # so nudge it on the next idle pass and once more shortly after —
            # the first attempt often runs before the geometry has settled.
            self.after_idle(lambda: self._set_width(width))
            self.after(120, lambda: self._set_width(width))
        except Exception as exc:
            _log(f"Quick View could not be shown: {exc}")
            return
        self.visible = True
        self.manager.settings["quickview_open"] = True
        self.update_current()

    def hide(self):
        if not self.visible:
            return
        try:
            self.manager.settings["quickview_width"] = max(200, self.winfo_width())
            self.panes.forget(self)
        except Exception:
            pass
        self.visible = False
        self.manager.settings["quickview_open"] = False
        # Hand the reclaimed space back to the two panels evenly
        self.after_idle(self.manager._rebalance_panels)

    def toggle(self):
        self.hide() if self.visible else self.show()

    def stop(self):
        """Called on shutdown — remember the width for next time."""
        if self.visible:
            try:
                self.manager.settings["quickview_width"] = max(200, self.winfo_width())
            except Exception:
                pass

    def _set_width(self, width: int):
        """Give the Quick View pane a sensible starting width.

        Quick View is the last pane, so the sash to move is the last one.
        It is capped at half the window, otherwise restoring a width saved on
        a much wider monitor would squeeze the file panels down to nothing.

        The two file panels are then re-balanced: without this, Tk takes the
        space for Quick View unevenly and the left panel ends up roughly half
        the width of the right one.
        """
        try:
            self.panes.update_idletasks()
            total = self.panes.winfo_width()
            if total <= 300:
                return
            width = min(width, total // 2)
            panes = self.panes.panes()
            last_sash = len(panes) - 2
            if last_sash < 0:
                return
            self.panes.sashpos(last_sash, total - width)
            # Split whatever is left equally between the two file panels
            if last_sash >= 1:
                self.panes.sashpos(0, (total - width) // 2)
        except Exception as exc:
            _log(f"Quick View width could not be set: {exc}")

    def _rebalance_panels(self):
        """Give the two file panels equal width again after Quick View closes."""
        try:
            self.panes.update_idletasks()
            total = self.panes.winfo_width()
            if total > 300 and len(self.panes.panes()) >= 2:
                self.panes.sashpos(0, total // 2)
        except Exception:
            pass

    def _mode_changed(self):
        self.manager.settings["quickview_mode"] = self.var_mode.get()
        self._current = None          # force a reload in the new mode
        self.update_current()

    def _on_resize(self, event=None):
        if self.visible and self._current and self._showing_image:
            self._render_image(self._current)

    # ── Loading ───────────────────────────────────────────────────────────

    _showing_image = False

    def update_current(self, path: str = None):
        """Refresh the preview for the panel cursor (or an explicit path)."""
        if not self.visible:
            return
        if path is None:
            try:
                panel = self.manager.get_active_panel()
                if getattr(panel, "is_remote", False):
                    self._set_message("Quick View is not available for FTP panels.")
                    return
                sel = panel.tree.selection()
                if not sel:
                    self._set_message("No file selected.")
                    return
                name = panel._fullname(sel[0])
                if name == "..":
                    self._set_message("Parent folder.")
                    return
                path = os.path.join(panel.current_path, name)
            except Exception:
                return

        if path == self._current:
            return
        self._current = path
        self._token += 1
        token = self._token

        self._title.configure(text=os.path.basename(path))

        if os.path.isdir(path):
            self._preview_folder(path, token)
            return
        if not os.path.isfile(path):
            self._set_message("Not available.")
            return

        mode = self.var_mode.get()
        ext  = os.path.splitext(path)[1].lower()
        if mode == "auto":
            if ext in _VIEWER_IMAGE_EXTS:
                mode = "image"
            elif ext in _VIEWER_PDF_EXTS:
                mode = "pdf"
            elif ext in _QV_TEXT_EXTS or not _looks_binary(path):
                mode = "text"
            else:
                mode = "hex"

        if mode == "image":
            self._render_image(path)
        elif mode == "pdf":
            self._preview_pdf(path, token)
        elif mode == "hex":
            threading.Thread(target=self._load_hex, args=(path, token),
                             daemon=True).start()
        else:
            threading.Thread(target=self._load_text, args=(path, token),
                             daemon=True).start()

    def _show_text_view(self):
        if self._showing_image:
            self._img_frame.pack_forget()
            self._text_frame.pack(fill="both", expand=True)
            self._showing_image = False

    def _show_image_view(self):
        if not self._showing_image:
            self._text_frame.pack_forget()
            self._img_frame.pack(fill="both", expand=True)
            self._showing_image = True

    def _set_message(self, msg: str, info: str = ""):
        self._show_text_view()
        self.text.configure(state="normal")
        self.text.delete("1.0", "end")
        self.text.insert("1.0", msg)
        self.text.configure(state="disabled")
        self._info.configure(text=info)

    def _set_text(self, content: str, info: str):
        self._show_text_view()
        self.text.configure(state="normal")
        self.text.delete("1.0", "end")
        self.text.insert("1.0", content)
        self.text.configure(state="disabled")
        self._info.configure(text=info)

    def _load_text(self, path: str, token: int):
        try:
            size = os.path.getsize(path)
            with open(path, "rb") as fh:
                raw = fh.read(self.MAX_TEXT_BYTES)
            for enc in ("utf-8-sig", "utf-8", "cp1252", "latin-1"):
                try:
                    content = raw.decode(enc)
                    break
                except UnicodeDecodeError:
                    continue
            else:
                enc, content = "latin-1", raw.decode("latin-1", "replace")
            truncated = size > self.MAX_TEXT_BYTES
            if truncated:
                content += (f"\n\n─── Preview truncated at "
                            f"{_human_size(self.MAX_TEXT_BYTES)} "
                            f"of {_human_size(size)} ───")
            info = (f"Text · {enc} · {_human_size(size)} · "
                    f"{content.count(chr(10)) + 1} lines"
                    + ("  (truncated)" if truncated else ""))
        except Exception as exc:
            content, info = f"Could not read file:\n{exc}", "error"
        if token == self._token:
            _ui_call(self, lambda: self._set_text(content, info))

    def _load_hex(self, path: str, token: int):
        try:
            size = os.path.getsize(path)
            with open(path, "rb") as fh:
                data = fh.read(self.MAX_HEX_BYTES)
            rows = []
            for off in range(0, len(data), 16):
                chunk = data[off:off + 16]
                hexs = " ".join(f"{c:02X}" for c in chunk).ljust(47)
                asc  = "".join(chr(c) if 32 <= c < 127 else "." for c in chunk)
                rows.append(f"{off:08X}  {hexs}  {asc}")
            content = "\n".join(rows)
            if size > self.MAX_HEX_BYTES:
                content += (f"\n\n─── Preview truncated at "
                            f"{_human_size(self.MAX_HEX_BYTES)} "
                            f"of {_human_size(size)} ───")
            info = f"Hex · {_human_size(size)}"
        except Exception as exc:
            content, info = f"Could not read file:\n{exc}", "error"
        if token == self._token:
            _ui_call(self, lambda: self._set_text(content, info))

    def _preview_folder(self, path: str, token: int):
        def work():
            try:
                names = os.listdir(path)
                dirs  = sorted(n for n in names if os.path.isdir(os.path.join(path, n)))
                files = sorted(n for n in names if os.path.isfile(os.path.join(path, n)))
                total = 0
                for n in files:
                    try:
                        total += os.path.getsize(os.path.join(path, n))
                    except OSError:
                        pass
                lines = [f"📁  {os.path.basename(path) or path}", ""]
                lines += [f"  📁  {n}" for n in dirs[:200]]
                lines += [f"  📄  {n}" for n in files[:400]]
                if len(dirs) > 200 or len(files) > 400:
                    lines.append("  …")
                content = "\n".join(lines)
                info = (f"Folder · {len(dirs)} folders · {len(files)} files · "
                        f"{_human_size(total)} (this level)")
            except Exception as exc:
                content, info = f"Could not read folder:\n{exc}", "error"
            if token == self._token:
                _ui_call(self, lambda: self._set_text(content, info))
        threading.Thread(target=work, daemon=True).start()

    def _preview_pdf(self, path: str, token: int):
        def work():
            try:
                import fitz
                doc = fitz.open(path)
                page = doc.load_page(0)
                zoom = 1.4
                pix = page.get_pixmap(matrix=fitz.Matrix(zoom, zoom))
                png = pix.tobytes("png")
                n_pages = doc.page_count
                doc.close()
                if token == self._token:
                    _ui_call(self, lambda: self._show_png_bytes(
                        png, f"PDF · page 1 of {n_pages} · "
                             f"{_human_size(os.path.getsize(path))}"))
            except Exception as exc:
                if token == self._token:
                    _ui_call(self, lambda e=exc: self._set_message(
                        f"PDF preview needs PyMuPDF:\n  pip install pymupdf\n\n{e}",
                        "PDF"))
        threading.Thread(target=work, daemon=True).start()

    def _show_png_bytes(self, png: bytes, info: str):
        try:
            from PIL import Image, ImageTk
            import io
            img = Image.open(io.BytesIO(png))
            self._fit_and_show(img, info)
        except Exception as exc:
            self._set_message(f"Could not render preview:\n{exc}", "error")

    def _render_image(self, path: str):
        try:
            from PIL import Image, ImageTk
        except ImportError:
            self._set_message("Image preview needs Pillow:\n  pip install pillow",
                              "Image")
            return
        try:
            img = Image.open(path)
            info = (f"Image · {img.width}×{img.height} · {img.mode} · "
                    f"{_human_size(os.path.getsize(path))}")
            self._fit_and_show(img, info)
        except Exception as exc:
            self._set_message(f"Could not open image:\n{exc}", "error")

    def _fit_and_show(self, img, info: str):
        """Scale an image to fit the pane and display it."""
        try:
            from PIL import Image, ImageTk
            self._show_image_view()
            self.update_idletasks()
            avail_w = max(60, self._img_frame.winfo_width()  - 8)
            avail_h = max(60, self._img_frame.winfo_height() - 8)
            scale = min(avail_w / img.width, avail_h / img.height, 1.0)
            if scale < 1.0:
                img = img.resize((max(1, int(img.width * scale)),
                                  max(1, int(img.height * scale))),
                                 Image.LANCZOS)
            self._photo = ImageTk.PhotoImage(img)
            self.img_label.configure(image=self._photo, text="")
            self._info.configure(text=info)
        except Exception as exc:
            self._set_message(f"Could not display image:\n{exc}", "error")


# ══════════════════════════════════════════════════════════════════════════
#  DEL 26 — Branch view  (Ctrl+B / Ctrl+Shift+B)
# ══════════════════════════════════════════════════════════════════════════
#
# Branch view flattens a whole folder tree into one list.  The panel keeps
# working normally — names simply become relative paths, and the FilePanel
# refresh() code reads `branch_mode` to decide what to list.

BRANCH_MAX_ITEMS = 60000       # safety cap, so a scan of C:\ cannot hang the UI


def branch_scan(root: str, include_dirs: bool = False,
                show_hidden: bool = False, show_system: bool = False,
                cancel=None) -> list:
    """Walk a tree and return relative paths (files, optionally folders too)."""
    out = []
    for dirpath, dirnames, filenames in os.walk(root):
        if cancel and cancel():
            break
        if not show_hidden or not show_system:
            keep = []
            for d in dirnames:
                try:
                    bits = ctypes.windll.kernel32.GetFileAttributesW(
                        os.path.join(dirpath, d))
                except Exception:
                    bits = 0
                if not show_hidden and ((bits & 2) or d.startswith(".")):
                    continue
                if not show_system and (bits & 4):
                    continue
                keep.append(d)
            dirnames[:] = keep

        if include_dirs:
            for d in dirnames:
                out.append(os.path.relpath(os.path.join(dirpath, d), root))
        for f in filenames:
            out.append(os.path.relpath(os.path.join(dirpath, f), root))
        if len(out) >= BRANCH_MAX_ITEMS:
            _log(f"branch_scan: hit the {BRANCH_MAX_ITEMS} item cap under {root}")
            break
    return out[:BRANCH_MAX_ITEMS]


# ══════════════════════════════════════════════════════════════════════════
#  DEL 27 — Checksums  (CRC32 / MD5 / SHA1 / SHA256)
# ══════════════════════════════════════════════════════════════════════════

CHECKSUM_ALGOS = ["crc32", "md5", "sha1", "sha256", "sha512"]

# Which file extension each algorithm writes by convention
CHECKSUM_EXT = {"crc32": ".sfv", "md5": ".md5", "sha1": ".sha1",
                "sha256": ".sha256", "sha512": ".sha512"}


class ChecksumWindow(tk.Toplevel):
    """Create and verify checksum files (.sfv / .md5 / .sha256 …)."""

    def __init__(self, manager: "EditorFrame", paths: list, verify_file: str = ""):
        super().__init__(manager)
        self.manager = manager
        self.paths   = [p for p in paths if os.path.isfile(p)]
        self._stop   = threading.Event()
        self._busy   = False
        self._results: list = []      # [(path, checksum, status)]

        self.configure(bg=C_BG)
        self.geometry("980x620")
        _setup_toplevel(self, "Checksums", manager, modal=False)

        self.var_algo = tk.StringVar(value="sha256")
        self.var_recursive = tk.BooleanVar(value=False)
        self._build_ui()

        if verify_file:
            self.after(60, lambda: self._verify_file(verify_file))
        self.bind("<Return>", lambda e: self._calculate())

    def _build_ui(self):
        head = tk.Frame(self, bg=C_BG3)
        head.pack(fill="x")
        tk.Label(head, text="🔐  Checksums", bg=C_BG3, fg=C_ACCENT,
                 font=("Segoe UI", 12, "bold")).pack(side="left", padx=10, pady=7)
        tk.Label(head, text="Create or verify CRC32 / MD5 / SHA files",
                 bg=C_BG3, fg=C_FG_DIM,
                 font=("Segoe UI", 9)).pack(side="left")

        opt = tk.Frame(self, bg=C_BG)
        opt.pack(fill="x", padx=10, pady=8)
        tk.Label(opt, text="Algorithm:", bg=C_BG, fg=C_FG).pack(side="left")
        algo_cb = ttk.Combobox(opt, textvariable=self.var_algo, width=10,
                               state="readonly", values=CHECKSUM_ALGOS)
        algo_cb.pack(side="left", padx=6)
        tk.Checkbutton(opt, text="Include subfolders", variable=self.var_recursive,
                       bg=C_BG, fg=C_FG, selectcolor=C_BG2,
                       activebackground=C_BG,
                       activeforeground=C_FG).pack(side="left", padx=(10, 0))
        tk.Button(opt, text="▶  Calculate", bg="lightgreen", fg="black", width=13,
                  command=self._calculate).pack(side="right")
        tk.Button(opt, text="■  Stop", bg="white", fg="black", width=8,
                  command=lambda: self._stop.set()).pack(side="right", padx=4)
        tk.Button(opt, text="Verify a checksum file…", bg="lightblue", fg="black",
                  command=self._pick_verify_file).pack(side="right", padx=4)

        mid = tk.Frame(self, bg=C_BG)
        mid.pack(fill="both", expand=True, padx=10, pady=4)
        self.tree = ttk.Treeview(mid, columns=("sum", "status"), selectmode="extended")
        self.tree.heading("#0",     text="File",     anchor="w")
        self.tree.heading("sum",    text="Checksum", anchor="w")
        self.tree.heading("status", text="Status",   anchor="w")
        self.tree.column("#0", width=330, stretch=True)
        self.tree.column("sum", width=460)
        self.tree.column("status", width=110)
        sb = ttk.Scrollbar(mid, orient="vertical", command=self.tree.yview)
        self.tree.configure(yscrollcommand=sb.set)
        self.tree.pack(side="left", fill="both", expand=True)
        sb.pack(side="right", fill="y")
        self.tree.tag_configure("ok",      foreground=TC_OK)
        self.tree.tag_configure("bad",     foreground=TC_BAD)
        self.tree.tag_configure("missing", foreground=TC_WARN)

        bot = tk.Frame(self, bg=C_BG)
        bot.pack(fill="x", padx=10, pady=(0, 10))
        self._status = tk.Label(bot, text=f"{len(self.paths)} file(s) queued.",
                                bg=C_BG, fg=C_FG_DIM, anchor="w")
        self._status.pack(side="left", fill="x", expand=True)
        tk.Button(bot, text="Close", bg="grey", fg="white", width=9,
                  command=self.destroy).pack(side="right", padx=4)
        tk.Button(bot, text="💾  Save checksum file…", bg="lightgreen", fg="black",
                  command=self._save_file).pack(side="right", padx=4)
        tk.Button(bot, text="📋  Copy to clipboard", bg="white", fg="black",
                  command=self._copy).pack(side="right", padx=4)

    # ── Calculating ───────────────────────────────────────────────────────

    def _expand_paths(self) -> list:
        out = []
        for p in self.paths:
            if os.path.isfile(p):
                out.append(p)
        if self.var_recursive.get():
            for p in self.paths:
                if os.path.isdir(p):
                    for dirpath, _d, files in os.walk(p):
                        out.extend(os.path.join(dirpath, f) for f in files)
        return out

    def _calculate(self):
        if self._busy:
            return
        files = self._expand_paths()
        if not files:
            messagebox.showinfo("Checksums", "No files selected.", parent=self)
            return
        self._busy = True
        self._stop.clear()
        self._results = []
        self.tree.delete(*self.tree.get_children())
        algo = self.var_algo.get()

        def worker():
            for i, path in enumerate(files, 1):
                if self._stop.is_set():
                    break
                try:
                    s = _file_hash(path, algo, cancel=self._stop.is_set)
                except Exception as exc:
                    s = f"error: {exc}"
                self._results.append((path, s, ""))
                self.after(0, lambda p=path, v=s, i=i: self._add_row(p, v, i, len(files)))
            self._busy = False
            self.after(0, lambda: self._status.configure(
                text=f"{len(self._results)} checksum(s) calculated with "
                     f"{algo.upper()}.", fg="#7ee787"))

        threading.Thread(target=worker, daemon=True).start()

    def _add_row(self, path: str, value: str, i: int, total: int):
        self.tree.insert("", "end", text=os.path.basename(path),
                         values=(value, ""))
        self._status.configure(text=f"Hashing {i} / {total} …", fg=C_ACCENT)

    def _copy(self):
        if not self._results:
            return
        text = "\n".join(f"{s}  {os.path.basename(p)}" for p, s, _ in self._results)
        self.clipboard_clear()
        self.clipboard_append(text)
        _flash_ok(self, f"{len(self._results)} checksum(s) copied.", "Copied")

    def _save_file(self):
        if not self._results:
            messagebox.showinfo("Checksums", "Calculate the checksums first.",
                                parent=self)
            return
        algo = self.var_algo.get()
        ext  = CHECKSUM_EXT.get(algo, ".txt")
        base_dir = os.path.dirname(self._results[0][0])
        default  = os.path.basename(base_dir.rstrip("\\/")) or "checksums"
        path = filedialog.asksaveasfilename(
            parent=self, title="Save checksum file",
            initialdir=base_dir, initialfile=default + ext,
            defaultextension=ext,
            filetypes=[(f"{algo.upper()} file", f"*{ext}"), ("All files", "*.*")])
        if not path:
            return
        try:
            with open(path, "w", encoding="utf-8") as fh:
                if algo == "crc32":
                    # SFV format:  filename checksum
                    fh.write(f"; Generated by File Manager  {datetime.now():%Y-%m-%d %H:%M}\n")
                    for p, s, _ in self._results:
                        fh.write(f"{os.path.relpath(p, os.path.dirname(path))} {s}\n")
                else:
                    # md5sum/shaXsum format:  checksum *filename
                    for p, s, _ in self._results:
                        fh.write(f"{s} *{os.path.relpath(p, os.path.dirname(path))}\n")
            self.manager.refresh_panels()
            _flash_ok(self, f"Saved to\n{os.path.basename(path)}", "Saved")
        except Exception as exc:
            messagebox.showerror("Checksums", f"Could not save:\n{exc}", parent=self)

    # ── Verifying ─────────────────────────────────────────────────────────

    def _pick_verify_file(self):
        path = filedialog.askopenfilename(
            parent=self, title="Choose a checksum file",
            initialdir=self.manager.get_active_panel().current_path,
            filetypes=[("Checksum files", "*.sfv *.md5 *.sha1 *.sha256 *.sha512"),
                       ("All files", "*.*")])
        if path:
            self._verify_file(path)

    @staticmethod
    def parse_checksum_file(path: str):
        """Parse .sfv / .md5 / .shaN files → (algo, [(filename, checksum)])."""
        ext = os.path.splitext(path)[1].lower()
        algo = {".sfv": "crc32", ".md5": "md5", ".sha1": "sha1",
                ".sha256": "sha256", ".sha512": "sha512"}.get(ext, "")
        entries = []
        with open(path, "r", encoding="utf-8", errors="replace") as fh:
            for line in fh:
                line = line.strip()
                if not line or line.startswith(";") or line.startswith("#"):
                    continue
                if algo == "crc32" or ext == ".sfv":
                    # "name with spaces.ext CRC32"
                    name, _, checksum = line.rpartition(" ")
                    if name and checksum:
                        entries.append((name.strip(), checksum.strip().upper()))
                else:
                    # "checksum *name" or "checksum  name"
                    checksum, _, name = line.partition(" ")
                    name = name.strip().lstrip("*").strip()
                    if name and checksum:
                        entries.append((name, checksum.strip().lower()))
        if not algo and entries:
            # Guess from the checksum length when the extension is unknown
            algo = {8: "crc32", 32: "md5", 40: "sha1",
                    64: "sha256", 128: "sha512"}.get(len(entries[0][1]), "md5")
        return algo, entries

    def _verify_file(self, path: str):
        try:
            algo, entries = self.parse_checksum_file(path)
        except Exception as exc:
            messagebox.showerror("Verify", f"Could not read:\n{exc}", parent=self)
            return
        if not entries:
            messagebox.showinfo("Verify", "No checksum entries found in that file.",
                                parent=self)
            return

        self.var_algo.set(algo)
        base = os.path.dirname(path)
        self.tree.delete(*self.tree.get_children())
        self._results = []
        self._stop.clear()
        self._busy = True

        def worker():
            ok = bad = missing = 0
            for i, (name, expected) in enumerate(entries, 1):
                if self._stop.is_set():
                    break
                target = os.path.join(base, name)
                if not os.path.isfile(target):
                    missing += 1
                    self.after(0, lambda n=name: self.tree.insert(
                        "", "end", text=n, values=("", "MISSING"),
                        tags=("missing",)))
                    continue
                try:
                    actual = _file_hash(target, algo, cancel=self._stop.is_set)
                except Exception as exc:
                    actual = f"error: {exc}"
                good = actual.lower() == expected.lower()
                ok, bad = (ok + 1, bad) if good else (ok, bad + 1)
                self.after(0, lambda n=name, a=actual, g=good: self.tree.insert(
                    "", "end", text=n, values=(a, "OK" if g else "FAILED"),
                    tags=("ok" if g else "bad",)))
                self.after(0, lambda i=i: self._status.configure(
                    text=f"Verifying {i} / {len(entries)} …", fg=C_ACCENT))
            self._busy = False
            colour = "#7ee787" if (bad == 0 and missing == 0) else "#ff6b6b"
            self.after(0, lambda: self._status.configure(
                text=f"Verified {os.path.basename(path)} ({algo.upper()}) — "
                     f"{ok} OK, {bad} failed, {missing} missing", fg=colour))

        threading.Thread(target=worker, daemon=True).start()


# ══════════════════════════════════════════════════════════════════════════
#  DEL 28 — Split / combine files
# ══════════════════════════════════════════════════════════════════════════

SPLIT_PRESETS = [
    ("1.44 MB  (floppy)",      1_457_664),
    ("10 MB",                  10 * 1024 * 1024),
    ("100 MB",                 100 * 1024 * 1024),
    ("700 MB  (CD)",           700 * 1024 * 1024),
    ("4700 MB (DVD)",          4700 * 1024 * 1024),
    ("Custom…",                0),
]


class SplitFileWindow(tk.Toplevel):
    """Split one large file into numbered parts (.001, .002 …)."""

    def __init__(self, manager: "EditorFrame", path: str, dest_dir: str):
        super().__init__(manager)
        self.manager = manager
        self.path    = path
        self.configure(bg=C_BG)
        self.resizable(False, False)
        _setup_toplevel(self, "Split file", manager, modal=False)

        try:
            self.size = os.path.getsize(path)
        except OSError:
            self.size = 0

        self.var_dest   = tk.StringVar(value=dest_dir)
        self.var_preset = tk.StringVar(value=SPLIT_PRESETS[1][0])
        self.var_custom = tk.StringVar(value="10")
        self.var_crc    = tk.BooleanVar(value=True)

        body = tk.Frame(self, bg=C_BG, padx=16, pady=14)
        body.pack(fill="both", expand=True)

        tk.Label(body, text="✂  Split file", bg=C_BG, fg=C_ACCENT,
                 font=("Segoe UI", 12, "bold")).pack(anchor="w")
        tk.Label(body, text=f"{os.path.basename(path)}   ·   {_human_size(self.size)}",
                 bg=C_BG, fg=C_FG, font=("Segoe UI", 9)).pack(anchor="w", pady=(2, 12))

        row = tk.Frame(body, bg=C_BG)
        row.pack(fill="x", pady=3)
        tk.Label(row, text="Target folder:", bg=C_BG, fg=C_FG,
                 width=14, anchor="w").pack(side="left")
        tk.Entry(row, textvariable=self.var_dest, width=44, bg=C_BG2, fg=C_FG,
                 insertbackground=C_FG,
                 insertofftime=0, insertontime=9999999).pack(side="left")
        tk.Button(row, text="…", width=3, bg="white", fg="black",
                  command=self._browse).pack(side="left", padx=4)

        row2 = tk.Frame(body, bg=C_BG)
        row2.pack(fill="x", pady=3)
        tk.Label(row2, text="Part size:", bg=C_BG, fg=C_FG,
                 width=14, anchor="w").pack(side="left")
        cb = ttk.Combobox(row2, textvariable=self.var_preset, width=22,
                          state="readonly", values=[p[0] for p in SPLIT_PRESETS])
        cb.pack(side="left")
        cb.bind("<<ComboboxSelected>>", lambda e: self._update_estimate())
        tk.Entry(row2, textvariable=self.var_custom, width=8, bg=C_BG2, fg=C_FG,
                 insertbackground=C_FG,
                 insertofftime=0, insertontime=9999999).pack(side="left", padx=(8, 2))
        tk.Label(row2, text="MB", bg=C_BG, fg=C_FG_DIM).pack(side="left")
        self.var_custom.trace_add("write", lambda *_: self._update_estimate())

        tk.Checkbutton(body, text="Also write a .crc file for verification",
                       variable=self.var_crc, bg=C_BG, fg=C_FG, selectcolor=C_BG2,
                       activebackground=C_BG,
                       activeforeground=C_FG).pack(anchor="w", pady=(8, 0))

        self._est = tk.Label(body, text="", bg=C_BG, fg=C_FG_DIM,
                             font=("Segoe UI", 9))
        self._est.pack(anchor="w", pady=(8, 12))

        btns = tk.Frame(body, bg=C_BG)
        btns.pack(fill="x")
        tk.Button(btns, text="Cancel", bg="grey", fg="white", width=10,
                  command=self.destroy).pack(side="right", padx=3)
        tk.Button(btns, text="✂  Split", bg="lightgreen", fg="black", width=12,
                  command=self._split).pack(side="right", padx=3)

        self.bind("<Return>", lambda e: self._split())
        self._update_estimate()

    def _browse(self):
        d = filedialog.askdirectory(title="Split into folder", parent=self,
                                    initialdir=self.var_dest.get())
        if d:
            self.var_dest.set(d)

    def _part_size(self) -> int:
        label = self.var_preset.get()
        for name, size in SPLIT_PRESETS:
            if name == label and size:
                return size
        try:
            return max(1, int(float(self.var_custom.get()) * 1024 * 1024))
        except Exception:
            return 10 * 1024 * 1024

    def _update_estimate(self):
        ps = self._part_size()
        n = (self.size + ps - 1) // ps if ps else 0
        self._est.configure(
            text=f"→  {n} part(s) of {_human_size(ps)}  "
                 f"(last part {_human_size(self.size - ps * (n - 1))})"
            if n else "")

    def _split(self):
        dest = self.var_dest.get()
        if not os.path.isdir(dest):
            messagebox.showerror("Split", "Choose an existing target folder.",
                                 parent=self)
            return
        ps = self._part_size()
        n_parts = (self.size + ps - 1) // ps
        if n_parts > 999:
            messagebox.showerror(
                "Split",
                f"That part size would create {n_parts} parts.\n"
                "The .001 … .999 naming scheme allows at most 999 — "
                "choose a larger part size.", parent=self)
            return

        base = os.path.basename(self.path)
        dlg = _ProgressDialog(self, "Splitting", total=n_parts)

        def worker():
            written, crc = [], 0
            try:
                with open(self.path, "rb") as src:
                    for part in range(1, n_parts + 1):
                        if dlg.cancelled:
                            break
                        out_path = os.path.join(dest, f"{base}.{part:03d}")
                        dlg.post("progress", part, n_parts, os.path.basename(out_path))
                        remaining = ps
                        with open(out_path, "wb") as dst:
                            while remaining > 0:
                                chunk = src.read(min(1 << 20, remaining))
                                if not chunk:
                                    break
                                dst.write(chunk)
                                crc = zlib.crc32(chunk, crc)
                                remaining -= len(chunk)
                        written.append(out_path)
                if self.var_crc.get() and not dlg.cancelled:
                    with open(os.path.join(dest, f"{base}.crc"), "w",
                              encoding="utf-8") as fh:
                        fh.write(f"filename={base}\n")
                        fh.write(f"size={self.size}\n")
                        fh.write(f"parts={len(written)}\n")
                        fh.write(f"crc32={crc & 0xFFFFFFFF:08X}\n")
                dlg.post("done")
                self.after(0, lambda: self._done(written, dlg.cancelled))
            except Exception as exc:
                dlg.post("done")
                self.after(0, lambda e=exc: messagebox.showerror(
                    "Split", f"Split failed:\n{e}", parent=self))

        threading.Thread(target=worker, daemon=True).start()

    def _done(self, written: list, cancelled: bool):
        self.manager.refresh_panels()
        if cancelled:
            messagebox.showinfo("Split", f"Cancelled — {len(written)} part(s) written.",
                                parent=self)
        else:
            _flash_ok(self.manager, f"Split into {len(written)} part(s).", "Split")
            self.destroy()


def combine_parts(manager: "EditorFrame", first_part: str):
    """Recombine a .001/.002/… series back into the original file."""
    folder = os.path.dirname(first_part)
    base   = os.path.basename(first_part)
    stem, ext = os.path.splitext(base)
    if not _re.fullmatch(r"\.\d{3}", ext):
        messagebox.showerror(
            "Combine",
            "Select the first part of a split file (the one ending in .001).")
        return

    parts = []
    i = 1
    while True:
        p = os.path.join(folder, f"{stem}.{i:03d}")
        if not os.path.isfile(p):
            break
        parts.append(p)
        i += 1
    if not parts:
        messagebox.showerror("Combine", "No numbered parts found.")
        return

    out_path = os.path.join(folder, stem)
    if os.path.exists(out_path):
        if not _ask_yes_no(
                "Combine",
                f"{stem} already exists.\n\nOverwrite it?"):
            return

    # Read the .crc sidecar written by the split function, when present
    expected_crc = expected_size = None
    crc_file = os.path.join(folder, f"{stem}.crc")
    if os.path.isfile(crc_file):
        try:
            info = dict(line.strip().split("=", 1)
                        for line in open(crc_file, encoding="utf-8")
                        if "=" in line)
            expected_crc  = info.get("crc32", "").upper() or None
            expected_size = int(info.get("size", 0)) or None
        except Exception:
            pass

    dlg = _ProgressDialog(manager, "Combining", total=len(parts))

    def worker():
        crc, total = 0, 0
        try:
            with open(out_path, "wb") as dst:
                for i, part in enumerate(parts, 1):
                    if dlg.cancelled:
                        break
                    dlg.post("progress", i, len(parts), os.path.basename(part))
                    with open(part, "rb") as src:
                        while True:
                            chunk = src.read(1 << 20)
                            if not chunk:
                                break
                            dst.write(chunk)
                            crc = zlib.crc32(chunk, crc)
                            total += len(chunk)
            dlg.post("done")
            actual_crc = f"{crc & 0xFFFFFFFF:08X}"
            manager.after(0, lambda: _combine_done(
                manager, out_path, len(parts), total,
                actual_crc, expected_crc, expected_size, dlg.cancelled))
        except Exception as exc:
            dlg.post("done")
            manager.after(0, lambda e=exc: messagebox.showerror(
                "Combine", f"Combine failed:\n{e}"))

    threading.Thread(target=worker, daemon=True).start()


def _combine_done(manager, out_path, n_parts, total, actual_crc,
                  expected_crc, expected_size, cancelled):
    manager.refresh_panels()
    if cancelled:
        messagebox.showinfo("Combine", "Cancelled — the output file is incomplete.")
        return
    if expected_crc:
        if actual_crc == expected_crc and (not expected_size or total == expected_size):
            _flash_ok(manager,
                      f"Combined {n_parts} parts into\n{os.path.basename(out_path)}\n"
                      f"CRC32 verified OK.", "Combined")
        else:
            messagebox.showerror(
                "Combine",
                f"The parts were joined, but verification FAILED.\n\n"
                f"Expected CRC32: {expected_crc}\nActual CRC32:   {actual_crc}\n"
                f"Expected size:  {expected_size}\nActual size:    {total}\n\n"
                "One or more parts are probably missing or damaged.")
    else:
        _flash_ok(manager,
                  f"Combined {n_parts} parts into\n{os.path.basename(out_path)}",
                  "Combined")


# ══════════════════════════════════════════════════════════════════════════
#  DEL 45b — Folder sort overrides: the list of every rule
# ══════════════════════════════════════════════════════════════════════════

class FolderSortManagerWindow(tk.Toplevel):
    """Every folder that has a sort of its own, in one place: see them, jump to
    them, and remove the ones you no longer want."""

    _COL_NAMES = {"#0": "Name", "type": "Type", "flag": FLAG_CHAR,
                  "size": "Size", "modified": "Modified",
                  "attributes": "Attr", "tags": "Tags"}

    def __init__(self, manager: "EditorFrame"):
        super().__init__(manager)
        self.manager = manager
        self.configure(bg=C_BG)
        self.geometry("900x460")
        _setup_toplevel(self, "Folder sort overrides", manager, modal=False)

        head = tk.Frame(self, bg=C_BG3)
        head.pack(fill="x")
        tk.Label(head, text="🔀  Folder sort overrides", bg=C_BG3, fg=C_ACCENT,
                 font=("Segoe UI", 12, "bold")).pack(side="left", padx=10, pady=7)
        tk.Label(head, text="A folder listed here ignores the window's sort and "
                            "uses its own — only while you stand in it.",
                 bg=C_BG3, fg=C_FG_DIM, font=("Segoe UI", 9)).pack(side="left")

        mid = tk.Frame(self, bg=C_BG)
        mid.pack(fill="both", expand=True, padx=10, pady=8)
        self.tree = ttk.Treeview(mid, columns=("files", "dirs", "sub"),
                                 selectmode="browse")
        self.tree.heading("#0",    text="Folder", anchor="w")
        self.tree.heading("files", text="Files sorted by", anchor="w")
        self.tree.heading("dirs",  text="Sub-folders sorted by", anchor="w")
        self.tree.heading("sub",   text="Applies below", anchor="w")
        self.tree.column("#0",    width=420, stretch=True)
        self.tree.column("files", width=170, stretch=False)
        self.tree.column("dirs",  width=170, stretch=False)
        self.tree.column("sub",   width=100, stretch=False)
        sb = ttk.Scrollbar(mid, orient="vertical", command=self.tree.yview)
        self.tree.configure(yscrollcommand=sb.set)
        sb.pack(side="right", fill="y")
        self.tree.pack(side="left", fill="both", expand=True)
        self.tree.bind("<Double-1>", lambda e: self._open("active"))
        self.tree.tag_configure("gone", foreground=TC_BAD)

        bot = tk.Frame(self, bg=C_BG)
        bot.pack(fill="x", padx=10, pady=(0, 10))
        tk.Button(bot, text="🗑  Remove override", bg="#ff8888", fg="black",
                  command=self._remove).pack(side="left", padx=2)
        tk.Button(bot, text="Toggle 'applies below'", bg="white", fg="black",
                  command=self._toggle_sub).pack(side="left", padx=2)
        tk.Button(bot, text="🧹  Remove rules for folders that are gone",
                  bg="white", fg="black",
                  command=self._prune).pack(side="left", padx=2)
        tk.Button(bot, text="Close", bg="grey", fg="white", width=9,
                  command=self.destroy).pack(side="right", padx=2)
        tk.Button(bot, text="Open right →", bg="lightblue", fg="black",
                  command=lambda: self._open("right")).pack(side="right", padx=2)
        tk.Button(bot, text="← Open left", bg="lightblue", fg="black",
                  command=lambda: self._open("left")).pack(side="right", padx=2)

        self.bind("<Return>", lambda e: self._open("active"))
        self._render()

    # ---- helpers ----
    def _describe(self, col, rev):
        name = self._COL_NAMES.get(col, col or "?")
        if col in ("modified", "size"):
            return f"{name}  {'newest/largest first' if rev else 'oldest/smallest first'}"
        return f"{name}  {'Z → A' if rev else 'A → Z'}"

    def _render(self):
        self.tree.delete(*self.tree.get_children())
        for key in sorted(self.manager.folder_sorts):
            rule = self.manager.folder_sorts.get(key)
            if not isinstance(rule, dict) or not rule.get("sort"):
                continue
            s = list(rule["sort"]) + ["", False, "", False]
            path = rule.get("path") or key
            exists = os.path.isdir(path)
            self.tree.insert(
                "", "end", iid=key,
                text=("📁  " if exists else "⚠  ") + path,
                values=(self._describe(s[0], bool(s[1])),
                        self._describe(s[2], bool(s[3])),
                        "yes" if rule.get("sub") else ""),
                tags=() if exists else ("gone",))

    def _sel_key(self):
        sel = self.tree.selection()
        return sel[0] if sel else None

    def _sel_path(self):
        key = self._sel_key()
        if not key:
            return None
        rule = self.manager.folder_sorts.get(key) or {}
        return rule.get("path") or key

    # ---- actions ----
    def _remove(self):
        path = self._sel_path()
        if not path:
            return
        self.manager.clear_folder_sort(path)
        self._render()

    def _toggle_sub(self):
        key = self._sel_key()
        if not key:
            return
        rule = self.manager.folder_sorts.get(key) or {}
        self.manager.set_folder_sort_sub(rule.get("path") or key,
                                         not bool(rule.get("sub")))
        self._render()

    def _prune(self):
        gone = [k for k, r in self.manager.folder_sorts.items()
                if isinstance(r, dict) and not os.path.isdir(r.get("path") or k)]
        if not gone:
            _flash_ok(self, "Every rule points at a folder that exists.",
                      "Folder sort")
            return
        if not _ask_yes_no(
                "Remove rules", f"Remove {len(gone)} rule(s) whose folder no "
                                f"longer exists?", parent=self):
            return
        for k in gone:
            self.manager.folder_sorts.pop(k, None)
        _save_json_dict(FOLDER_SORTS_PATH, self.manager.folder_sorts,
                        portable=True)
        self.manager._apply_folder_sorts()
        self._render()

    def _open(self, side):
        path = self._sel_path()
        if not path or not os.path.isdir(path):
            return
        panel = (self.manager.get_active_panel() if side == "active"
                 else (self.manager.left_panel if side == "left"
                       else self.manager.right_panel))
        panel.change_directory(path)


# ══════════════════════════════════════════════════════════════════════════
#  DEL 29 — Directory hotlist  (Ctrl+D)
# ══════════════════════════════════════════════════════════════════════════

class HotlistWindow(tk.Toplevel):
    """Manage the list of favourite local folders."""

    def __init__(self, manager: "EditorFrame"):
        super().__init__(manager)
        self.manager = manager
        self.configure(bg=C_BG)
        self.geometry("680x460")
        _setup_toplevel(self, "Directory hotlist", manager, modal=False)

        head = tk.Frame(self, bg=C_BG3)
        head.pack(fill="x")
        tk.Label(head, text="⭐  Directory hotlist", bg=C_BG3, fg=C_ACCENT,
                 font=("Segoe UI", 12, "bold")).pack(side="left", padx=10, pady=7)
        tk.Label(head, text="Ctrl+D opens this list from anywhere",
                 bg=C_BG3, fg=C_FG_DIM, font=("Segoe UI", 9)).pack(side="left")

        mid = tk.Frame(self, bg=C_BG)
        mid.pack(fill="both", expand=True, padx=10, pady=8)
        self.tree = ttk.Treeview(mid, columns=("path",), selectmode="browse")
        self.tree.heading("#0",   text="Name", anchor="w")
        self.tree.heading("path", text="Folder", anchor="w")
        self.tree.column("#0", width=180)
        self.tree.column("path", width=440, stretch=True)
        sb = ttk.Scrollbar(mid, orient="vertical", command=self.tree.yview)
        self.tree.configure(yscrollcommand=sb.set)
        self.tree.pack(side="left", fill="both", expand=True)
        sb.pack(side="right", fill="y")
        self.tree.bind("<Double-1>", lambda e: self._open("active"))
        self.tree.tag_configure("gone", foreground=TC_BAD)

        bot = tk.Frame(self, bg=C_BG)
        bot.pack(fill="x", padx=10, pady=(0, 10))
        tk.Button(bot, text="＋  Add current folder", bg="lightgreen", fg="black",
                  command=self._add_current).pack(side="left", padx=2)
        tk.Button(bot, text="Rename", bg="white", fg="black",
                  command=self._rename).pack(side="left", padx=2)
        tk.Button(bot, text="↑", width=3, bg="white", fg="black",
                  command=lambda: self._move(-1)).pack(side="left", padx=2)
        tk.Button(bot, text="↓", width=3, bg="white", fg="black",
                  command=lambda: self._move(1)).pack(side="left", padx=2)
        tk.Button(bot, text="🗑  Remove", bg="#ff8888", fg="black",
                  command=self._remove).pack(side="left", padx=2)
        tk.Button(bot, text="Close", bg="grey", fg="white", width=9,
                  command=self.destroy).pack(side="right", padx=2)
        tk.Button(bot, text="Open right →", bg="lightblue", fg="black",
                  command=lambda: self._open("right")).pack(side="right", padx=2)
        tk.Button(bot, text="← Open left", bg="lightblue", fg="black",
                  command=lambda: self._open("left")).pack(side="right", padx=2)

        self.bind("<Return>", lambda e: self._open("active"))
        self._render()

    def _render(self):
        self.tree.delete(*self.tree.get_children())
        for i, fav in enumerate(self.manager.hotlist):
            exists = os.path.isdir(fav.get("path", ""))
            self.tree.insert("", "end", iid=str(i),
                             text=("⭐  " if exists else "⚠  ") + fav.get("name", ""),
                             values=(fav.get("path", ""),),
                             tags=() if exists else ("gone",))

    def _selected(self):
        sel = self.tree.selection()
        return int(sel[0]) if sel else None

    def _add_current(self):
        path = self.manager.get_active_panel().current_path
        name = _ask_text(self, "Add to hotlist", "Name for this folder:",
                         initial=os.path.basename(path.rstrip("\\/")) or path)
        if not name:
            return
        self.manager.hotlist.append({"name": name, "path": path})
        self.manager.save_hotlist()
        self._render()

    def _rename(self):
        i = self._selected()
        if i is None:
            return
        name = _ask_text(self, "Rename", "New name:",
                         initial=self.manager.hotlist[i]["name"])
        if name:
            self.manager.hotlist[i]["name"] = name
            self.manager.save_hotlist()
            self._render()

    def _move(self, delta: int):
        i = self._selected()
        if i is None:
            return
        j = i + delta
        if 0 <= j < len(self.manager.hotlist):
            hl = self.manager.hotlist
            hl[i], hl[j] = hl[j], hl[i]
            self.manager.save_hotlist()
            self._render()
            self.tree.selection_set(str(j))

    def _remove(self):
        i = self._selected()
        if i is None:
            return
        del self.manager.hotlist[i]
        self.manager.save_hotlist()
        self._render()

    def _open(self, side: str):
        i = self._selected()
        if i is None:
            return
        path = self.manager.hotlist[i].get("path", "")
        if not os.path.isdir(path):
            messagebox.showerror("Hotlist", f"This folder no longer exists:\n{path}",
                                 parent=self)
            return
        panel = (self.manager.get_active_panel() if side == "active"
                 else getattr(self.manager, f"{side}_panel"))
        if getattr(panel, "is_remote", False):
            messagebox.showinfo("Hotlist",
                                "That panel is mounted on FTP — unmount it first.",
                                parent=self)
            return
        panel.change_directory(path)
        self.destroy()


# ══════════════════════════════════════════════════════════════════════════
#  DEL 30 — Directory print / export  (TXT / CSV / HTML / PDF)
# ══════════════════════════════════════════════════════════════════════════

class PrintListingWindow(tk.Toplevel):
    """Export or print the contents of a folder as TXT / CSV / HTML / PDF."""

    def __init__(self, manager: "EditorFrame", folder: str):
        super().__init__(manager)
        self.manager = manager
        self.folder  = folder
        self.configure(bg=C_BG)
        # Wide enough for the option rows to fit without clipping — the depth
        # box and the name filter pushed the first row past the old 760.
        self.geometry("900x620")
        _setup_toplevel(self, "Print / export folder listing", manager, modal=False)

        # Last time's choices — the window opens the way you left it.
        try:
            saved = dict(manager.settings.get("print_listing", {}) or {})
        except Exception:
            saved = {}
        saved_cols = saved.get("columns", {}) or {}

        self.var_recursive = tk.BooleanVar(value=bool(saved.get("recursive", False)))
        self.var_selected_only = tk.BooleanVar(
            value=bool(saved.get("selected_only", False)))
        self.var_format = tk.StringVar(value=saved.get("format", "txt"))
        # What goes in the listing: files, folders, both — or the compact
        # tree, which is one line per folder with its files listed after it.
        inc = saved.get("include", "both")
        self.var_include = tk.StringVar(
            value=inc if inc in ("both", "files", "dirs", "tree") else "both")
        # How many folder levels to go down.  0 = no limit, which is what
        # "Include subfolders" on its own always meant, so an older saved
        # setting keeps behaving exactly as it did.
        self.var_depth = tk.StringVar(value=str(saved.get("depth", 0) or 0))
        # Comma-separated wildcards (*.exe, Backup*).  Matched against FILE
        # names only — a folder is structure, not content, and filtering
        # folders away would silently hide everything underneath them.
        self.var_filter = tk.StringVar(value=saved.get("filter", ""))
        # One unit for the whole Size column, or "Auto" for the friendliest
        # per row.  A fixed unit is what makes the column addable.
        unit = saved.get("size_unit", "Auto")
        self.var_unit = tk.StringVar(
            value=unit if unit in _SIZE_UNITS else "Auto")
        self._last_total_bytes = 0
        # Marks have done their job once the listing is out — see _finish_ok().
        self.var_clear_marks = tk.BooleanVar(
            value=bool(saved.get("clear_marks", True)))
        self.var_cols = {
            "name":     tk.BooleanVar(value=bool(saved_cols.get("name", True))),
            "size":     tk.BooleanVar(value=bool(saved_cols.get("size", True))),
            "modified": tk.BooleanVar(value=bool(saved_cols.get("modified", True))),
            "type":     tk.BooleanVar(value=bool(saved_cols.get("type", True))),
            "attr":     tk.BooleanVar(value=bool(saved_cols.get("attr", False))),
            "path":     tk.BooleanVar(value=bool(saved_cols.get("path", False))),
            "version":  tk.BooleanVar(value=bool(saved_cols.get("version", False))),
        }
        # The preview can be narrowed to the lines that match a word.  The
        # full render is kept apart from it so a save or a print is never
        # quietly reduced to whatever the box happens to be showing.
        self.var_find = tk.StringVar()
        self._full_text = ""

        head = tk.Frame(self, bg=C_BG3)
        head.pack(fill="x")
        tk.Label(head, text="🖨  Print / export listing", bg=C_BG3, fg=C_ACCENT,
                 font=("Segoe UI", 12, "bold")).pack(side="left", padx=10, pady=7)

        opt = tk.Frame(self, bg=C_BG)
        opt.pack(fill="x", padx=10, pady=8)
        tk.Label(opt, text=f"Folder:  {folder}", bg=C_BG, fg=C_FG,
                 anchor="w").pack(fill="x")

        r1 = tk.Frame(opt, bg=C_BG)
        r1.pack(fill="x", pady=(8, 2))
        self._cb_recursive = tk.Checkbutton(
            r1, text="Include subfolders", variable=self.var_recursive,
            bg=C_BG, fg=C_FG, selectcolor=C_BG2, activebackground=C_BG,
            activeforeground=C_FG, command=self._preview)
        self._cb_recursive.pack(side="left")
        self._lbl_depth = tk.Label(r1, text="levels:", bg=C_BG, fg=C_FG)
        self._lbl_depth.pack(side="left", padx=(8, 2))
        self._e_depth = tk.Entry(r1, textvariable=self.var_depth, width=4,
                                 bg=C_BG2, fg=C_FG, insertbackground=C_FG,
                                 insertofftime=0, insertontime=9999999)
        self._e_depth.pack(side="left")
        self._e_depth.bind("<KeyRelease>", lambda e: self._preview())
        tk.Label(r1, text="(0 = all)", bg=C_BG,
                 fg=C_FG_DIM).pack(side="left", padx=(4, 0))
        self._cb_selected = tk.Checkbutton(
            r1, text="Only selected items", variable=self.var_selected_only,
            bg=C_BG, fg=C_FG, selectcolor=C_BG2, activebackground=C_BG,
            activeforeground=C_FG, command=self._preview)
        self._cb_selected.pack(side="left", padx=(12, 0))
        tk.Checkbutton(r1, text="Clear the marks after a successful print / export",
                       variable=self.var_clear_marks,
                       bg=C_BG, fg=C_FG, selectcolor=C_BG2, activebackground=C_BG,
                       activeforeground=C_FG,
                       command=self._preview).pack(side="left", padx=(12, 0))

        # What to list: everything, only the files, only the folders, or the
        # compact tree — one line per folder with its files after it.
        r1b = tk.Frame(opt, bg=C_BG)
        r1b.pack(fill="x", pady=2)
        tk.Label(r1b, text="Include:", bg=C_BG, fg=C_FG).pack(side="left")
        for label, val in (("Files and folders", "both"),
                           ("Files only", "files"),
                           ("Folders only", "dirs"),
                           ("Compact tree", "tree")):
            tk.Radiobutton(r1b, text=label, value=val, variable=self.var_include,
                           bg=C_BG, fg=C_FG, selectcolor=C_BG2,
                           activebackground=C_BG, activeforeground=C_FG,
                           command=self._on_include).pack(side="left", padx=4)

        # Name filter — the listing's own, so a folder full of build output
        # can come out as just the *.exe without touching the panel.
        r1c = tk.Frame(opt, bg=C_BG)
        r1c.pack(fill="x", pady=2)
        tk.Label(r1c, text="Name filter:", bg=C_BG, fg=C_FG).pack(side="left")
        e_filter = tk.Entry(r1c, textvariable=self.var_filter, width=34,
                            bg=C_BG2, fg=C_FG, insertbackground=C_FG,
                            insertofftime=0, insertontime=9999999)
        e_filter.pack(side="left", padx=(6, 6))
        e_filter.bind("<KeyRelease>", lambda e: self._preview())
        tk.Label(r1c, text="e.g.  *.exe,*.dll   ·   empty = every file   ·   "
                           "folders are never filtered",
                 bg=C_BG, fg=C_FG_DIM).pack(side="left")

        r2 = tk.Frame(opt, bg=C_BG)
        r2.pack(fill="x", pady=2)
        tk.Label(r2, text="Columns:", bg=C_BG, fg=C_FG).pack(side="left")
        self._col_boxes = {}
        for key, label in (("name", "Name"), ("size", "Size"),
                           ("modified", "Modified"), ("type", "Type"),
                           ("attr", "Attr"), ("path", "Full path"),
                           ("version", "Version")):
            cb = tk.Checkbutton(r2, text=label, variable=self.var_cols[key],
                                bg=C_BG, fg=C_FG, selectcolor=C_BG2,
                                activebackground=C_BG, activeforeground=C_FG,
                                command=self._preview)
            cb.pack(side="left", padx=3)
            self._col_boxes[key] = cb
        tk.Label(r2, text="Size in:", bg=C_BG, fg=C_FG).pack(side="left",
                                                             padx=(14, 4))
        self._unit_menu = tk.OptionMenu(r2, self.var_unit, *_SIZE_UNITS,
                                        command=lambda _v: self._preview())
        self._unit_menu.configure(bg=C_BG2, fg=C_FG, activebackground=C_BG3,
                                  activeforeground=C_FG, highlightthickness=0,
                                  relief="flat", width=6)
        self._unit_menu["menu"].configure(bg=C_BG2, fg=C_FG)
        self._unit_menu.pack(side="left")

        r3 = tk.Frame(opt, bg=C_BG)
        r3.pack(fill="x", pady=(6, 2))
        tk.Label(r3, text="Format:", bg=C_BG, fg=C_FG).pack(side="left")
        for label, val in (("Plain text", "txt"), ("CSV", "csv"),
                           ("HTML", "html"), ("PDF", "pdf")):
            tk.Radiobutton(r3, text=label, value=val, variable=self.var_format,
                           bg=C_BG, fg=C_FG, selectcolor=C_BG2,
                           activebackground=C_BG, activeforeground=C_FG,
                           command=self._preview).pack(side="left", padx=4)

        # The button row is packed BEFORE the preview, and against the bottom.
        # pack hands out space in the order things are packed, so the preview
        # with expand=True takes everything that is left — pack it first and
        # this row is starved down to a few pixels of unclickable sliver, and
        # disappears completely as soon as the window is made smaller.
        bot = tk.Frame(self, bg=C_BG)
        bot.pack(side="bottom", fill="x", padx=10, pady=(0, 10))
        self._status = tk.Label(bot, text="", bg=C_BG, fg=C_FG_DIM, anchor="w")
        self._status.pack(side="left", fill="x", expand=True)
        tk.Button(bot, text="Close", bg="grey", fg="white", width=9,
                  command=self.destroy).pack(side="right", padx=3)
        tk.Button(bot, text="🖨  Print…", bg="lightblue", fg="black",
                  command=self._print).pack(side="right", padx=3)
        tk.Button(bot, text="📋  Copy", bg="white", fg="black",
                  command=self._copy).pack(side="right", padx=3)
        tk.Button(bot, text="💾  Save as…", bg="lightgreen", fg="black", width=12,
                  command=self._save).pack(side="right", padx=3)

        prow = tk.Frame(self, bg=C_BG)
        prow.pack(fill="x", padx=10)
        tk.Label(prow, text="Preview:", bg=C_BG, fg=C_FG_DIM,
                 anchor="w").pack(side="left")
        tk.Label(prow, text="Find:", bg=C_BG, fg=C_FG).pack(side="left", padx=(16, 4))
        e_find = tk.Entry(prow, textvariable=self.var_find, width=24,
                          bg=C_BG2, fg=C_FG, insertbackground=C_FG,
                          insertofftime=0, insertontime=9999999)
        e_find.pack(side="left")
        e_find.bind("<KeyRelease>", lambda e: self._apply_find())
        tk.Button(prow, text="✕", bg=C_BG2, fg=C_FG, bd=0,
                  command=self._clear_find).pack(side="left", padx=(4, 0))
        tk.Label(prow, text="narrows the preview — 📋 Copy then takes just those",
                 bg=C_BG, fg=C_FG_DIM).pack(side="left", padx=(8, 0))
        pf = tk.Frame(self, bg=C_BG)
        pf.pack(fill="both", expand=True, padx=10, pady=(2, 6))
        self.preview = tk.Text(pf, wrap="none", bg=C_BG2, fg=C_FG,
                               font=("Consolas", 9), padx=6, pady=4,
                               insertofftime=0, insertontime=9999999)
        vsb = ttk.Scrollbar(pf, orient="vertical", command=self.preview.yview)
        self.preview.configure(yscrollcommand=vsb.set)
        self.preview.pack(side="left", fill="both", expand=True)
        vsb.pack(side="right", fill="y")

        self.bind("<Return>", lambda e: self._save())
        self._preview()

    # ── Data gathering ────────────────────────────────────────────────────

    def _depth(self) -> int:
        """Folder levels to descend.  0 — or anything that is not a number —
        means no limit, so a half-typed value never truncates a listing."""
        try:
            return max(0, int(str(self.var_depth.get()).strip() or "0"))
        except ValueError:
            return 0

    def _patterns(self) -> list:
        """The name filter split on commas.  An empty list keeps every file."""
        return [p.strip().lower()
                for p in self.var_filter.get().split(",") if p.strip()]

    @staticmethod
    def _keep_file(name: str, patterns: list) -> bool:
        if not patterns:
            return True
        low = name.lower()
        return any(fnmatch.fnmatch(low, pat) for pat in patterns)

    def _gather(self) -> list:
        """Return [(display_name, size, modified, type, attr, path, version)].

        Honours the Include choice (everything / only files / only folders),
        the depth limit and the name filter.
        """
        rows = []
        total = 0
        include = self.var_include.get()
        patterns = self._patterns()
        unit = self.var_unit.get()
        if self.var_selected_only.get():
            paths = self.manager.get_active_panel().get_all_selected()
        elif self.var_recursive.get():
            paths = []
            limit = self._depth()
            base = os.path.normpath(self.folder)
            for dirpath, dirs, files in os.walk(self.folder):
                # The entries of THIS folder are listed before the pruning, so
                # "1 level" still names the subfolders it refuses to open.
                paths.extend(os.path.join(dirpath, d) for d in dirs)
                paths.extend(os.path.join(dirpath, f) for f in files)
                if not limit:
                    continue
                here = 0 if os.path.normpath(dirpath) == base else \
                    len(os.path.relpath(dirpath, self.folder).split(os.sep))
                if here + 1 >= limit:
                    dirs[:] = []          # go no deeper down this branch
        else:
            try:
                paths = [os.path.join(self.folder, n)
                         for n in sorted(os.listdir(self.folder))]
            except OSError as exc:
                self._status.configure(text=f"Could not read folder: {exc}",
                                       fg="#ff6b6b")
                return []

        for p in paths:
            try:
                st = os.stat(p)
                is_dir = os.path.isdir(p)
                if (include == "files" and is_dir) or \
                   (include == "dirs" and not is_dir):
                    continue
                name = os.path.basename(p)
                if not is_dir and not self._keep_file(name, patterns):
                    continue
                ext = os.path.splitext(p)[1].lower()
                if not is_dir:
                    total += st.st_size
                rows.append((
                    os.path.relpath(p, self.folder) if self.var_recursive.get()
                    else name,
                    "<DIR>" if is_dir else _size_in_unit(st.st_size, unit),
                    f"{datetime.fromtimestamp(st.st_mtime):%Y-%m-%d %H:%M}",
                    "Folder" if is_dir else _EXT_TYPE.get(ext, ext.lstrip(".").upper() or "File"),
                    self._attr_string(p),
                    p,
                    _version_token(name),
                ))
            except OSError:
                continue
        # Kept for the summary line: counting the rows says how many things
        # are listed, which is not the question "how big is this folder".
        self._last_total_bytes = total
        return rows

    def _gather_tree(self) -> list:
        """The compact tree: [(folder, files joined, version)], one per folder.

        This is Dir_lister's listing, which this window took over: one line per
        folder with its files after it, so a whole build tree fits on a screen
        instead of a page per folder.  The version token is looked for in the
        shown files first, then in the ones the filter hid, and last in the
        folder's own name — a folder is usually named for what is in it.
        """
        rows = []
        total = [0]
        limit = self._depth() if self.var_recursive.get() else 1
        patterns = self._patterns()
        want_files = self.var_include.get() != "dirs"
        root = os.path.abspath(self.folder)

        def walk(cur: str, level: int):
            try:
                entries = sorted(os.listdir(cur), key=str.lower)
            except OSError:
                return                      # unreadable branch — skip it
            dirs, files = [], []
            for e in entries:
                (dirs if os.path.isdir(os.path.join(cur, e)) else files).append(e)

            rel = os.path.relpath(cur, root)
            if rel == ".":
                rel = os.path.basename(root) or root

            shown, token = [], ""
            if want_files and files:
                shown = [f for f in files if self._keep_file(f, patterns)]
                for fname in shown:
                    try:
                        total[0] += os.path.getsize(os.path.join(cur, fname))
                    except OSError:
                        pass
                for fname in reversed(shown):
                    token = _version_token(fname)
                    if token:
                        break
            if not token:
                for fname in reversed(files):
                    token = _version_token(fname)
                    if token:
                        break
            if not token:
                token = _version_token(os.path.basename(cur))

            rows.append((rel, ", ".join(shown), token))
            if not limit or level < limit:
                for d in dirs:
                    walk(os.path.join(cur, d), level + 1)

        if os.path.isdir(root):
            walk(root, 1)
        self._last_total_bytes = total[0]
        return rows

    @staticmethod
    def _attr_string(path: str) -> str:
        try:
            bits = ctypes.windll.kernel32.GetFileAttributesW(path)
        except Exception:
            return ""
        out = ""
        for mask, ch in ((0x01, "R"), (0x02, "H"), (0x04, "S"), (0x20, "A")):
            if bits & mask:
                out += ch
        return out or "-"

    def _active_columns(self):
        # With a fixed unit the cells are bare numbers, so the unit has to be
        # in the heading or the column means nothing on its own.
        unit = self.var_unit.get()
        size_label = f"Size ({unit})" if unit in _SIZE_DIV else "Size"
        order = [("name", "Name"), ("size", size_label), ("modified", "Modified"),
                 ("type", "Type"), ("attr", "Attr"), ("path", "Full path"),
                 ("version", "Version")]
        idx = {"name": 0, "size": 1, "modified": 2, "type": 3, "attr": 4,
               "path": 5, "version": 6}
        return [(idx[k], label) for k, label in order if self.var_cols[k].get()]

    def _table(self):
        """(header, data) for whichever mode is on — the single source that
        the text, CSV, HTML and PDF writers all read, so a new mode never has
        to be added to four renderers."""
        if self.var_include.get() == "tree":
            rows = self._gather_tree()
            self._last_row_count = len(rows)
            want_v = self.var_cols["version"].get()
            header = ["Folder", "Files"] + (["Version"] if want_v else [])
            data = [[r[0], r[1]] + ([r[2]] if want_v else []) for r in rows]
            return header, data
        rows = self._gather()
        # Remembered so the status line can report the real number of items
        # instead of counting newlines in the finished text.
        self._last_row_count = len(rows)
        cols = self._active_columns()
        if not cols:
            return [], []
        return ([label for _i, label in cols],
                [[r[i] for i, _lbl in cols] for r in rows])

    # ── Rendering ─────────────────────────────────────────────────────────

    def _summary(self, count: str) -> str:
        """"120 files · 3.4 GB" — the line File-sizes existed to produce."""
        out = count
        if self._last_total_bytes:
            auto = _human_size(self._last_total_bytes)
            out += f" · {auto}"
            unit = self.var_unit.get()
            # Only worth repeating when the chosen unit is not the one the
            # readable form already landed on — "4.0 MB (4.00 MB)" is noise.
            if unit in _SIZE_DIV and not auto.endswith(f" {unit}"):
                out += f" ({_size_in_unit(self._last_total_bytes, unit)} {unit})"
        return out

    def _render_tree_text(self, title: str, stamp: str) -> str:
        """The compact tree as plain text — folder, its files, its version."""
        rows = self._gather_tree()
        self._last_row_count = len(rows)
        want_v = self.var_cols["version"].get()
        lines = [title,
                 self._summary(f"{len(rows)} folder(s)") + f" · generated {stamp}",
                 ""]
        for folder, files, token in rows:
            line = folder
            if files:
                line += "    " + files
            if want_v and token:
                line += f"    [{token}]"
            lines.append(line)
        return "\n".join(lines)

    def _render(self, fmt: str) -> str:
        title = f"Folder listing — {self.folder}"
        stamp = f"{datetime.now():%Y-%m-%d %H:%M}"
        if self.var_include.get() == "tree" and fmt == "txt":
            return self._render_tree_text(title, stamp)
        header, data = self._table()
        if not header:
            return "(choose at least one column)"

        if fmt == "csv":
            def esc(v):
                v = str(v)
                return f'"{v}"' if any(c in v for c in ',";\n') else v
            lines = [";".join(esc(h) for h in header)]
            lines += [";".join(esc(c) for c in row) for row in data]
            return "\n".join(lines)

        if fmt == "html":
            def esc(v):
                return (str(v).replace("&", "&amp;").replace("<", "&lt;")
                        .replace(">", "&gt;"))
            out = [
                "<!DOCTYPE html><html><head><meta charset='utf-8'>",
                f"<title>{esc(title)}</title>",
                "<style>",
                "body{font-family:Segoe UI,Arial,sans-serif;margin:24px;color:#222}",
                "h1{font-size:18px}",
                "p.meta{color:#666;font-size:12px}",
                "table{border-collapse:collapse;width:100%;font-size:13px}",
                "th{background:#33405c;color:#fff;text-align:left;padding:6px 8px}",
                "td{border-bottom:1px solid #ddd;padding:5px 8px}",
                "tr:nth-child(even) td{background:#f6f7f9}",
                "</style></head><body>",
                f"<h1>{esc(title)}</h1>",
                f"<p class='meta'>{esc(self._summary(f'{len(data)} items'))} "
                f"&middot; generated {stamp}</p>",
                "<table><tr>" + "".join(f"<th>{esc(h)}</th>" for h in header) + "</tr>",
            ]
            for row in data:
                out.append("<tr>" + "".join(f"<td>{esc(c)}</td>" for c in row) + "</tr>")
            out.append("</table></body></html>")
            return "\n".join(out)

        # Plain text — fixed-width columns
        widths = [max(len(str(header[i])),
                      max((len(str(r[i])) for r in data), default=0))
                  for i in range(len(header))]
        widths = [min(w, 70) for w in widths]

        def fmt_row(vals):
            return "  ".join(str(v)[:w].ljust(w) for v, w in zip(vals, widths))

        lines = [title,
                 self._summary(f"{len(data)} items") + f" · generated {stamp}",
                 "", fmt_row(header), "  ".join("-" * w for w in widths)]
        lines += [fmt_row(r) for r in data]
        return "\n".join(lines)

    def _on_include(self):
        """Set the compact tree up the first time it is picked.

        A tree of one folder is not a tree, so choosing it turns subfolders
        on, and bounds the walk at three levels — where Dir_lister always
        started — rather than launching an unlimited walk of a whole drive on
        a click.  Type 0 in the levels box to go all the way down.
        """
        if self.var_include.get() == "tree" and not self.var_recursive.get():
            self.var_recursive.set(True)
            if not self._depth():
                self.var_depth.set("3")
        self._preview()

    def _preview(self):
        self._sync_enabled()
        fmt = self.var_format.get()
        self._full_text = self._render("txt" if fmt == "pdf" else fmt)
        self._apply_find()
        self._save_prefs()

    def _sync_enabled(self):
        """Grey out what the current mode does not use.

        The depth box only means something while subfolders are included, and
        the compact tree writes its own columns, so leaving those controls
        live would just be three ways of being ignored.
        """
        tree = self.var_include.get() == "tree"
        deep = "normal" if self.var_recursive.get() else "disabled"
        for w in (self._lbl_depth, self._e_depth):
            try:
                w.configure(state=deep)
            except Exception:
                pass
        for key, cb in self._col_boxes.items():
            try:
                cb.configure(state="disabled" if (tree and key != "version")
                             else "normal")
            except Exception:
                pass
        try:
            self._cb_selected.configure(state="disabled" if tree else "normal")
        except Exception:
            pass
        # The unit only shows up in a Size column, and the tree has none.
        try:
            self._unit_menu.configure(
                state="normal" if (not tree and self.var_cols["size"].get())
                else "disabled")
        except Exception:
            pass

    def _clear_find(self):
        self.var_find.set("")
        self._apply_find()

    def _apply_find(self):
        """Show the whole render, or only the lines that contain the word.

        The full text is kept in _full_text, so Save and Print always write
        the complete listing however narrow the preview happens to be — only
        📋 Copy deliberately follows what is on screen.
        """
        needle = self.var_find.get().strip().lower()
        text = self._full_text
        shown = None
        if needle:
            all_lines = text.splitlines()
            hits = [ln for ln in all_lines if needle in ln.lower()]
            shown = (len(hits), len(all_lines))
            text = "\n".join(hits) if hits else f"(no line contains '{needle}')"
        self.preview.configure(state="normal")
        self.preview.delete("1.0", "end")
        self.preview.insert("1.0", text)
        self.preview.configure(state="disabled")
        what = {"both": "files and folders",
                "files": "files only",
                "dirs": "folders only",
                "tree": "compact tree"}[self.var_include.get()]
        msg = (self._summary(f"{getattr(self, '_last_row_count', 0)} row(s)")
               + f"   ·   {what}")
        if self._patterns():
            msg += f"   ·   filter {self.var_filter.get().strip()}"
        if self.var_recursive.get() and self._depth():
            msg += f"   ·   {self._depth()} level(s)"
        if shown:
            msg += f"   ·   showing {shown[0]} of {shown[1]} lines"
        self._status.configure(text=msg, fg=C_FG_DIM)

    def _save_prefs(self):
        """Keep this window's choices for next time (written to disk with the
        rest of the settings when the program closes)."""
        try:
            self.manager.settings["print_listing"] = {
                "recursive":     bool(self.var_recursive.get()),
                "selected_only": bool(self.var_selected_only.get()),
                "include":       self.var_include.get(),
                "depth":         self._depth(),
                "filter":        self.var_filter.get().strip(),
                "size_unit":     self.var_unit.get(),
                "clear_marks":   bool(self.var_clear_marks.get()),
                "format":        self.var_format.get(),
                "columns":       {k: bool(v.get()) for k, v in self.var_cols.items()},
            }
        except Exception:
            pass

    # ── After a finished job ──────────────────────────────────────────────

    def _finish_ok(self, what: str):
        """A print or an export went through.

        The marked files have done their job, so the red marks come off in the
        panel — otherwise the next operation silently inherits a selection you
        have already dealt with.  Switch it off with the checkbox at the top if
        you want to export the same selection several times in a row.
        """
        if not self.var_clear_marks.get():
            return
        try:
            panel = self.manager.get_active_panel()
            had = len(getattr(panel, "_marked", ()) or ())
            if had and hasattr(panel, "_clear_marks_and_selection"):
                panel._clear_marks_and_selection()
                self._status.configure(
                    text=f"{what} — {had} mark(s) cleared in the panel.",
                    fg=C_ACCENT)
        except Exception as exc:
            _log(f"Print listing: could not clear the marks: {exc}")

    def _copy(self):
        self.clipboard_clear()
        self.clipboard_append(self.preview.get("1.0", "end-1c"))
        _flash_ok(self, "Listing copied to clipboard.", "Copied")
        self._finish_ok("Copied to the clipboard")

    def _save(self):
        fmt = self.var_format.get()
        ext = {"txt": ".txt", "csv": ".csv", "html": ".html", "pdf": ".pdf"}[fmt]
        default = (os.path.basename(self.folder.rstrip("\\/")) or "listing") + ext
        path = filedialog.asksaveasfilename(
            parent=self, title="Save listing", initialdir=self.folder,
            initialfile=default, defaultextension=ext,
            filetypes=[(fmt.upper(), f"*{ext}"), ("All files", "*.*")])
        if not path:
            return
        try:
            if fmt == "pdf":
                self._save_pdf(path)
            else:
                with open(path, "w", encoding="utf-8") as fh:
                    fh.write(self._render(fmt))
            self.manager.refresh_panels()
            _flash_ok(self, f"Saved to\n{os.path.basename(path)}", "Saved")
            self._finish_ok(f"Saved {os.path.basename(path)}")
        except Exception as exc:
            messagebox.showerror("Save", f"Could not save:\n{exc}", parent=self)

    def _save_pdf(self, path: str):
        """Write the listing as a real PDF (reportlab, else PyMuPDF)."""
        header, raw = self._table()
        data = [[str(c) for c in row] for row in raw]
        rows = data
        title = f"Folder listing — {self.folder}"

        try:
            from reportlab.lib.pagesizes import A4, landscape
            from reportlab.lib.units import mm
            from reportlab.lib import colors
            from reportlab.platypus import (SimpleDocTemplate, Table, TableStyle,
                                            Paragraph, Spacer)
            from reportlab.lib.styles import getSampleStyleSheet

            styles = getSampleStyleSheet()
            doc = SimpleDocTemplate(path, pagesize=landscape(A4),
                                    leftMargin=12 * mm, rightMargin=12 * mm,
                                    topMargin=12 * mm, bottomMargin=12 * mm,
                                    title=title)
            story = [Paragraph(title.replace("&", "&amp;").replace("<", "&lt;"),
                               styles["Heading2"]),
                     Paragraph(f"{len(rows)} items · generated "
                               f"{datetime.now():%Y-%m-%d %H:%M}", styles["Normal"]),
                     Spacer(1, 6 * mm)]

            # Truncate long cells so the table still fits the page
            def clip(v, n=64):
                return v if len(v) <= n else v[:n - 1] + "…"
            table_data = [header] + [[clip(c) for c in row] for row in data]
            tbl = Table(table_data, repeatRows=1)
            tbl.setStyle(TableStyle([
                ("BACKGROUND", (0, 0), (-1, 0), colors.HexColor("#33405c")),
                ("TEXTCOLOR",  (0, 0), (-1, 0), colors.white),
                ("FONTNAME",   (0, 0), (-1, 0), "Helvetica-Bold"),
                ("FONTSIZE",   (0, 0), (-1, -1), 7),
                ("VALIGN",     (0, 0), (-1, -1), "MIDDLE"),
                ("ROWBACKGROUNDS", (0, 1), (-1, -1),
                 [colors.white, colors.HexColor("#f2f4f7")]),
                ("GRID", (0, 0), (-1, -1), 0.25, colors.HexColor("#cccccc")),
                ("LEFTPADDING", (0, 0), (-1, -1), 4),
                ("RIGHTPADDING", (0, 0), (-1, -1), 4),
            ]))
            story.append(tbl)
            doc.build(story)
            return
        except ImportError:
            pass

        # Fallback: render the plain-text listing into a PDF via PyMuPDF
        try:
            import fitz
            text = self._render("txt")
            doc = fitz.open()
            font_size, margin, leading = 8, 36, 10
            page = doc.new_page()
            y = margin
            for line in text.splitlines():
                if y > page.rect.height - margin:
                    page = doc.new_page()
                    y = margin
                page.insert_text((margin, y), line[:150], fontsize=font_size,
                                 fontname="cour")
                y += leading
            doc.save(path)
            doc.close()
        except ImportError:
            raise RuntimeError(
                "PDF export needs reportlab or PyMuPDF:\n"
                "  pip install reportlab\n"
                "  pip install pymupdf")

    def _print(self):
        """Send the listing to the default printer via the OS."""
        fmt = self.var_format.get()
        ext = {"txt": ".txt", "csv": ".csv", "html": ".html", "pdf": ".pdf"}[fmt]
        tmp = LOG_DIR / f"listing_print_{os.getpid()}{ext}"
        try:
            if fmt == "pdf":
                self._save_pdf(str(tmp))
            else:
                with open(tmp, "w", encoding="utf-8") as fh:
                    fh.write(self._render(fmt))
        except Exception as exc:
            messagebox.showerror("Print", f"Could not prepare the document:\n{exc}",
                                 parent=self)
            return

        try:
            if platform.system() == "Windows":
                # "print" verb — Windows hands it to the registered application
                os.startfile(str(tmp), "print")
                _flash_ok(self, "Sent to the default printer.", "Printing", ms=1200)
                self._finish_ok("Sent to the printer")
            else:
                subprocess.Popen(["lp", str(tmp)])
                self._finish_ok("Sent to the printer")
        except Exception as exc:
            # Not every file type has a print verb registered — open it instead
            try:
                os.startfile(str(tmp))
                messagebox.showinfo(
                    "Print",
                    "No print handler is registered for this format, so the "
                    "document was opened instead.\nUse the application's own "
                    "Print command (Ctrl+P).", parent=self)
            except Exception:
                messagebox.showerror("Print", f"Could not print:\n{exc}", parent=self)


# ══════════════════════════════════════════════════════════════════════════
#  DEL 31 — Command bar + command library
# ══════════════════════════════════════════════════════════════════════════
#
# The command bar sits under the panels: type a command, press Enter, and it
# runs in the active panel's folder with the output shown inline.  The command
# library stores commands you use often, each with the shell it belongs in,
# and can run several of them in sequence.

SHELLS = {
    "cmd":        "Command Prompt",
    "powershell": "PowerShell",
}

# Placeholders expanded in saved commands before they run
COMMAND_PLACEHOLDERS = """\
  %P   Active panel folder            %p   Other panel folder
  %N   Selected file name             %F   Selected file, full path
  %M   All selected names (quoted)    %L   All selected full paths (quoted)
  %E   Selected file extension        %B   Selected name without extension
"""


def _shell_command(shell: str, command: str, cwd: str, keep_open: bool = False):
    """Build the argument list that runs `command` in the chosen shell."""
    if shell == "powershell":
        exe = shutil.which("pwsh") or shutil.which("powershell") or "powershell"
        if keep_open:
            return [exe, "-NoExit", "-Command", command]
        return [exe, "-NoProfile", "-Command", command]
    # cmd.exe
    # COMSPEC, never the bare name - see the ShellExecuteW above.
    return [os.environ.get("COMSPEC", r"C:\Windows\System32\cmd.exe"),
            "/K" if keep_open else "/C", command]


def expand_command(command: str, manager: "EditorFrame") -> str:
    """Replace the %-placeholders with the current selection / folders."""
    panel = manager.get_active_panel()
    other = manager.get_inactive_panel()
    cur_dir = getattr(panel, "current_path", "")
    other_dir = getattr(other, "current_path", "")
    try:
        selected = panel.get_all_selected()
    except Exception:
        selected = []
    first = selected[0] if selected else ""
    name = os.path.basename(first) if first else ""
    stem, ext = os.path.splitext(name)

    def quoted(paths, basenames=False):
        return " ".join(f'"{os.path.basename(p) if basenames else p}"'
                        for p in paths)

    out = command
    for token, value in (("%P", cur_dir), ("%p", other_dir),
                         ("%F", first), ("%N", name),
                         ("%B", stem), ("%E", ext.lstrip(".")),
                         ("%M", quoted(selected, basenames=True)),
                         ("%L", quoted(selected))):
        out = out.replace(token, value)
    return out


class CommandBar(tk.Frame):
    """Inline command line with history, shell choice and captured output."""

    HISTORY_MAX = 200

    def __init__(self, parent, manager: "EditorFrame"):
        super().__init__(parent, bg=C_BG3)
        self.manager = manager
        self.visible = False
        self.history: list = manager.settings.get("cmd_history", [])[-self.HISTORY_MAX:]
        self._hist_idx = len(self.history)
        self._proc = None

        self.var_shell = tk.StringVar(value=manager.settings.get("cmdbar_shell", "cmd"))
        self.var_cmd   = tk.StringVar()

        row = tk.Frame(self, bg=C_BG3)
        row.pack(fill="x")

        self._prompt = tk.Label(row, text="", bg=C_BG3, fg=C_ACCENT,
                                font=("Consolas", 9), anchor="w")
        self._prompt.pack(side="left", padx=(6, 4), pady=3)

        shell_cb = ttk.Combobox(row, textvariable=self.var_shell, width=11,
                                state="readonly", values=list(SHELLS.keys()))
        shell_cb.pack(side="left", padx=(0, 4))
        shell_cb.bind("<<ComboboxSelected>>",
                      lambda e: manager.settings.__setitem__("cmdbar_shell",
                                                             self.var_shell.get()))

        self.entry = tk.Entry(row, textvariable=self.var_cmd, bg=C_BG2, fg=C_FG,
                              insertbackground=C_FG, font=("Consolas", 10),
                              insertofftime=0, insertontime=9999999)
        self.entry.pack(side="left", fill="x", expand=True)
        self.entry.bind("<Return>",   lambda e: self.run())
        self.entry.bind("<Up>",       lambda e: self._history(-1))
        self.entry.bind("<Down>",     lambda e: self._history(1))
        self.entry.bind("<Escape>",   lambda e: self.hide())
        self.entry.bind("<Control-l>", lambda e: self._clear_output())

        tk.Button(row, text="▶ Run", bg="lightgreen", fg="black",
                  font=("Segoe UI", 8), command=self.run).pack(side="left", padx=2)
        tk.Button(row, text="📚 Library", bg="white", fg="black",
                  font=("Segoe UI", 8),
                  command=self.manager.open_command_library).pack(side="left", padx=2)
        tk.Button(row, text="🗔 New window", bg="white", fg="black",
                  font=("Segoe UI", 8),
                  command=lambda: self.run(external=True)).pack(side="left", padx=2)
        tk.Button(row, text="✕", bg=C_BG3, fg=C_FG, relief="flat",
                  command=self.hide).pack(side="right", padx=4)

        # Output area (hidden until something is run)
        self._out_frame = tk.Frame(self, bg=C_BG2)
        self.output = tk.Text(self._out_frame, height=10, wrap="none", bg="#12121c",
                              fg="#d0d0e0", font=("Consolas", 9), padx=6, pady=4,
                              insertofftime=0, insertontime=9999999)
        vsb = ttk.Scrollbar(self._out_frame, orient="vertical", command=self.output.yview)
        hsb = ttk.Scrollbar(self._out_frame, orient="horizontal", command=self.output.xview)
        self.output.configure(yscrollcommand=vsb.set, xscrollcommand=hsb.set,
                              state="disabled")
        vsb.pack(side="right", fill="y")
        hsb.pack(side="bottom", fill="x")
        self.output.pack(side="left", fill="both", expand=True)
        self.output.tag_configure("cmd",  foreground=C_ACCENT)
        self.output.tag_configure("err",  foreground="#ff8080")
        self.output.tag_configure("note", foreground="#8888aa")

    # ── Show / hide ───────────────────────────────────────────────────────

    def show(self):
        if not self.visible:
            # Sit directly above the status bar when one already exists
            statusbar = getattr(self.manager, "statusbar", None)
            if statusbar is not None and statusbar.winfo_manager() == "pack":
                self.pack(fill="x", before=statusbar)
            else:
                self.pack(fill="x", side="bottom")
            self.visible = True
            self.manager.settings["cmdbar_open"] = True
        self.update_prompt()
        self.entry.focus_set()

    def hide(self):
        if self.visible:
            self.pack_forget()
            self.visible = False
            self.manager.settings["cmdbar_open"] = False
            try:
                self.manager.get_active_panel().focus_set()
            except Exception:
                pass

    def toggle(self):
        self.hide() if self.visible else self.show()

    def update_prompt(self):
        try:
            path = self.manager.get_active_panel().current_path
        except Exception:
            path = ""
        if len(path) > 44:
            path = "…" + path[-43:]
        self._prompt.configure(text=f"{path}>")

    # ── History ───────────────────────────────────────────────────────────

    def _history(self, delta: int):
        if not self.history:
            return "break"
        self._hist_idx = max(0, min(len(self.history), self._hist_idx + delta))
        self.var_cmd.set(self.history[self._hist_idx]
                         if self._hist_idx < len(self.history) else "")
        self.entry.icursor("end")
        return "break"

    def _remember(self, command: str):
        if command and (not self.history or self.history[-1] != command):
            self.history.append(command)
            del self.history[:-self.HISTORY_MAX]
        self._hist_idx = len(self.history)
        self.manager.settings["cmd_history"] = self.history

    # ── Running ───────────────────────────────────────────────────────────

    def _clear_output(self):
        self.output.configure(state="normal")
        self.output.delete("1.0", "end")
        self.output.configure(state="disabled")
        return "break"

    def _append(self, text: str, tag: str = None):
        self.output.configure(state="normal")
        self.output.insert("end", text, (tag,) if tag else ())
        self.output.see("end")
        self.output.configure(state="disabled")

    def run(self, external: bool = False):
        command = self.var_cmd.get().strip()
        if not command:
            return "break"
        cwd = self.manager.get_active_panel().current_path
        if not os.path.isdir(cwd):
            cwd = str(APP_ROOT)
        shell = self.var_shell.get()
        self._remember(command)
        self.var_cmd.set("")

        # Built-in shortcuts that make more sense inside the file manager
        low = command.lower()
        if low in ("cls", "clear"):
            return self._clear_output()
        if low.startswith("cd "):
            target = command[3:].strip().strip('"')
            new = os.path.abspath(os.path.join(cwd, os.path.expandvars(target)))
            if os.path.isdir(new):
                self.manager.get_active_panel().change_directory(new)
                self.update_prompt()
            else:
                self._show_output()
                self._append(f"The folder does not exist: {new}\n", "err")
            return "break"

        if external:
            try:
                subprocess.Popen(_shell_command(shell, command, cwd, keep_open=True),
                                 cwd=cwd)
            except Exception as exc:
                messagebox.showerror("Command", f"Could not start the shell:\n{exc}")
            return "break"

        self._show_output()
        self._append(f"\n{cwd}> {command}\n", "cmd")
        run_command_async(
            shell, command, cwd,
            on_output=lambda line: self._append(line),
            on_done=self._on_done)
        return "break"

    def _show_output(self):
        if not self._out_frame.winfo_ismapped():
            self._out_frame.pack(fill="both", expand=True)

    def _on_done(self, code: int):
        tag = "note" if code == 0 else "err"
        self._append(f"[exit code {code}]\n", tag)
        self.manager.refresh_panels()


def run_command_async(shell: str, command: str, cwd: str,
                      on_output=None, on_done=None, timeout: int = 600):
    """Run a shell command on a background thread, streaming its output."""
    def worker():
        code = -1
        try:
            proc = subprocess.Popen(
                _shell_command(shell, command, cwd),
                cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT,
                stdin=subprocess.DEVNULL, text=True, errors="replace",
                bufsize=1, **_no_window_kwargs())
            start = _time.time()
            for line in proc.stdout:
                if on_output:
                    on_output(line)
                if _time.time() - start > timeout:
                    proc.kill()
                    if on_output:
                        on_output(f"\n[timed out after {timeout} s — killed]\n")
                    break
            proc.wait(timeout=10)
            code = proc.returncode
        except Exception as exc:
            if on_output:
                on_output(f"[could not run: {exc}]\n")
        finally:
            if on_done:
                on_done(code)

    threading.Thread(target=worker, daemon=True).start()


class CommandLibraryWindow(tk.Toplevel):
    """Saved commands: each has a name, a shell, and can run in sequence."""

    def __init__(self, manager: "EditorFrame"):
        super().__init__(manager)
        self.manager = manager
        self.configure(bg=C_BG)
        self.geometry("980x660")
        _setup_toplevel(self, "Command library", manager, modal=False)

        head = tk.Frame(self, bg=C_BG3)
        head.pack(fill="x")
        tk.Label(head, text="📚  Command library", bg=C_BG3, fg=C_ACCENT,
                 font=("Segoe UI", 12, "bold")).pack(side="left", padx=10, pady=7)
        tk.Label(head,
                 text="Tick several commands and press “Run checked in sequence”",
                 bg=C_BG3, fg=C_FG_DIM, font=("Segoe UI", 9)).pack(side="left")

        mid = tk.Frame(self, bg=C_BG)
        mid.pack(fill="both", expand=True, padx=10, pady=(8, 4))
        self.tree = ttk.Treeview(mid, columns=("shell", "command"),
                                 selectmode="browse", height=12)
        self.tree.heading("#0",      text="✓  Name", anchor="w")
        self.tree.heading("shell",   text="Shell",   anchor="w")
        self.tree.heading("command", text="Command", anchor="w")
        self.tree.column("#0", width=240)
        self.tree.column("shell", width=100)
        self.tree.column("command", width=560, stretch=True)
        sb = ttk.Scrollbar(mid, orient="vertical", command=self.tree.yview)
        self.tree.configure(yscrollcommand=sb.set)
        self.tree.pack(side="left", fill="both", expand=True)
        sb.pack(side="right", fill="y")
        self.tree.bind("<space>",    self._toggle)
        self.tree.bind("<Double-1>", lambda e: self._run_selected())

        btns = tk.Frame(self, bg=C_BG)
        btns.pack(fill="x", padx=10)
        tk.Button(btns, text="＋  New", bg="lightgreen", fg="black",
                  command=self._new).pack(side="left", padx=2)
        tk.Button(btns, text="Edit", bg="white", fg="black",
                  command=self._edit).pack(side="left", padx=2)
        tk.Button(btns, text="Duplicate", bg="white", fg="black",
                  command=self._duplicate).pack(side="left", padx=2)
        tk.Button(btns, text="↑", width=3, bg="white", fg="black",
                  command=lambda: self._move(-1)).pack(side="left", padx=2)
        tk.Button(btns, text="↓", width=3, bg="white", fg="black",
                  command=lambda: self._move(1)).pack(side="left", padx=2)
        tk.Button(btns, text="🗑  Delete", bg="#ff8888", fg="black",
                  command=self._delete).pack(side="left", padx=2)
        tk.Button(btns, text="?  Placeholders", bg="white", fg="black",
                  command=self._show_placeholders).pack(side="left", padx=(14, 2))

        out_lbl = tk.Frame(self, bg=C_BG)
        out_lbl.pack(fill="x", padx=10, pady=(8, 0))
        tk.Label(out_lbl, text="Output:", bg=C_BG, fg=C_FG_DIM,
                 anchor="w").pack(side="left")
        tk.Button(out_lbl, text="Clear", bg="white", fg="black",
                  font=("Segoe UI", 8), command=self._clear).pack(side="right")

        of = tk.Frame(self, bg=C_BG)
        of.pack(fill="both", expand=True, padx=10, pady=(2, 4))
        self.output = tk.Text(of, height=10, wrap="none", bg="#12121c", fg="#d0d0e0",
                              font=("Consolas", 9), padx=6, pady=4,
                              insertofftime=0, insertontime=9999999)
        vsb = ttk.Scrollbar(of, orient="vertical", command=self.output.yview)
        self.output.configure(yscrollcommand=vsb.set, state="disabled")
        vsb.pack(side="right", fill="y")
        self.output.pack(side="left", fill="both", expand=True)
        self.output.tag_configure("cmd", foreground=C_ACCENT)
        self.output.tag_configure("err", foreground="#ff8080")
        self.output.tag_configure("note", foreground="#8888aa")

        bot = tk.Frame(self, bg=C_BG)
        bot.pack(fill="x", padx=10, pady=(0, 10))
        self._status = tk.Label(bot, text="", bg=C_BG, fg=C_FG_DIM, anchor="w")
        self._status.pack(side="left", fill="x", expand=True)
        tk.Button(bot, text="Close", bg="grey", fg="white", width=9,
                  command=self.destroy).pack(side="right", padx=3)
        tk.Button(bot, text="▶▶  Run checked in sequence", bg="lightgreen",
                  fg="black", command=self._run_sequence).pack(side="right", padx=3)
        tk.Button(bot, text="▶  Run selected", bg="lightblue", fg="black",
                  command=self._run_selected).pack(side="right", padx=3)

        self._seed_defaults()
        self._render()
        self.bind("<Return>", lambda e: self._run_selected())

    def _seed_defaults(self):
        """First run: give the library a few genuinely useful examples."""
        if self.manager.command_lib:
            return
        self.manager.command_lib = [
            {"name": "Directory tree", "shell": "cmd",
             "command": "tree \"%P\" /F", "checked": False},
            {"name": "Folder size", "shell": "powershell",
             "command": "Get-ChildItem -LiteralPath '%P' -Recurse -File | "
                        "Measure-Object -Property Length -Sum | "
                        "Select-Object Count, @{n='SizeMB';e={[math]::Round($_.Sum/1MB,2)}}",
             "checked": False},
            {"name": "Ping gateway", "shell": "cmd",
             "command": "ping -n 4 8.8.8.8", "checked": False},
            {"name": "Open folder in Explorer", "shell": "cmd",
             "command": "explorer \"%P\"", "checked": False},
            {"name": "Git status", "shell": "cmd",
             "command": "git -C \"%P\" status", "checked": False},
            {"name": "List largest files", "shell": "powershell",
             "command": "Get-ChildItem -LiteralPath '%P' -Recurse -File | "
                        "Sort-Object Length -Descending | Select-Object -First 20 "
                        "Name, @{n='MB';e={[math]::Round($_.Length/1MB,2)}}, FullName",
             "checked": False},
        ]
        self.manager.save_command_lib()

    def _render(self):
        self.tree.delete(*self.tree.get_children())
        for i, cmd in enumerate(self.manager.command_lib):
            mark = "☑" if cmd.get("checked") else "☐"
            self.tree.insert("", "end", iid=str(i),
                             text=f"{mark}  {cmd.get('name', '')}",
                             values=(SHELLS.get(cmd.get("shell", "cmd"), "cmd"),
                                     cmd.get("command", "")))
        n = sum(1 for c in self.manager.command_lib if c.get("checked"))
        self._status.configure(
            text=f"{len(self.manager.command_lib)} command(s) · {n} checked")

    def _selected(self):
        sel = self.tree.selection()
        return int(sel[0]) if sel else None

    def _toggle(self, event=None):
        i = self._selected()
        if i is None:
            return "break"
        lib = self.manager.command_lib
        lib[i]["checked"] = not lib[i].get("checked")
        self.manager.save_command_lib()
        self._render()
        self.tree.selection_set(str(i))
        return "break"

    def _show_placeholders(self):
        messagebox.showinfo(
            "Placeholders",
            "These are replaced before the command runs:\n\n"
            + COMMAND_PLACEHOLDERS, parent=self)

    # ── Editing ───────────────────────────────────────────────────────────

    def _edit_dialog(self, initial: dict = None, index: int = None):
        top = tk.Toplevel(self)
        top.configure(bg=C_BG)
        top.resizable(False, False)
        _setup_toplevel(top, "Command", self, modal=True)

        initial = initial or {"name": "", "shell": "cmd", "command": ""}
        v_name  = tk.StringVar(value=initial.get("name", ""))
        v_shell = tk.StringVar(value=initial.get("shell", "cmd"))

        body = tk.Frame(top, bg=C_BG, padx=16, pady=14)
        body.pack(fill="both", expand=True)

        tk.Label(body, text="Name:", bg=C_BG, fg=C_FG, anchor="w").pack(fill="x")
        e_name = tk.Entry(body, textvariable=v_name, width=58, bg=C_BG2, fg=C_FG,
                          insertbackground=C_FG,
                          insertofftime=0, insertontime=9999999)
        e_name.pack(fill="x", pady=(0, 8))

        tk.Label(body, text="Shell:", bg=C_BG, fg=C_FG, anchor="w").pack(fill="x")
        ttk.Combobox(body, textvariable=v_shell, width=16, state="readonly",
                     values=list(SHELLS.keys())).pack(anchor="w", pady=(0, 8))

        tk.Label(body, text="Command:", bg=C_BG, fg=C_FG, anchor="w").pack(fill="x")
        txt = tk.Text(body, width=58, height=6, bg=C_BG2, fg=C_FG,
                      insertbackground=C_FG, font=("Consolas", 9),
                      insertofftime=0, insertontime=9999999)
        txt.pack(fill="both", expand=True, pady=(0, 4))
        txt.insert("1.0", initial.get("command", ""))

        tk.Label(body, text=COMMAND_PLACEHOLDERS, bg=C_BG, fg=C_FG_DIM,
                 font=("Consolas", 8), justify="left",
                 anchor="w").pack(fill="x", pady=(2, 10))

        def save(event=None):
            name = v_name.get().strip()
            command = txt.get("1.0", "end-1c").strip()
            if not name or not command:
                messagebox.showerror("Command", "Name and command are both required.",
                                     parent=top)
                return
            entry = {"name": name, "shell": v_shell.get(), "command": command,
                     "checked": initial.get("checked", False)}
            if index is None:
                self.manager.command_lib.append(entry)
            else:
                self.manager.command_lib[index] = entry
            self.manager.save_command_lib()
            self._render()
            top.destroy()

        btns = tk.Frame(body, bg=C_BG)
        btns.pack(fill="x")
        tk.Button(btns, text="Cancel", bg="grey", fg="white", width=10,
                  command=top.destroy).pack(side="right", padx=3)
        tk.Button(btns, text="Save", bg="lightgreen", fg="black", width=10,
                  command=save).pack(side="right", padx=3)
        # ENTER saves from the name field; Ctrl+Enter saves from the command box
        e_name.bind("<Return>", save)
        txt.bind("<Control-Return>", save)
        e_name.focus_set()

    def _new(self):
        self._edit_dialog()

    def _edit(self):
        i = self._selected()
        if i is not None:
            self._edit_dialog(dict(self.manager.command_lib[i]), i)

    def _duplicate(self):
        i = self._selected()
        if i is None:
            return
        copy = dict(self.manager.command_lib[i])
        copy["name"] += " (copy)"
        self.manager.command_lib.insert(i + 1, copy)
        self.manager.save_command_lib()
        self._render()

    def _move(self, delta: int):
        i = self._selected()
        if i is None:
            return
        j = i + delta
        lib = self.manager.command_lib
        if 0 <= j < len(lib):
            lib[i], lib[j] = lib[j], lib[i]
            self.manager.save_command_lib()
            self._render()
            self.tree.selection_set(str(j))

    def _delete(self):
        i = self._selected()
        if i is None:
            return
        name = self.manager.command_lib[i].get("name", "")
        if _ask_yes_no("Delete", f"Delete the command “{name}”?", parent=self):
            del self.manager.command_lib[i]
            self.manager.save_command_lib()
            self._render()

    # ── Running ───────────────────────────────────────────────────────────

    def _clear(self):
        self.output.configure(state="normal")
        self.output.delete("1.0", "end")
        self.output.configure(state="disabled")

    def _append(self, text: str, tag: str = None):
        self.output.configure(state="normal")
        self.output.insert("end", text, (tag,) if tag else ())
        self.output.see("end")
        self.output.configure(state="disabled")

    def _run_selected(self):
        i = self._selected()
        if i is None:
            return
        self._run_list([self.manager.command_lib[i]])

    def _run_sequence(self):
        chosen = [c for c in self.manager.command_lib if c.get("checked")]
        if not chosen:
            messagebox.showinfo(
                "Run sequence",
                "Tick the commands you want to run (select a row and press Space).",
                parent=self)
            return
        if not _ask_yes_no(
                "Run sequence",
                f"Run these {len(chosen)} command(s) one after the other?\n\n"
                + "\n".join(f"  {i}. {c['name']}" for i, c in enumerate(chosen, 1)),
                parent=self):
            return
        self._run_list(chosen)

    def _run_list(self, commands: list):
        """Run commands strictly one after the other, streaming to the output."""
        cwd = self.manager.get_active_panel().current_path
        if not os.path.isdir(cwd):
            cwd = str(APP_ROOT)
        queue_ = list(commands)

        def run_next(index: int = 0):
            if index >= len(queue_):
                self._append(f"\n─── Finished {len(queue_)} command(s) ───\n", "note")
                self.manager.refresh_panels()
                return
            entry = queue_[index]
            expanded = expand_command(entry.get("command", ""), self.manager)
            self._append(f"\n[{index + 1}/{len(queue_)}]  {entry.get('name', '')}"
                         f"   ({SHELLS.get(entry.get('shell', 'cmd'))})\n", "cmd")
            self._append(f"{cwd}> {expanded}\n", "cmd")

            def done(code):
                self._append(f"[exit code {code}]\n",
                             "note" if code == 0 else "err")
                # Chain on the UI thread so the next command starts cleanly
                self.after(10, lambda: run_next(index + 1))

            run_command_async(entry.get("shell", "cmd"), expanded, cwd,
                              on_output=lambda line: self.after(
                                  0, lambda l=line: self._append(l)),
                              on_done=lambda code: self.after(
                                  0, lambda c=code: done(c)))

        run_next()


# ══════════════════════════════════════════════════════════════════════════
#  DEL 32 — Folder auto-refresh watcher
# ══════════════════════════════════════════════════════════════════════════

class FolderWatcher:
    """Poll the two panel folders and refresh whichever one changed on disk.

    Polling (rather than a native change notification) keeps this dependency
    free and works the same on local disks, network shares and USB drives.
    The signature is cheap: names, sizes and timestamps at one level only.
    """

    def __init__(self, manager: "EditorFrame"):
        self.manager = manager
        self._after_id = None
        self._signatures: dict = {}
        self._running = False
        self._busy = False

    # ── Control ───────────────────────────────────────────────────────────

    def start(self):
        if self._running:
            return
        self._running = True
        self._schedule()

    def stop(self):
        self._running = False
        if self._after_id is not None:
            try:
                self.manager.after_cancel(self._after_id)
            except Exception:
                pass
            self._after_id = None

    def toggle(self) -> bool:
        if self._running:
            self.stop()
        else:
            self.start()
        self.manager.settings["auto_refresh"] = self._running
        return self._running

    @property
    def running(self) -> bool:
        return self._running

    def forget(self, path: str):
        """Drop a cached signature — used after the program's own operations."""
        self._signatures.pop(os.path.normcase(path), None)

    # ── Polling ───────────────────────────────────────────────────────────

    def _schedule(self):
        if not self._running:
            return
        interval = max(500, int(self.manager.settings.get("auto_refresh_ms", 1500)))
        try:
            self._after_id = self.manager.after(interval, self._tick)
        except Exception:
            self._running = False

    def _tick(self):
        if not self._running:
            return
        if self._busy:
            self._schedule()
            return
        panels = []
        for side in ("left", "right"):
            panel = getattr(self.manager, f"{side}_panel", None)
            if panel is None or getattr(panel, "is_remote", False):
                continue
            if getattr(panel, "branch_mode", False):
                continue      # a whole-tree rescan is far too costly to poll
            if getattr(panel, "_rename_entry", None) is not None:
                continue      # never yank the list out from under an edit
            panels.append(panel)

        if not panels:
            self._schedule()
            return

        self._busy = True
        paths = [p.current_path for p in panels]
        threading.Thread(target=self._check, args=(paths,), daemon=True).start()

    def _check(self, paths: list):
        """Compute folder signatures off the UI thread, then hand the result
        back to the main thread to apply changes AND schedule the next poll."""
        changed = []
        for path in paths:
            try:
                sig = self._signature(path)
            except Exception:
                continue
            key = os.path.normcase(path)
            previous = self._signatures.get(key)
            self._signatures[key] = sig
            if previous is not None and previous != sig:
                changed.append(path)
        # Always come back to the main thread — even with no changes — so the
        # poll keeps running.  (Earlier this only rescheduled on the two
        # early-return branches, so after the very first check the watcher went
        # silent and panels only refreshed on manual navigation.)
        try:
            self.manager.after(0, lambda c=changed: self._finish(c))
        except Exception:
            self._busy = False   # window is going away; let it stop

    def _finish(self, changed: list):
        """Runs on the main thread: apply any changes, then re-arm the poll."""
        self._busy = False
        if changed:
            try:
                self.manager._ct("WATCHER-fires",
                                 "folders changed: " + ", ".join(changed))
            except Exception:
                pass
            try:
                self._apply(changed)
            except Exception as exc:
                _log(f"Auto-refresh apply failed: {exc}")
        self._schedule()

    @staticmethod
    def _signature(path: str):
        """A cheap fingerprint of one directory level."""
        try:
            with os.scandir(path) as it:
                items = []
                for entry in it:
                    try:
                        st = entry.stat(follow_symlinks=False)
                        items.append((entry.name, st.st_size, int(st.st_mtime)))
                    except OSError:
                        items.append((entry.name, -1, -1))
            return hash(tuple(sorted(items)))
        except OSError:
            return None

    def _apply(self, changed: list):
        """Refresh the affected panels, preserving cursor and scroll position."""
        for side in ("left", "right"):
            panel = getattr(self.manager, f"{side}_panel", None)
            if panel is None or getattr(panel, "is_remote", False):
                continue
            if panel.current_path not in changed:
                continue
            try:
                # Remember what the cursor was on, so it survives the refresh
                sel = panel.tree.selection()
                keep = panel._fullname(sel[0]) if sel else None
                yview = panel.tree.yview()

                panel.refresh()

                if keep:
                    for iid in panel.tree.get_children():
                        if panel._fullname(iid) == keep:
                            panel.tree.selection_set(iid)
                            panel.tree.focus(iid)
                            break
                panel.tree.yview_moveto(yview[0])
            except Exception as exc:
                _log(f"Auto-refresh failed for {panel.current_path}: {exc}")

        try:
            self.manager._update_disk_info()
        except Exception:
            pass


# ══════════════════════════════════════════════════════════════════════════
#  DEL 33 — Keyboard shortcut configuration
# ══════════════════════════════════════════════════════════════════════════
#
# Every shortcut lives in one table instead of being scattered through the
# code, so the user can rebind any of them.  Overrides are stored in
# Helpfiles/redigerare/keymap.json and merged over the defaults on startup.

# action id → (default key, menu label, EditorFrame method name)
KEY_ACTIONS = [
    # PARENT FOLDER.  revAO2 — there was no key for this AT ALL: the only ways
    # up were the toolbar ↑ and pressing Enter on the ".." row, so going up
    # meant AIMING at one particular row, and every miss ran whatever the
    # cursor happened to be on.  Backspace is the Total Commander key for it;
    # Alt+Up (the Explorer one) is bound as a fixed extra in _bind_keys.
    ("go_up",            "<BackSpace>",       "Go up one directory (parent)", "go_up"),
    ("rename",           "<F2>",              "Rename",                    "_rename_selected"),
    # The extension is the other half of the name and had no key at all — only
    # a slow click on the Type column, which nobody finds by looking (revBM).
    ("rename_ext",       "<Shift-F2>",        "Rename the extension",      "_rename_ext_selected"),
    ("view",             "<F3>",              "View file",                 "view_file"),
    ("edit",             "<F4>",              "Edit file",                 "edit_file"),
    ("edit_secondary",   "<Shift-F4>",        "Edit with 2nd program",     "edit_file_secondary"),
    ("edit_default",     "",                  "Edit with Windows default", "edit_file_default"),
    ("open_with",        "<Control-F4>",      "Open with… (Windows dialog)", "open_with_dialog"),
    ("copy",             "<F5>",              "Copy",                      "copy_files"),
    ("move",             "<F6>",              "Move / rename",             "move_files"),
    ("copy_as",          "<Shift-F5>",        "Copy As…",                  "copy_files_as"),
    ("move_as",          "<Shift-F6>",        "Move As…",                  "move_files_as"),
    ("new_folder",       "<F7>",              "New folder",                "new_folder"),
    # F8 no longer deletes (the Del key already does) — it now cycles through
    # the Left+Right tab pairs.  Delete stays unbound here but Del still works.
    ("pair_cycle",       "<F8>",              "Cycle tab pairs (L+R)",     "_cycle_tab_pairs"),
    ("delete",           "",                  "Delete  (also the Del key)", "delete_files"),
    ("pack",             "<Alt-F5>",          "Pack archive",              "pack_files_as"),
    ("unpack",           "<Alt-F9>",          "Unpack archive",            "unpack_any"),
    ("disk_left",        "<Alt-F1>",          "Drive menu (left panel)",   "_disk_menu_left"),
    ("disk_right",       "<Alt-F2>",          "Drive menu (right panel)",  "_disk_menu_right"),
    ("disk_overview",    "<Alt-F3>",          "Disk overview",             "_show_disk_overview"),
    ("properties",       "<Alt-Return>",      "Properties",                "show_properties"),
    # Deliberately unbound: stamping the date is not something a stray key
    # press may do.  Bind it here yourself if you want one (revBM).
    ("date_now",         "",                  "Set date and time to NOW",  "set_dates_now"),
    ("search",           "<Control-f>",       "Search",                    "open_search"),
    ("new_tab",          "<Control-t>",       "New tab",                   "_add_new_tab"),
    ("close_tab",        "<Control-w>",       "Close tab",                 "_close_current_tab"),
    ("reopen_tab",       "<Control-T>",       "Reopen closed tab",         "_reopen_last_tab"),
    ("refresh",          "<Control-r>",       "Refresh panels",            "refresh_panels"),
    # ── Total Commander parity features ───────────────────────────────
    ("multi_rename",     "<Control-m>",       "Multi-Rename tool",         "open_multi_rename"),
    ("backup_rename",    "<Control-Alt-B>",   "Backup rename",             "backup_rename_selected"),
    ("quick_view",       "<Control-q>",       "Quick View panel",          "toggle_quick_view"),
    ("branch_view",      "<Control-b>",       "Branch view (files)",       "toggle_branch_view"),
    ("branch_view_dirs", "<Control-B>",       "Branch view (with folders)", "toggle_branch_view_dirs"),
    ("hotlist",          "<Control-d>",       "Directory hotlist",         "open_hotlist"),
    ("compare_files",    "<Control-C>",       "Compare files",             "open_compare"),
    ("sync_dirs",        "<Control-S>",       "Synchronize directories",   "open_sync"),
    ("duplicates",       "<Control-D>",       "Find duplicate files",      "open_duplicates"),
    ("checksums",        "<Control-K>",       "Checksums",                 "open_checksums"),
    ("split_file",       "<Control-Alt-s>",   "Split file",                "open_split"),
    ("combine_files",    "<Control-Alt-c>",   "Combine split parts",       "open_combine"),
    ("print_listing",    "<Control-p>",       "Print / export listing",    "open_print_listing"),
    ("command_bar",      "<Control-l>",       "Command bar",               "toggle_command_bar"),
    ("command_library",  "<Control-Alt-l>",   "Command library",           "open_command_library"),
    # Ctrl+PageDown was Browse archive; moved to Ctrl+Alt+PageDown so plain
    # Ctrl+Page is free for the fixed cursor jump.  Still fully re-mappable.
    ("browse_archive",   "<Control-Alt-Next>", "Browse archive",           "open_archive_browser"),
    # Cycle the saved Workspaces (whole profile) — Shift + side arrows.
    ("ws_prev",          "<Shift-Left>",      "Previous workspace",        "_ws_cycle_prev"),
    ("ws_next",          "<Shift-Right>",     "Next workspace",            "_ws_cycle_next"),
    # Switch tabs on the active panel — Ctrl + side arrows.
    ("tab_prev",         "<Control-Left>",    "Previous tab (active panel)",  "_tab_prev"),
    ("tab_next",         "<Control-Right>",   "Next tab (active panel)",      "_tab_next"),
    # Move the active tab to the far left / right — Alt + side arrows.
    ("tab_move_first",   "<Alt-Left>",        "Move tab to leftmost",      "_tab_move_leftmost"),
    ("tab_move_last",    "<Alt-Right>",       "Move tab to rightmost",     "_tab_move_rightmost"),
    # Cursor jumps between the two blocks of the list.  Home/End go all the
    # way to the ends and Page Up/Down move a window-full — these land exactly
    # on the first file / the first folder in the CURRENT sort order.
    ("goto_first_file",  "<Control-Down>",    "Jump to first file (past folders)", "_goto_first_file"),
    ("goto_first_folder","<Control-Up>",      "Jump to first folder (past '..')",  "_goto_first_folder"),
    ("auto_refresh",     "<Control-Alt-r>",   "Toggle auto-refresh",       "toggle_auto_refresh"),
    ("shortcuts",        "<Control-Alt-k>",   "Configure shortcuts",       "open_shortcut_config"),
    # NOTE: Ctrl+Alt+T is deliberately avoided — Total Commander registers it
    # as a global hotkey, so it never reaches this program.
    ("toolbar_config",   "<Control-Alt-b>",   "Configure toolbar",         "open_toolbar_config"),
    ("shares",           "<Control-Alt-n>",   "Browse network shares",     "open_shares"),
    # The "Go to:" box at the right-hand end of the Workspace bar (DEL 51).
    # Ctrl+Shift+G, because plain Ctrl+G is File tags and Ctrl+L is the
    # command bar — Tk tells the capital letter from the small one.
    ("goto_box",         "<Control-G>",       "Go to — the path box on the Workspace bar",
                                                                          "_goto_focus_box"),
    ("palette",          "<Control-P>",       "Command palette",           "open_palette"),
    ("undo_history",     "<Control-z>",       "Undo history",              "open_undo"),
    ("treemap",          "<Control-Alt-d>",   "Disk usage (treemap)",      "open_treemap"),
    ("tags",             "<Control-g>",       "File tags",                 "open_tags"),
    ("flag_toggle",      "<Control-Alt-m>",   "Flag / unflag (★ column)",  "toggle_flag_selected"),
    ("dates_delete",     "",                  "Dates & deletion settings", "open_dates_delete"),
    ("relocator",        "<Control-Alt-x>",   "Relocator (tidy files away)", "open_relocator"),
    # The ⚖ Rules button on the Workspace bar, on a key as well (DEL 52).
    ("pair_rules",       "<Control-Alt-w>",   "Rules for the two folders in the panels",
                                                                          "open_pair_rules"),
    # 💿 Build a data image from the selection (DEL 53).
    ("make_image",       "<Control-Alt-i>",   "Create ISO / IMG image from the selection",
                                                                          "make_image"),
    # Total Commander's own key for this.  Folders are listed with an empty
    # Size cell, so "sort folders by size" had nothing to sort on until the
    # numbers are actually measured.
    ("folder_sizes",     "<Alt-Shift-Return>", "Show folder sizes in the Size column",
                                                                          "calc_folder_sizes"),
    # The standing MODE version of the line above — same thing, but for every
    # listing from now on instead of this one press.  No default key: it is a
    # setting, and Alt+Shift+Enter is the one you reach for by hand.
    ("auto_folder_sizes", "",                  "Folder sizes: always on / off (mode)",
                                                                          "toggle_auto_folder_sizes"),
    ("help",             "<F1>",              "Help",                      "_show_help"),
]

DEFAULT_KEYMAP = {aid: key for aid, key, _label, _method in KEY_ACTIONS}
KEY_LABELS     = {aid: label for aid, _key, label, _method in KEY_ACTIONS}
KEY_METHODS    = {aid: method for aid, _key, _label, method in KEY_ACTIONS}


def load_keymap() -> dict:
    """Defaults merged with the user's saved overrides."""
    keymap = dict(DEFAULT_KEYMAP)
    try:
        with open(KEYMAP_PATH, "r", encoding="utf-8") as fh:
            saved = json.load(fh)
        if isinstance(saved, dict):
            for aid, key in saved.items():
                if aid in DEFAULT_KEYMAP:
                    keymap[aid] = key
    except FileNotFoundError:
        pass
    except Exception as exc:
        _log(f"Could not read keymap.json: {exc}")
    return keymap


def save_keymap(keymap: dict):
    try:
        # Only store what actually differs from the defaults
        diff = {aid: key for aid, key in keymap.items()
                if DEFAULT_KEYMAP.get(aid) != key}
        with open(KEYMAP_PATH, "w", encoding="utf-8") as fh:
            json.dump(diff, fh, indent=2, ensure_ascii=False)
    except Exception as exc:
        _log(f"Could not save keymap.json: {exc}")


def key_to_label(seq: str) -> str:
    """Turn '<Control-Shift-T>' into a readable 'Ctrl+Shift+T'."""
    if not seq:
        return "(none)"
    body = seq.strip("<>")
    parts = body.split("-")
    out = []
    for p in parts[:-1]:
        out.append({"Control": "Ctrl", "Alt": "Alt", "Shift": "Shift"}.get(p, p))
    last = parts[-1]
    pretty = {"Return": "Enter", "Next": "PageDown", "Prior": "PageUp",
              "grave": "`", "slash": "/", "space": "Space"}.get(last, last)
    # A bare capital letter in a Control binding means Shift is implied
    if len(pretty) == 1 and pretty.isupper() and "Shift" not in out and out:
        out.append("Shift")
    out.append(pretty.upper() if len(pretty) == 1 else pretty)
    return "+".join(out)


class ShortcutConfigWindow(tk.Toplevel):
    """Let the user rebind any shortcut, with conflict detection."""

    def __init__(self, manager: "EditorFrame"):
        super().__init__(manager)
        self.manager = manager
        self.working = dict(manager.keymap)

        self.configure(bg=C_BG)
        self.geometry("720x620")
        _setup_toplevel(self, "Configure keyboard shortcuts", manager, modal=False)

        head = tk.Frame(self, bg=C_BG3)
        head.pack(fill="x")
        tk.Label(head, text="⌨  Keyboard shortcuts", bg=C_BG3, fg=C_ACCENT,
                 font=("Segoe UI", 12, "bold")).pack(side="left", padx=10, pady=7)
        tk.Label(head, text="Select an action, then press the new key combination",
                 bg=C_BG3, fg=C_FG_DIM, font=("Segoe UI", 9)).pack(side="left")

        mid = tk.Frame(self, bg=C_BG)
        mid.pack(fill="both", expand=True, padx=10, pady=8)
        self.tree = ttk.Treeview(mid, columns=("key", "default"), selectmode="browse")
        self.tree.heading("#0",      text="Action",   anchor="w")
        self.tree.heading("key",     text="Shortcut", anchor="w")
        self.tree.heading("default", text="Default",  anchor="w")
        self.tree.column("#0", width=300, stretch=True)
        self.tree.column("key", width=180)
        self.tree.column("default", width=180)
        sb = ttk.Scrollbar(mid, orient="vertical", command=self.tree.yview)
        self.tree.configure(yscrollcommand=sb.set)
        self.tree.pack(side="left", fill="both", expand=True)
        sb.pack(side="right", fill="y")
        self.tree.tag_configure("changed", foreground=TC_WARN)
        self.tree.tag_configure("clash",   foreground=TC_BAD)

        cap = tk.Frame(self, bg=C_BG2)
        cap.pack(fill="x", padx=10)
        tk.Label(cap, text="New shortcut:", bg=C_BG2, fg=C_FG).pack(side="left",
                                                                    padx=(6, 4), pady=5)
        self.capture = tk.Entry(cap, width=28, bg=C_BG, fg=C_ACCENT,
                                insertbackground=C_FG, font=("Segoe UI", 10, "bold"),
                                insertofftime=0, insertontime=9999999)
        self.capture.pack(side="left", pady=5)
        self.capture.bind("<Key>", self._on_key)
        tk.Label(cap, text="(click here and press the keys)", bg=C_BG2, fg=C_FG_DIM,
                 font=("Segoe UI", 8, "italic")).pack(side="left", padx=6)
        tk.Button(cap, text="Clear shortcut", bg="white", fg="black",
                  font=("Segoe UI", 8),
                  command=self._clear_binding).pack(side="right", padx=6)

        bot = tk.Frame(self, bg=C_BG)
        bot.pack(fill="x", padx=10, pady=10)
        self._status = tk.Label(bot, text="", bg=C_BG, fg=C_FG_DIM, anchor="w")
        self._status.pack(side="left", fill="x", expand=True)
        tk.Button(bot, text="Close", bg="grey", fg="white", width=9,
                  command=self.destroy).pack(side="right", padx=3)
        tk.Button(bot, text="✔  Apply", bg="lightgreen", fg="black", width=11,
                  command=self._apply).pack(side="right", padx=3)
        tk.Button(bot, text="Restore defaults", bg="white", fg="black",
                  command=self._restore).pack(side="right", padx=3)

        self._render()
        self.bind("<Return>", lambda e: self._apply())

    def _render(self):
        sel = self.tree.selection()
        self.tree.delete(*self.tree.get_children())
        used = {}
        for aid, key in self.working.items():
            if key:
                used.setdefault(key, []).append(aid)
        clashes = {k for k, v in used.items() if len(v) > 1}
        for aid, default, label, _m in KEY_ACTIONS:
            key = self.working.get(aid, "")
            tags = ()
            if key in clashes:
                tags = ("clash",)
            elif key != default:
                tags = ("changed",)
            self.tree.insert("", "end", iid=aid, text=label,
                             values=(key_to_label(key), key_to_label(default)),
                             tags=tags)
        if sel:
            try:
                self.tree.selection_set(sel[0])
            except Exception:
                pass
        if clashes:
            self._status.configure(
                text=f"{len(clashes)} shortcut(s) are assigned twice — "
                     "shown in red", fg="#ff6b6b")
        else:
            self._status.configure(text="No conflicts.", fg=C_FG_DIM)

    def _on_key(self, event):
        """Turn a key press into a tkinter binding string."""
        sel = self.tree.selection()
        if not sel:
            self._status.configure(text="Select an action in the list first.",
                                   fg="#ffd479")
            return "break"

        keysym = event.keysym
        if keysym in ("Control_L", "Control_R", "Alt_L", "Alt_R",
                      "Shift_L", "Shift_R", "Win_L", "Win_R"):
            return "break"       # a modifier on its own is not a shortcut

        ctrl  = bool(event.state & 0x4)
        shift = bool(event.state & 0x1)
        alt   = bool(event.state & 0x20000) or bool(event.state & 0x8)

        parts = []
        if ctrl:
            parts.append("Control")
        if alt:
            parts.append("Alt")

        if len(keysym) == 1 and keysym.isalpha():
            # Tk convention: Shift is expressed by using the capital letter
            key = keysym.upper() if shift else keysym.lower()
        else:
            if shift:
                parts.append("Shift")
            key = keysym
        parts.append(key)
        seq = "<" + "-".join(parts) + ">"

        self.working[sel[0]] = seq
        self.capture.delete(0, "end")
        self.capture.insert(0, key_to_label(seq))
        self._render()
        self.tree.selection_set(sel[0])
        return "break"

    def _clear_binding(self):
        sel = self.tree.selection()
        if sel:
            self.working[sel[0]] = ""
            self._render()
            self.tree.selection_set(sel[0])

    def _restore(self):
        if _ask_yes_no("Shortcuts",
                               "Restore every shortcut to its default?",
                               parent=self):
            self.working = dict(DEFAULT_KEYMAP)
            self._render()

    def _apply(self):
        used = {}
        for aid, key in self.working.items():
            if key:
                used.setdefault(key, []).append(aid)
        clashes = {k: v for k, v in used.items() if len(v) > 1}
        if clashes:
            detail = "\n".join(
                f"  {key_to_label(k)} → " + ", ".join(KEY_LABELS[a] for a in v)
                for k, v in clashes.items())
            messagebox.showerror(
                "Shortcuts",
                f"These shortcuts are assigned more than once:\n\n{detail}\n\n"
                "Give each action its own key before applying.", parent=self)
            return
        self.manager.keymap = dict(self.working)
        save_keymap(self.manager.keymap)
        self.manager.rebind_keys()
        _flash_ok(self, "Shortcuts applied.", "Shortcuts")


# ══════════════════════════════════════════════════════════════════════════
#  DEL 35 — Network share discovery  (NetRadar-style \\server\Share finder)
# ══════════════════════════════════════════════════════════════════════════
#
# The LAN scanner finds hosts; this finds what each host actually offers, so
# a share such as \\TOWER\Film can be opened straight into a panel instead of
# being typed by hand.

def list_smb_shares(host: str, timeout: int = 20, include_admin: bool = False) -> list:
    """List the SMB shares a host offers, via `net view`.

    Returns [{'name', 'type', 'comment'}].  Raises RuntimeError on failure.
    The output of `net view` is localised, so the parser keys off the line of
    dashes rather than any English header text.
    """
    host = host.strip().strip("\\/")
    if not host:
        raise RuntimeError("No host given.")
    if platform.system() != "Windows":
        raise RuntimeError("Share browsing is a Windows feature.")

    _net_restore_login(host)        # a saved sign-in, if Windows lost it
    cmd = ["net", "view", f"\\\\{host}"]
    if include_admin:
        cmd.append("/all")
    try:
        res = subprocess.run(cmd, capture_output=True, text=True,
                             errors="replace", timeout=timeout,
                             **_no_window_kwargs())
    except subprocess.TimeoutExpired:
        raise RuntimeError(f"{host} did not answer within {timeout} seconds.")
    except Exception as exc:
        raise RuntimeError(f"Could not run `net view`: {exc}")

    out = res.stdout or ""
    if res.returncode != 0 and not out.strip():
        err = (res.stderr or "").strip() or f"net view returned {res.returncode}"
        # The common cases are worth translating into plain language
        low = err.lower()
        # `net view` words its errors by language, but the number is stable.
        # 53 ("network path not found") is also what a computer that wants a
        # sign-in answers to an unknown user, so look at the port first:
        # if it answers, the computer IS there and only needs a sign-in.
        m = _re.search(r"\b(\d{1,4})\b", err)
        code = int(m.group(1)) if m else 0
        if code in (5, 53, 86, 1219, 1326, 1331) or "access is denied" in low \
                or "åtkomst" in low or "network path" in low:
            if _net_port_open(host):
                raise NetNeedsSignIn(
                    f"{host} is there but needs a sign-in (user and password) "
                    "before it shows its drives.")
            raise RuntimeError(f"{host} was not found on the network.")
        raise RuntimeError(err)

    lines = out.splitlines()
    # Everything after the dashed rule and before the trailing status line
    try:
        start = next(i for i, l in enumerate(lines)
                     if l.strip() and set(l.strip()) <= set("-")) + 1
    except StopIteration:
        start = 0

    shares = []
    for line in lines[start:]:
        raw = line.rstrip()
        if not raw.strip():
            continue
        # The closing "The command completed successfully." line has no columns
        parts = _re.split(r"\s{2,}", raw.strip())
        name = parts[0].strip()
        if not name or " " in name and len(parts) == 1:
            continue
        if name.lower().startswith("the command") or name.endswith("."):
            continue
        stype = parts[1].strip() if len(parts) > 1 else ""
        comment = parts[2].strip() if len(parts) > 2 else ""
        # Skip printers and IPC — only disks can be opened in a panel
        shares.append({"name": name, "type": stype, "comment": comment})
    return shares


def share_is_reachable(unc: str, timeout: float = 3.0) -> bool:
    """True if a UNC path can actually be listed (not just advertised)."""
    result = {}

    def probe():
        try:
            os.listdir(unc)
            result["ok"] = True
        except Exception:
            result["ok"] = False

    t = threading.Thread(target=probe, daemon=True)
    t.start()
    t.join(timeout)
    return result.get("ok", False)


class SharesWindow(tk.Toplevel):
    """Browse the shares offered by one host — or by every host found so far."""

    def __init__(self, manager: "EditorFrame", host: str = "",
                 hosts: list = None):
        super().__init__(manager)
        self.manager = manager
        self._stop = threading.Event()
        self._busy = False
        self._rows: list = []          # [(host, share_dict, unc, reachable)]

        self.configure(bg=C_BG)
        self.geometry("900x600")
        _setup_toplevel(self, "Network shares", manager, modal=False)

        self.var_host  = tk.StringVar(value=host)
        self.var_admin = tk.BooleanVar(value=False)
        self.var_check = tk.BooleanVar(value=True)
        self._preset_hosts = hosts or []

        self._build_ui()
        if host:
            self.after(80, self._scan_one)
        elif self._preset_hosts:
            self.after(80, self._scan_all)

    def _build_ui(self):
        head = tk.Frame(self, bg=C_BG3)
        head.pack(fill="x")
        tk.Label(head, text="🖧  Network shares", bg=C_BG3, fg=C_ACCENT,
                 font=("Segoe UI", 12, "bold")).pack(side="left", padx=10, pady=7)
        tk.Label(head, text="Find what a machine offers — e.g. \\\\TOWER\\Film",
                 bg=C_BG3, fg=C_FG_DIM, font=("Segoe UI", 9)).pack(side="left")

        form = tk.Frame(self, bg=C_BG)
        form.pack(fill="x", padx=10, pady=8)
        row = tk.Frame(form, bg=C_BG)
        row.pack(fill="x")
        tk.Label(row, text="Computer:", bg=C_BG, fg=C_FG, width=10,
                 anchor="w").pack(side="left")
        ent = tk.Entry(row, textvariable=self.var_host, bg=C_BG2, fg=C_FG,
                       insertbackground=C_FG,
                       insertofftime=0, insertontime=9999999)
        ent.pack(side="left", fill="x", expand=True)
        ent.bind("<Return>", lambda e: self._scan_one())
        tk.Button(row, text="▶  Show shares", bg="lightgreen", fg="black",
                  command=self._scan_one).pack(side="left", padx=4)
        tk.Button(row, text="■  Stop", bg="white", fg="black",
                  command=lambda: self._stop.set()).pack(side="left")

        opt = tk.Frame(form, bg=C_BG)
        opt.pack(fill="x", pady=(6, 0))
        tk.Checkbutton(opt, text="Include hidden / admin shares (C$, ADMIN$)",
                       variable=self.var_admin, bg=C_BG, fg=C_FG,
                       selectcolor=C_BG2, activebackground=C_BG,
                       activeforeground=C_FG).pack(side="left")
        tk.Checkbutton(opt, text="Check that each share really opens",
                       variable=self.var_check, bg=C_BG, fg=C_FG,
                       selectcolor=C_BG2, activebackground=C_BG,
                       activeforeground=C_FG).pack(side="left", padx=(12, 0))
        tk.Button(opt, text="🔍  Scan every host found by the LAN scan",
                  bg="lightblue", fg="black",
                  command=self._scan_all).pack(side="right")

        mid = tk.Frame(self, bg=C_BG)
        mid.pack(fill="both", expand=True, padx=10, pady=4)
        cols = ("type", "status", "comment", "unc")
        self.tree = ttk.Treeview(mid, columns=cols, selectmode="browse")
        self.tree.heading("#0",      text="Computer / share", anchor="w")
        self.tree.heading("type",    text="Type",    anchor="w")
        self.tree.heading("status",  text="Status",  anchor="w")
        self.tree.heading("comment", text="Comment", anchor="w")
        self.tree.heading("unc",     text="Path",    anchor="w")
        self.tree.column("#0", width=230, stretch=True)
        self.tree.column("type", width=70)
        self.tree.column("status", width=90)
        self.tree.column("comment", width=190)
        self.tree.column("unc", width=250)
        sb = ttk.Scrollbar(mid, orient="vertical", command=self.tree.yview)
        self.tree.configure(yscrollcommand=sb.set)
        self.tree.pack(side="left", fill="both", expand=True)
        sb.pack(side="right", fill="y")
        self.tree.tag_configure("host",  foreground=TC_INFO,
                                font=("Segoe UI", 9, "bold"))
        self.tree.tag_configure("ok",    foreground=TC_OK)
        self.tree.tag_configure("nope",  foreground=TC_MUTED)
        self.tree.bind("<Double-1>", lambda e: self._open("active"))

        bot = tk.Frame(self, bg=C_BG)
        bot.pack(fill="x", padx=10, pady=(0, 10))
        self._status = tk.Label(bot, text="Enter a computer name or IP address.",
                                bg=C_BG, fg=C_FG_DIM, anchor="w")
        self._status.pack(side="left", fill="x", expand=True)
        tk.Button(bot, text="Close", bg="grey", fg="white", width=9,
                  command=self.destroy).pack(side="right", padx=3)
        tk.Button(bot, text="Open right →", bg="lightblue", fg="black",
                  command=lambda: self._open("right")).pack(side="right", padx=3)
        tk.Button(bot, text="← Open left", bg="lightblue", fg="black",
                  command=lambda: self._open("left")).pack(side="right", padx=3)
        tk.Button(bot, text="⭐  Add to hotlist", bg="white", fg="black",
                  command=self._add_hotlist).pack(side="right", padx=3)
        tk.Button(bot, text="🔗  Map drive letter…", bg="white", fg="black",
                  command=self._map_drive).pack(side="right", padx=3)
        tk.Button(bot, text="★  Save ALL as network favourites…",
                  bg="lightgreen", fg="black",
                  command=self._save_all_favourites).pack(side="right", padx=3)

        self.bind("<Return>", lambda e: self._open("active"))

    # ── Scanning ──────────────────────────────────────────────────────────

    def _scan_one(self):
        host = self.var_host.get().strip()
        if not host:
            messagebox.showinfo("Shares", "Enter a computer name or IP address.",
                                parent=self)
            return
        self._start([host], clear=True)

    def _scan_all(self):
        hosts = list(self._preset_hosts)
        if not hosts:
            messagebox.showinfo(
                "Shares",
                "No hosts to scan.\n\n"
                "Run a LAN scan first (NET ▾ → Scan …), then open this window "
                "from the scan results.", parent=self)
            return
        self._start(hosts, clear=True)

    def _start(self, hosts: list, clear: bool):
        if self._busy:
            return
        self._busy = True
        self._stop.clear()
        if clear:
            self._rows = []
            self.tree.delete(*self.tree.get_children())
        threading.Thread(target=self._worker, args=(hosts,), daemon=True).start()

    def _worker(self, hosts: list):
        found = 0
        for i, host in enumerate(hosts, 1):
            if self._stop.is_set():
                break
            _ui_call(self, lambda h=host, i=i: self._status.configure(
                text=f"Asking {h} …  ({i} of {len(hosts)})", fg=C_ACCENT))
            try:
                shares = list_smb_shares(host, include_admin=self.var_admin.get())
            except Exception as exc:
                _ui_call(self, lambda h=host, e=exc: self._add_host(h, [], str(e)))
                continue

            rows = []
            for sh in shares:
                unc = f"\\\\{host}\\{sh['name']}"
                reachable = (share_is_reachable(unc)
                             if self.var_check.get() else None)
                rows.append((sh, unc, reachable))
                found += 1
            _ui_call(self, lambda h=host, r=rows: self._add_host(h, r, ""))

        self._busy = False
        _ui_call(self, lambda: self._status.configure(
            text=(f"{found} share(s) found on {len(hosts)} host(s)."
                  if found else "No shares found."),
            fg=TC_OK if found else C_FG_DIM))

    def _add_host(self, host: str, rows: list, error: str):
        node = self.tree.insert("", "end", text=f"🖥  {host}",
                                values=("", "error" if error else
                                        f"{len(rows)} share(s)",
                                        error, f"\\\\{host}"),
                                open=True, tags=("host",))
        for sh, unc, reachable in rows:
            if reachable is None:
                status, tag = "", ()
            elif reachable:
                status, tag = "opens", ("ok",)
            else:
                status, tag = "no access", ("nope",)
            iid = self.tree.insert(node, "end", text=f"📁  {sh['name']}",
                                   values=(sh["type"], status, sh["comment"], unc),
                                   tags=tag)
            self._rows.append(iid)

    # ── Actions ───────────────────────────────────────────────────────────

    def _selected_unc(self) -> str:
        sel = self.tree.selection()
        if not sel:
            return ""
        return self.tree.item(sel[0], "values")[3]

    def _open(self, side: str):
        unc = self._selected_unc()
        if not unc:
            messagebox.showinfo("Shares", "Select a share first.", parent=self)
            return
        if not os.path.isdir(unc):
            messagebox.showerror(
                "Shares",
                f"{unc} could not be opened.\n\n"
                "The share may need credentials — connect to it once in "
                "Explorer, or map it to a drive letter.", parent=self)
            return
        panel = (self.manager.get_active_panel() if side == "active"
                 else getattr(self.manager, f"{side}_panel"))
        if getattr(panel, "is_remote", False):
            messagebox.showinfo("Shares",
                                "That panel is mounted on FTP — unmount it first.",
                                parent=self)
            return
        panel.change_directory(unc)
        self.destroy()

    def _add_hotlist(self):
        unc = self._selected_unc()
        if not unc:
            return
        name = _ask_text(self, "Add to hotlist", "Name for this share:",
                         initial=unc.rstrip("\\").split("\\")[-1])
        if name:
            self.manager.hotlist.append({"name": name, "path": unc})
            self.manager.save_hotlist()
            _flash_ok(self, f"Added “{name}” to the hotlist.", "Hotlist")

    def _save_all_favourites(self):
        """Turn every share found here into a network favourite in one go.

        That completes the NetRadar-style loop: scan the LAN, see what each
        machine offers, save them all, and reconnect the lot afterwards with
        NET ▾ → Activate All Favorites.
        """
        # Only real, reachable disk shares are worth a drive letter
        shares = []
        for node in self.tree.get_children():
            for iid in self.tree.get_children(node):
                vals = self.tree.item(iid, "values")
                if not vals or len(vals) < 4:
                    continue
                stype, status, _comment, unc = vals[0], vals[1], vals[2], vals[3]
                if status == "no access":
                    continue
                if stype and "disk" not in stype.lower():
                    continue          # printers and IPC cannot be mounted
                name = self.tree.item(iid, "text").replace("📁", "").strip()
                if name.endswith("$"):
                    continue          # skip admin shares by default
                shares.append((name, unc))

        if not shares:
            messagebox.showinfo(
                "Network favourites",
                "No usable disk shares in the list.\n\n"
                "Run a scan first — shares marked “no access”, printers and "
                "hidden admin shares (C$) are skipped.", parent=self)
            return

        existing = _net_load_favorites()
        taken = {f.get("letter", "").upper().rstrip(":") for f in existing}
        taken |= {d[0] for d in _get_mapped_letters()}
        free = [c for c in "ZYXWVUTSRQPONMLKJIHGF" if c not in taken]

        # Anything already saved for the same path is left alone
        known_paths = {f.get("path", "").lower().rstrip("\\") for f in existing}
        todo = [(n, u) for n, u in shares
                if u.lower().rstrip("\\") not in known_paths]
        if not todo:
            messagebox.showinfo("Network favourites",
                                "Every share here is already saved as a favourite.",
                                parent=self)
            return
        if len(todo) > len(free):
            messagebox.showwarning(
                "Network favourites",
                f"{len(todo)} share(s) to save but only {len(free)} free drive "
                f"letter(s).\n\nThe first {len(free)} will be saved.",
                parent=self)
            todo = todo[:len(free)]

        preview = "\n".join(f"   {free[i]}:   {u}" for i, (n, u) in enumerate(todo))
        if not _ask_yes_no(
                "Network favourites",
                f"Save {len(todo)} share(s) as network favourites?\n\n{preview}\n\n"
                "Afterwards, NET ▾ → Activate All Favorites reconnects them all "
                "with one click.", parent=self):
            return

        for i, (name, unc) in enumerate(todo):
            existing.append({
                "name":   f"{name} ({unc.strip(chr(92)).split(chr(92))[0]})",
                "letter": f"{free[i]}:",
                "path":   unc,
                "user":   "",
                "_pw":    "",
            })
        _net_save_favorites(existing)
        _flash_ok(self,
                  f"Saved {len(todo)} favourite(s).\n"
                  "NET ▾ → Activate All Favorites reconnects them.",
                  "Network favourites", ms=1600)

    def _map_drive(self):
        unc = self._selected_unc()
        if not unc or unc.count("\\") < 3:
            messagebox.showinfo("Map drive", "Select a share first.", parent=self)
            return
        used = {d[0].upper() for d in _get_mapped_letters()}
        free = [c for c in "ZYXWVUTSRQPONMLKJIHGF" if c not in used]
        if not free:
            messagebox.showerror("Map drive", "No free drive letters.", parent=self)
            return
        letter = _ask_text(self, "Map drive",
                           f"Drive letter for\n{unc}",
                           initial=free[0], choices=free[:20])
        if not letter:
            return
        letter = letter.strip().rstrip(":").upper()[:1]
        if not letter or letter not in _string.ascii_uppercase:
            messagebox.showerror("Map drive", "Enter a single drive letter.",
                                 parent=self)
            return
        try:
            res = subprocess.run(["net", "use", f"{letter}:", unc, "/persistent:no"],
                                 capture_output=True, text=True, errors="replace",
                                 timeout=30, **_no_window_kwargs())
            if res.returncode != 0:
                raise RuntimeError((res.stderr or res.stdout).strip())
            self.manager.refresh_panels()
            _flash_ok(self, f"{unc}\nmapped to {letter}:", "Mapped")
        except Exception as exc:
            messagebox.showerror("Map drive", f"Could not map the drive:\n{exc}",
                                 parent=self)


def _get_mapped_letters() -> list:
    """Drive letters currently in use, e.g. ['C:', 'D:']."""
    out = []
    try:
        bits = ctypes.windll.kernel32.GetLogicalDrives()
        for i, ch in enumerate(_string.ascii_uppercase):
            if bits & (1 << i):
                out.append(f"{ch}:")
    except Exception:
        pass
    return out


# ══════════════════════════════════════════════════════════════════════════
#  DEL 35b — Find the HARD DRIVES on a host  (admin C$/D$… shares) and save
#            each with your own drive letter
# ══════════════════════════════════════════════════════════════════════════
#
# A scanned machine is just an IP.  You cannot map \\IP\ — you map a SHARE on
# it (\\IP\C$, \\IP\D$ …).  This dialog discovers the physical drives a host
# offers (the hidden admin drive shares plus any normal disk shares), lets you
# tick the ones you want, give each its OWN target drive letter, and then save
# them as network favourites and/or map them right away.

def _net_open_session(host: str, user: str = "", pw: str = "") -> None:
    """Best-effort: open an authenticated IPC$ session to *host* so that the
    hidden admin drive shares (C$, D$ …) can be listed.  Silently ignored when
    no credentials are given or the session already exists."""
    host = host.strip().strip("\\/")
    if not host:
        return
    if not user:
        _net_restore_login(host)        # nothing typed: use the saved sign-in
        return
    # Typed sign-in: use it now AND keep it (Windows + File manager's own list)
    # so the computer is found again next time and after a Windows reinstall.
    _net_sign_in(host, user, pw, remember=True)


def _net_probe_share(unc: str, timeout: float = 2.0) -> str:
    """Probe one UNC path and classify it:
        "open"    — it lists, you can use it now
        "denied"  — it EXISTS but you lack rights (needs credentials)
        "absent"  — no such share / drive letter on the host
    The difference matters for the drive finder: a "denied" C$ means that hard
    drive really is there, you just have to sign in; an "absent" one is not."""
    result = {"status": "absent"}

    def probe():
        try:
            os.listdir(unc)
            result["status"] = "open"
        except PermissionError:
            result["status"] = "denied"          # exists, access refused
        except OSError as exc:
            we = getattr(exc, "winerror", None)
            # 5 access denied, 1326 logon failure, 86 bad password,
            # 1327 account restriction → the share exists, creds are the issue
            if we == 1272:
                # Windows 11 blocks guest-only access before it even looks at
                # the share name: the computer is there but every drive letter
                # answers the same, so nothing can be said about which exist
                # until a real user/password is given (2026-11-03).
                result["status"] = "blocked"
            elif we in (5, 86, 1219, 1326, 1327, 1330, 1331):
                result["status"] = "denied"
            else:
                result["status"] = "absent"      # 53/67/2 = not found, etc.
        except Exception:
            result["status"] = "absent"

    t = threading.Thread(target=probe, daemon=True)
    t.start()
    t.join(timeout)
    return result["status"]


def _net_discover_drives(host: str, user: str = "", pw: str = "",
                         stop_evt: "threading.Event | None" = None) -> list:
    """Discover the drives/disk shares a host offers.

    Probes the hidden admin drive shares \\host\\C$ … \\host\\Z$ (these map to
    the machine's physical drives) and merges in any normal disk shares from
    `net view`.  Returns a list of dicts sorted drive-letter first:
        {'unc', 'label', 'kind', 'status'}
    status is "open" (usable now), "denied" (exists, needs credentials) or —
    for admin drive letters that simply are not present — the row is skipped.
    So a machine's real hard drives show up even before you sign in, greyed
    out as "needs sign-in", while empty drive letters stay out of the way."""
    host = host.strip().strip("\\/")
    results: list = []
    seen: set = set()
    if not host:
        return results

    _net_open_session(host, user, pw)

    # 1. Hidden admin drive shares C$ … Z$  (skip A$/B$ = floppies)
    for c in "CDEFGHIJKLMNOPQRSTUVWXYZ":
        if stop_evt is not None and stop_evt.is_set():
            break
        unc = f"\\\\{host}\\{c}$"
        status = _net_probe_share(unc, timeout=2.0)
        if status == "blocked":
            break                            # sign-in needed first; see caller
        if status in ("open", "denied"):     # a real drive; keep even if denied
            results.append({"unc": unc, "label": f"{c}$",
                            "kind": "drive$", "status": status})
            seen.add(unc.lower())

    # 2. Normal disk shares advertised by the host
    try:
        for sh in list_smb_shares(host, include_admin=True):
            if stop_evt is not None and stop_evt.is_set():
                break
            name = sh.get("name", "")
            if not name:
                continue
            if sh.get("type") and "disk" not in sh["type"].lower():
                continue                      # printers / IPC can't be mounted
            unc = f"\\\\{host}\\{name}"
            if unc.lower() in seen:
                continue
            status = _net_probe_share(unc, timeout=2.0)
            results.append({"unc": unc, "label": name,
                            "kind": "drive$" if name.endswith("$") else "share",
                            "status": status})
            seen.add(unc.lower())
    except Exception:
        pass

    return results


class NetDrivesDialog(tk.Toplevel):
    """Find the hard drives on one host and save/map them with your own letters."""

    def __init__(self, parent, manager: "EditorFrame", host: str = "",
                 net_win=None):
        super().__init__(parent)
        self.manager = manager
        self._net_win = net_win          # NetworkWindow to refresh (optional)
        self._stop    = threading.Event()
        self._busy    = False
        self._rows: list = []            # [{'data', 'sel_var', 'letter_var'}]

        self.configure(bg=C_BG)
        self.geometry("760x520")
        _setup_toplevel(self, "Find drives on host", parent, modal=False)

        self.var_host = tk.StringVar(value=host)
        # A sign-in saved earlier for this computer is filled in again.
        _saved = _net_logins_load().get(_net_host_key(host), {})
        self.var_user = tk.StringVar(value=_saved.get("user", ""))
        self.var_pw   = tk.StringVar(value=_net_decode_pw(_saved.get("_pw", "")))

        self._build_ui()
        if host:
            self.after(120, self._start)

    # ── UI ────────────────────────────────────────────────────────────────
    def _build_ui(self):
        head = tk.Frame(self, bg=C_BG3)
        head.pack(fill="x")
        tk.Label(head, text="🖴  Drives on host", bg=C_BG3, fg=C_ACCENT,
                 font=("Segoe UI", 12, "bold")).pack(side="left", padx=10, pady=7)
        tk.Label(head, text="Pick the hard drives to save — each with its own letter",
                 bg=C_BG3, fg=C_FG_DIM, font=("Segoe UI", 9)).pack(side="left")

        form = tk.Frame(self, bg=C_BG)
        form.pack(fill="x", padx=10, pady=8)

        r1 = tk.Frame(form, bg=C_BG)
        r1.pack(fill="x")
        tk.Label(r1, text="Computer:", bg=C_BG, fg=C_FG, width=10,
                 anchor="w").pack(side="left")
        ent = tk.Entry(r1, textvariable=self.var_host, bg=C_BG2, fg=C_FG,
                       insertbackground=C_FG, insertofftime=0, insertontime=9999999)
        ent.pack(side="left", fill="x", expand=True)
        ent.bind("<Return>", lambda e: self._start())
        tk.Button(r1, text="🔍  Find drives", bg="lightgreen", fg="black",
                  activebackground="lightgreen",
                  command=self._start).pack(side="left", padx=4)
        tk.Button(r1, text="■  Stop", bg="white", fg="black",
                  activebackground="white",
                  command=lambda: self._stop.set()).pack(side="left")

        r2 = tk.Frame(form, bg=C_BG)
        r2.pack(fill="x", pady=(6, 0))
        tk.Label(r2, text="Sign-in for C$/D$ (remembered for next time) —  "
                          "User:", bg=C_BG, fg=C_FG_DIM,
                 anchor="w").pack(side="left")
        tk.Entry(r2, textvariable=self.var_user, width=16, bg=C_BG2, fg=C_FG,
                 insertbackground=C_FG, insertofftime=0,
                 insertontime=9999999).pack(side="left", padx=(4, 8))
        tk.Label(r2, text="Password:", bg=C_BG, fg=C_FG_DIM).pack(side="left")
        tk.Entry(r2, textvariable=self.var_pw, width=16, show="●", bg=C_BG2,
                 fg=C_FG, insertbackground=C_FG, insertofftime=0,
                 insertontime=9999999).pack(side="left", padx=4)

        # ── Scrollable list of discovered drives ───────────────────────────
        mid = tk.Frame(self, bg=C_BG)
        mid.pack(fill="both", expand=True, padx=10, pady=4)

        col_hdr = tk.Frame(mid, bg=C_BG2)
        col_hdr.pack(fill="x")
        tk.Label(col_hdr, text="  Save", bg=C_BG2, fg=C_FG_DIM, width=6,
                 anchor="w", font=("Segoe UI", 8, "bold")).pack(side="left")
        tk.Label(col_hdr, text="Drive / share", bg=C_BG2, fg=C_FG_DIM, width=28,
                 anchor="w", font=("Segoe UI", 8, "bold")).pack(side="left")
        tk.Label(col_hdr, text="Status", bg=C_BG2, fg=C_FG_DIM, width=12,
                 anchor="w", font=("Segoe UI", 8, "bold")).pack(side="left")
        tk.Label(col_hdr, text="Map to letter", bg=C_BG2, fg=C_FG_DIM,
                 anchor="w", font=("Segoe UI", 8, "bold")).pack(side="left")

        canvas = tk.Canvas(mid, bg=C_BG, highlightthickness=0)
        sb = ttk.Scrollbar(mid, orient="vertical", command=canvas.yview)
        canvas.configure(yscrollcommand=sb.set)
        sb.pack(side="right", fill="y")
        canvas.pack(side="left", fill="both", expand=True)
        self._list_inner = tk.Frame(canvas, bg=C_BG)
        self._list_id = canvas.create_window((0, 0), window=self._list_inner,
                                             anchor="nw")
        self._list_inner.bind(
            "<Configure>",
            lambda e: canvas.configure(scrollregion=canvas.bbox("all")))
        canvas.bind(
            "<Configure>",
            lambda e: canvas.itemconfig(self._list_id, width=e.width))
        canvas.bind("<MouseWheel>",
                    lambda e: canvas.yview_scroll(-1 * (e.delta // 120), "units"))
        self._canvas = canvas

        bot = tk.Frame(self, bg=C_BG)
        bot.pack(fill="x", padx=10, pady=(0, 10))
        self._status = tk.Label(bot, text="Enter a computer name or IP, then Find drives.",
                                bg=C_BG, fg=C_FG_DIM, anchor="w")
        self._status.pack(side="left", fill="x", expand=True)
        tk.Button(bot, text="Close", bg="grey", fg="white", width=9,
                  activebackground="grey",
                  command=self.destroy).pack(side="right", padx=3)
        tk.Button(bot, text="★  Save selected as favourites", bg="lightgreen",
                  fg="black", activebackground="lightgreen",
                  command=self._save_selected).pack(side="right", padx=3)
        tk.Button(bot, text="🔗  Map selected now", bg="lightblue", fg="black",
                  activebackground="lightblue",
                  command=self._map_selected).pack(side="right", padx=3)

    # ── Discovery ───────────────────────────────────────────────────────────
    def _start(self):
        if self._busy:
            return
        host = self.var_host.get().strip()
        if not host:
            messagebox.showinfo("Drives", "Enter a computer name or IP address.",
                                parent=self)
            return
        self._busy = True
        self._stop.clear()
        for w in self._list_inner.winfo_children():
            w.destroy()
        self._rows = []
        self._status.configure(text=f"Looking for drives on {host} …", fg=C_ACCENT)
        threading.Thread(target=self._worker,
                         args=(host, self.var_user.get().strip(),
                               self.var_pw.get()),
                         daemon=True).start()

    def _worker(self, host, user, pw):
        try:
            drives = _net_discover_drives(host, user, pw, self._stop)
        except Exception as exc:
            drives = []
            _ui_call(self, lambda e=exc: self._status.configure(
                text=f"Error: {e}", fg=TC_BAD))
        _ui_call(self, lambda d=drives: self._show_results(d))

    def _show_results(self, drives: list):
        self._busy = False
        if not drives:
            self._status.configure(
                text="No drives listed.  If the computer is there it needs a "
                     "sign-in: fill in User and Password above and press Find "
                     "drives again (it is saved, so next time it just works).",
                fg=C_FG_DIM)
            return

        # Assign a distinct free letter to each row by default
        avail, _mapped = _net_get_drive_info()
        taken = {f.get("letter", "").upper().rstrip(":")
                 for f in _net_load_favorites()}
        free = [l for l in avail if l.rstrip(":") not in taken]
        if not free:
            free = [f"{c}:" for c in "ZYXWVUTSRQPONMLKJIHGF"]

        for i, d in enumerate(drives):
            status = d.get("status", "absent")
            is_open = (status == "open")
            row = tk.Frame(self._list_inner, bg=C_BG)
            row.pack(fill="x", pady=1)
            # Tick only reachable drives by default; a "needs sign-in" drive can
            # still be ticked once you fill in the credentials above.
            sel_var = tk.BooleanVar(value=is_open)
            tk.Checkbutton(row, variable=sel_var, bg=C_BG, activebackground=C_BG,
                           selectcolor=C_BG2).pack(side="left", padx=(6, 0))
            # Drive / share label — greyed out when it needs sign-in
            icon = "🖴" if d["kind"] == "drive$" else "📁"
            tk.Label(row, text=f"{icon}  {d['label']}   {d['unc']}", bg=C_BG,
                     fg=(C_FG if is_open else C_FG_DIM),
                     width=44, anchor="w").pack(side="left")
            # Status
            if is_open:
                st_txt, st_fg = "opens", TC_OK
            else:
                st_txt, st_fg = "needs sign-in", TC_WARN
            tk.Label(row, text=st_txt, bg=C_BG, fg=st_fg, width=13,
                     anchor="w").pack(side="left")
            # Target letter
            letter_var = tk.StringVar(
                value=free[i] if i < len(free) else "")
            ttk.Combobox(row, textvariable=letter_var,
                         values=[f"{c}:" for c in _string.ascii_uppercase[3:]],
                         width=5, state="normal").pack(side="left", padx=4)
            self._rows.append({"data": d, "sel_var": sel_var,
                               "letter_var": letter_var})

        n_ok   = sum(1 for d in drives if d.get("status") == "open")
        n_lock = len(drives) - n_ok
        extra  = (f"  {n_lock} need sign-in (fill in user/password and retry)."
                  if n_lock else "")
        self._status.configure(
            text=f"{len(drives)} drive/share(s) found  ({n_ok} ready).{extra}  "
                 "Tick the ones to keep and set a letter for each.",
            fg=TC_OK)

    # ── Collect the ticked rows ─────────────────────────────────────────────
    def _selected(self) -> list:
        picked = []
        used_letters: set = set()
        for r in self._rows:
            if not r["sel_var"].get():
                continue
            letter = r["letter_var"].get().strip().rstrip(":").upper()[:1]
            if not letter or letter not in _string.ascii_uppercase:
                messagebox.showwarning(
                    "Drives",
                    f"Pick a valid drive letter for {r['data']['unc']}.",
                    parent=self)
                return []
            if letter in used_letters:
                messagebox.showwarning(
                    "Drives",
                    f"Drive letter {letter}: is used for more than one drive — "
                    "give each its own letter.", parent=self)
                return []
            used_letters.add(letter)
            picked.append((f"{letter}:", r["data"]["unc"]))
        if not picked:
            messagebox.showinfo("Drives", "Tick at least one drive first.",
                                parent=self)
        return picked

    def _save_selected(self):
        picked = self._selected()
        if not picked:
            return
        host = self.var_host.get().strip().strip("\\/")
        user = self.var_user.get().strip()
        pw   = self.var_pw.get()
        existing = _net_load_favorites()
        known_paths = {f.get("path", "").lower().rstrip("\\") for f in existing}
        existing_letters = {f.get("letter", "").upper() for f in existing}
        added = 0
        for letter, unc in picked:
            if unc.lower().rstrip("\\") in known_paths:
                continue
            # Keep favourite letters unique against what is already saved
            use_letter = letter
            if use_letter.upper() in existing_letters:
                use_letter = ""     # let the user fix it later; still saved
            share = unc.rstrip("\\").split("\\")[-1]
            existing.append({
                "name":   f"{share} on {host}",
                "letter": use_letter,
                "path":   unc,
                "user":   user,
                "_pw":    _net_encode_pw(pw),
            })
            existing_letters.add(use_letter.upper())
            added += 1
        _net_save_favorites(existing)
        # Refresh an open NetworkWindow's favourites view
        if self._net_win is not None:
            try:
                self._net_win._favorites = _net_load_favorites()
                self._net_win._render_favs()
            except Exception:
                pass
        if added:
            _flash_ok(self,
                      f"Saved {added} drive(s) as favourites.\n"
                      "NET ▾ → Activate All Favorites reconnects them.",
                      "Network favourites", ms=1600)
        else:
            messagebox.showinfo("Drives",
                                "Every selected drive is already saved.",
                                parent=self)

    def _map_selected(self):
        picked = self._selected()
        if not picked:
            return
        user = self.var_user.get().strip()
        pw   = self.var_pw.get()
        ok = 0
        fails = []
        for letter, unc in picked:
            cmd = ["net", "use", letter, unc, "/persistent:no"]
            if user:
                cmd += [f"/user:{user}"]
                if pw:
                    cmd += [pw]
            try:
                res = subprocess.run(cmd, capture_output=True, text=True,
                                     errors="replace", timeout=30,
                                     **_no_window_kwargs())
                if res.returncode == 0:
                    ok += 1
                else:
                    fails.append(f"{letter} {unc}: "
                                 f"{(res.stderr or res.stdout).strip()}")
            except Exception as exc:
                fails.append(f"{letter} {unc}: {exc}")
        self.manager.refresh_panels()
        if fails:
            messagebox.showwarning(
                "Map drives",
                f"Mapped {ok} drive(s).\n\nFailed:\n" + "\n".join(fails),
                parent=self)
        else:
            _flash_ok(self, f"Mapped {ok} drive(s).", "Mapped")


# ══════════════════════════════════════════════════════════════════════════
#  DEL 35c — Transfer presets  (saved 1-click copy/move jobs)
# ══════════════════════════════════════════════════════════════════════════
#
# A preset is a ready-to-run transfer: one or more SOURCE folders/files, a
# DESTINATION (a local folder or a network path like \\TOWER\Media), whether to
# COPY or MOVE, and how to handle name clashes.  Press ▶ Run and it drops
# straight into the Task Queue — no dialogs.  Two typical uses:
#   • "Subtitles → TOWER, overwrite old"   (mode=copy, conflict=overwrite_all)
#   • "Back up my Python programs"          (dated sub-folder = a fresh, safe
#                                            copy every run, nothing overwritten)
# The optional destination sub-folder (and the "add date/time" tick) is the
# "rename on the receiving computer" part: each run can land in its own named
# or time-stamped folder.

# REPORTED, and right (2026-09-12): "Overwrite old" and "Overwrite older" were
# one letter apart and neither said what it did.  The first overwrites
# EVERYTHING that is in the way, old or not — "old" was decoration.  The second
# compares the dates and only writes when the file coming IN is the newer one,
# which is a condition about the source, so that is what it is now named after.
# Nothing is stored by label — every saved rule, preset and setting keeps the
# mode string on the right — so these are free to say the truth.
_CONFLICT_CHOICES = [
    ("Overwrite always", "overwrite_all"),
    ("Skip existing",   "skip_all"),
    ("Backup-rename old", "backup_old"),
    ("Rename new (_1)", "auto_rename"),
    ("Overwrite if newer", "overwrite_older"),
    ("Ask each time",   "ask"),
]
_CONFLICT_LABEL = {mode: lbl for lbl, mode in _CONFLICT_CHOICES}


def _load_transfer_presets() -> list:
    try:
        if TRANSFER_PRESETS_PATH.exists():
            data = json.loads(TRANSFER_PRESETS_PATH.read_text(encoding="utf-8"))
            return data if isinstance(data, list) else []
    except Exception as exc:
        _log(f"Could not load transfer presets: {exc}")
    return []


def _save_transfer_presets(presets: list):
    try:
        TRANSFER_PRESETS_PATH.write_text(
            json.dumps(presets, indent=2, ensure_ascii=False), encoding="utf-8")
    except Exception as exc:
        _log(f"Could not save transfer presets: {exc}")


# Conflict actions that DESTROY the file already there.  A rule doing one of
# these over a whole drive or a whole tree is the shape that cost him a
# backup, so it is flagged wherever a rule is shown (revBF).
_DESTRUCTIVE_MODES = {"overwrite_all", "overwrite_older"}


def _rule_path_overlap(a: str, b: str) -> bool:
    """Can these two rule paths ever describe the same folder?

    True when one is a wildcard, or when one contains the other.  Two folders
    that merely sit side by side are NOT an overlap — nothing is in both."""
    a = (a or "").strip()
    b = (b or "").strip()
    if not a or not b:
        return True                            # "(any)" covers everything
    try:
        an = os.path.normcase(os.path.abspath(a))
        bn = os.path.normcase(os.path.abspath(b))
    except Exception:
        return False
    return (an == bn
            or an.startswith(bn + os.sep)
            or bn.startswith(an + os.sep))


def _conflict_rule_overlaps(rules: list) -> list:
    """Rule pairs that can BOTH describe one transfer and disagree about it.

    His question was the right one: "odd that two rules can be in conflict —
    surely the first one fires and the second is never asked about?"  They are
    not a chain, they are a LOOKUP.  Folder paths NEST, so one transfer can be
    described by several rules at once — a rule on the whole tree also covers
    every folder inside it — and the program has to CHOOSE one.  Two rules are
    in conflict when their sources overlap, their destinations overlap, and
    they then say different things.

    Returns [(i, j, why)], where *why* explains when they are both live."""
    out = []
    for i in range(len(rules)):
        for j in range(i + 1, len(rules)):
            a, b = rules[i], rules[j]
            if not (a.get("enabled", True) and b.get("enabled", True)):
                continue
            if a.get("conflict") == b.get("conflict"):
                continue                       # same answer — nothing to warn
            if not _rule_path_overlap(a.get("src", ""), b.get("src", "")):
                continue
            if not _rule_path_overlap(a.get("dst", ""), b.get("dst", "")):
                continue
            ws_a = (a.get("workspace") or "").strip()
            ws_b = (b.get("workspace") or "").strip()
            # Two DIFFERENT named Workspaces do not make them safe: both are
            # live the moment one is loaded on the left and the other on the
            # right.  And when only one of the two is loaded, the rule scoped
            # to the OTHER one is not merely out-ranked — it is not there at
            # all, so a broad rule decides alone.  That is the exact shape
            # that cost him a backup.
            if ws_a and ws_b and ws_a != ws_b:
                why = (f"both live only when \"{ws_a}\" and \"{ws_b}\" are "
                       f"loaded on the two sides; with just one of them "
                       f"loaded the other rule is not consulted AT ALL")
            elif ws_a or ws_b:
                why = (f"the one with no Workspace applies everywhere, "
                       f"including inside \"{ws_a or ws_b}\"")
            else:
                why = "both always apply; the more precise one wins"
            out.append((i, j, why))
    return out


def _rule_is_catch_all(rule: dict) -> bool:
    """True when a rule's source or destination covers a whole drive, the whole
    program tree, or anything at all.

    Such a rule is not wrong in itself — but it silently governs every folder
    beneath it, including folders he later wrote a precise rule for, so it has
    to be visible."""
    try:
        roots = {os.path.normcase(os.path.abspath(_fm_home())),
                 os.path.normcase(os.path.abspath(_fm_root()))}
    except Exception:
        roots = set()
    for key in ("src", "dst"):
        p = (rule.get(key) or "").strip()
        if not p:
            return True                       # "(any)"
        try:
            ap = os.path.normcase(os.path.abspath(p))
        except Exception:
            continue
        # A bare drive root: "X:\", "B:\"
        if len(ap) <= 3 and ap.endswith(os.sep):
            return True
        if ap in roots:
            return True
    return False


def _load_conflict_rules() -> list:
    try:
        if CONFLICT_RULES_PATH.exists():
            data = fm_unpack_tree(
                json.loads(CONFLICT_RULES_PATH.read_text(encoding="utf-8")))
            return data if isinstance(data, list) else []
    except Exception as exc:
        _log(f"Could not load conflict rules: {exc}")
    return []


def _save_conflict_rules(rules: list):
    try:
        CONFLICT_RULES_PATH.write_text(
            json.dumps(fm_pack_tree(rules), indent=2, ensure_ascii=False),
            encoding="utf-8")
    except Exception as exc:
        _log(f"Could not save conflict rules: {exc}")


# ── How WIDE a saved rule should be ──────────────────────────────────────
# A rule remembers a from→to folder pair, and matching already covers every
# sub-folder underneath it.  The scope decides which folder is written down:
# the one you actually copied from/to, or one of its parents.
#
# WHY: "save this in the working folder" means a dated sub-folder gets made
# every day —  …\Claude_working\2026-08-29\, then …\2026-08-30\ — and an
# exact rule for one of them is dead the next morning.  Saved "1 level up"
# the rule sits on Claude_working itself and covers every dated folder that
# will ever be made under it, so the question is asked once instead of daily.
# The scope is set separately for the source and the destination.
_RULE_SCOPES = [
    ("This folder",     0),
    ("1 level up",      1),
    ("2 levels up",     2),
    ("3 levels up",     3),
    ("Any folder",     -1),
]
_RULE_SCOPE_LABEL = {n: lbl for lbl, n in _RULE_SCOPES}
_RULE_SCOPE_NUM   = {lbl: n for lbl, n in _RULE_SCOPES}


def _rule_scope_path(path: str, levels: int) -> str:
    """Widen *path* by walking *levels* folders up.

    0 = the folder itself, 1-3 = that many parents, negative = "" (which the
    matcher reads as "any folder").  It never climbs past the volume root:
    asking for 3 levels up from "D:\\Foo" gives "D:\\", not nonsense — a rule
    that covered a whole drive by accident is exactly the thing you would not
    notice until it overwrote something."""
    try:
        levels = int(levels)
    except Exception:
        levels = 0
    if levels < 0:
        return ""
    p = str(path or "").strip()
    if not p or levels == 0:
        return p
    p = os.path.abspath(p)
    for _ in range(levels):
        if os.path.splitdrive(p)[1].strip("\\/") == "":
            break                       # already a volume root — go no higher
        parent = os.path.dirname(p.rstrip("\\/"))
        if not parent:
            break
        # dirname("D:\\Foo") is "D:\\", but dirname("D:\\") is "D:" — a drive
        # with no root slash, which is the CURRENT directory on that drive,
        # not its root.  Put the slash back so the rule means what it says.
        if os.path.splitdrive(parent)[1] == "":
            parent += os.sep
        if os.path.normcase(parent) == os.path.normcase(p):
            break
        p = parent
    return p


def _rule_scope_depth(path: str) -> int:
    """How many levels up *path* can still go before it is a volume root.

    Used to grey out the scopes that would do nothing on a shallow path."""
    n, p = 0, os.path.abspath(str(path or ""))
    while n < 3:
        wider = _rule_scope_path(p, 1)
        if os.path.normcase(wider) == os.path.normcase(p):
            break
        p = wider
        n += 1
    return n


def _find_exact_rule(rules: list, src: str, dst: str, workspace: str) -> int:
    """Index of the rule whose source, destination AND workspace match exactly
    (case-insensitive paths), or -1.  Used by the Task Queue's one-tick
    "always auto-resolve this folder pair" checkbox."""
    def _n(p):
        return os.path.normcase(os.path.abspath(p)) if p else ""
    ns, nd, nw = _n(src), _n(dst), (workspace or "")
    for i, r in enumerate(rules):
        if _n(r.get("src", "")) == ns and _n(r.get("dst", "")) == nd \
           and (r.get("workspace", "") or "") == nw:
            return i
    return -1


def _preset_effective_dest(preset: dict) -> str:
    """Compute the real destination for a run: base destination + optional
    sub-folder, with an optional date/time stamp appended for versioned
    backups."""
    dest = preset.get("dest", "").strip()
    sub  = preset.get("subfolder", "").strip()
    if preset.get("dated"):
        stamp = datetime.now().strftime("%Y-%m-%d_%H%M")
        sub = f"{sub}_{stamp}" if sub else stamp
    if sub:
        dest = os.path.join(dest, sub)
    return dest


class TransferPresetsWindow(tk.Toplevel):
    """List of saved transfer jobs; each has a ▶ Run that queues it instantly."""

    def __init__(self, manager: "EditorFrame"):
        super().__init__(manager)
        self.manager = manager
        self.configure(bg=C_BG)
        self.geometry("720x460")
        _setup_toplevel(self, "Transfer presets", manager, modal=False)
        self.presets = _load_transfer_presets()
        self._build_ui()
        self._render()

    def _build_ui(self):
        head = tk.Frame(self, bg=C_BG3)
        head.pack(fill="x")
        tk.Label(head, text="⇪  Transfer presets", bg=C_BG3, fg=C_ACCENT,
                 font=("Segoe UI", 12, "bold")).pack(side="left", padx=10, pady=7)
        tk.Label(head, text="Ready-to-run copy/move jobs — press ▶ Run to queue one",
                 bg=C_BG3, fg=C_FG_DIM, font=("Segoe UI", 9)).pack(side="left")

        bar = tk.Frame(self, bg=C_BG)
        bar.pack(fill="x", padx=10, pady=(8, 2))
        tk.Button(bar, text="＋  New preset", bg="lightgreen", fg="black",
                  activebackground="lightgreen",
                  command=self._new).pack(side="left")
        tk.Button(bar, text="Close", bg="grey", fg="white", width=9,
                  activebackground="grey",
                  command=self.destroy).pack(side="right")

        # Scrollable list of preset rows
        mid = tk.Frame(self, bg=C_BG)
        mid.pack(fill="both", expand=True, padx=10, pady=4)
        canvas = tk.Canvas(mid, bg=C_BG, highlightthickness=0)
        sb = ttk.Scrollbar(mid, orient="vertical", command=canvas.yview)
        canvas.configure(yscrollcommand=sb.set)
        sb.pack(side="right", fill="y")
        canvas.pack(side="left", fill="both", expand=True)
        self._inner = tk.Frame(canvas, bg=C_BG)
        self._inner_id = canvas.create_window((0, 0), window=self._inner,
                                              anchor="nw")
        self._inner.bind("<Configure>",
            lambda e: canvas.configure(scrollregion=canvas.bbox("all")))
        canvas.bind("<Configure>",
            lambda e: canvas.itemconfig(self._inner_id, width=e.width))
        canvas.bind("<MouseWheel>",
            lambda e: canvas.yview_scroll(-1 * (e.delta // 120), "units"))
        self._canvas = canvas

    def _render(self):
        for w in self._inner.winfo_children():
            w.destroy()
        if not self.presets:
            tk.Label(self._inner,
                     text="No presets yet.  Click  “＋ New preset”  to make your "
                          "first 1-click transfer job.",
                     bg=C_BG, fg=C_FG_DIM, font=("Segoe UI", 10),
                     wraplength=640, justify="left").pack(anchor="w", pady=20)
            return
        for idx, p in enumerate(self.presets):
            self._render_row(idx, p)

    def _render_row(self, idx: int, p: dict):
        row = tk.Frame(self._inner, bg=C_BG2, padx=8, pady=6)
        row.pack(fill="x", pady=3)

        left = tk.Frame(row, bg=C_BG2)
        left.pack(side="left", fill="x", expand=True)
        tk.Label(left, text=p.get("name", "(unnamed)"), bg=C_BG2, fg=C_FG,
                 font=("Segoe UI", 10, "bold"), anchor="w").pack(anchor="w")
        n_src = len(p.get("sources", []))
        mode  = "MOVE" if p.get("mode") == "move" else "COPY"
        conf  = _CONFLICT_LABEL.get(p.get("conflict", "ask"), p.get("conflict", ""))
        dest  = p.get("dest", "")
        extra = ""
        if p.get("subfolder") or p.get("dated"):
            sub = p.get("subfolder", "")
            if p.get("dated"):
                sub = (sub + "_<date>") if sub else "<date>"
            extra = f"  ▸  {sub}"
        summary = f"{mode}  ·  {n_src} source(s)  →  {dest}{extra}   ·  on clash: {conf}"
        tk.Label(left, text=summary, bg=C_BG2, fg=C_FG_DIM,
                 font=("Segoe UI", 8), anchor="w",
                 wraplength=460, justify="left").pack(anchor="w")

        btns = tk.Frame(row, bg=C_BG2)
        btns.pack(side="right")
        tk.Button(btns, text="▶ Run", bg="green", fg="white", width=7,
                  activebackground="green",
                  command=lambda i=idx: self._run(i)).pack(side="left", padx=2)
        tk.Button(btns, text="✎ Edit", bg="white", fg="black", width=7,
                  activebackground="white",
                  command=lambda i=idx: self._edit(i)).pack(side="left", padx=2)
        tk.Button(btns, text="🗑", bg="grey", fg="white", width=3,
                  activebackground="grey",
                  command=lambda i=idx: self._delete(i)).pack(side="left", padx=2)

    # ── Actions ─────────────────────────────────────────────────────────────
    def _new(self):
        TransferPresetEditor(self, self.manager, preset=None)

    def _edit(self, idx: int):
        if 0 <= idx < len(self.presets):
            TransferPresetEditor(self, self.manager, preset=self.presets[idx],
                                 edit_idx=idx)

    def _delete(self, idx: int):
        if 0 <= idx < len(self.presets):
            name = self.presets[idx].get("name", "this preset")
            if _ask_yes_no("Delete preset",
                                   f"Delete preset  '{name}'?", parent=self):
                del self.presets[idx]
                _save_transfer_presets(self.presets)
                self._render()

    def _run(self, idx: int):
        if not (0 <= idx < len(self.presets)):
            return
        p = self.presets[idx]
        sources = [s for s in p.get("sources", []) if os.path.exists(s)]
        missing = [s for s in p.get("sources", []) if not os.path.exists(s)]
        if not sources:
            messagebox.showerror(
                "Run preset",
                "None of the source paths exist any more:\n\n" +
                "\n".join(p.get("sources", [])), parent=self)
            return
        dest = _preset_effective_dest(p)
        if not dest:
            messagebox.showerror("Run preset", "This preset has no destination.",
                                 parent=self)
            return
        move = (p.get("mode") == "move")
        conflict = p.get("conflict", "ask")
        try:
            self.manager.task_queue_mgr.add_copy_move(
                sources, dest, move, conflict_mode=conflict)
            # The clash scan is threaded now, so nothing is known about name
            # clashes at this point; _preflight_done() raises the "waiting in
            # the Task Queue" alert itself if the answer turns out to be yes.
            self.manager._after_task_enqueued(
                f"Preset '{p.get('name','')}' queued", has_conflict=False)
        except Exception as exc:
            messagebox.showerror("Run preset", f"Could not queue the job:\n{exc}",
                                 parent=self)
            return
        note = f"Queued: {p.get('name','')}\n{len(sources)} source(s) → {dest}"
        if missing:
            note += f"\n\n(Skipped {len(missing)} missing source(s).)"
        _flash_ok(self, note, "Transfer preset", ms=1600)

    # Called by the editor when a preset is saved
    def reload(self):
        self.presets = _load_transfer_presets()
        self._render()


class TransferPresetEditor(tk.Toplevel):
    """Create or edit one transfer preset."""

    def __init__(self, parent: "TransferPresetsWindow", manager: "EditorFrame",
                 preset: dict = None, edit_idx: int = None):
        super().__init__(parent)
        self.parent   = parent
        self.manager  = manager
        self.edit_idx = edit_idx
        self.configure(bg=C_BG)
        self.geometry("640x560")
        _setup_toplevel(self, "Edit preset" if preset else "New preset",
                        parent, modal=False)

        p = preset or {}
        self.var_name = tk.StringVar(value=p.get("name", ""))
        self.var_dest = tk.StringVar(value=p.get("dest", ""))
        self.var_mode = tk.StringVar(value=p.get("mode", "copy"))
        self.var_conf = tk.StringVar(
            value=_CONFLICT_LABEL.get(p.get("conflict", "overwrite_all"),
                                      _CONFLICT_LABEL["overwrite_all"]))
        self.var_sub  = tk.StringVar(value=p.get("subfolder", ""))
        self.var_dated = tk.BooleanVar(value=bool(p.get("dated", False)))
        self._sources = list(p.get("sources", []))
        self._build_ui()

    def _build_ui(self):
        body = tk.Frame(self, bg=C_BG)
        body.pack(fill="both", expand=True, padx=12, pady=10)

        # Name
        tk.Label(body, text="Preset name:", bg=C_BG, fg=C_FG,
                 anchor="w").pack(fill="x")
        tk.Entry(body, textvariable=self.var_name, bg=C_BG2, fg=C_FG,
                 insertbackground=C_FG, insertofftime=0,
                 insertontime=9999999).pack(fill="x", pady=(0, 8))

        # Sources
        tk.Label(body, text="Source folders / files:", bg=C_BG, fg=C_FG,
                 anchor="w").pack(fill="x")
        src_wrap = tk.Frame(body, bg=C_BG)
        src_wrap.pack(fill="both", expand=True, pady=(0, 4))
        self._lb = tk.Listbox(src_wrap, height=6, bg=C_BG2, fg=C_FG,
                              selectmode="extended",
                              highlightthickness=0, activestyle="none")
        sb = ttk.Scrollbar(src_wrap, orient="vertical", command=self._lb.yview)
        self._lb.configure(yscrollcommand=sb.set)
        sb.pack(side="right", fill="y")
        self._lb.pack(side="left", fill="both", expand=True)
        for s in self._sources:
            self._lb.insert("end", s)

        src_btns = tk.Frame(body, bg=C_BG)
        src_btns.pack(fill="x", pady=(0, 8))
        tk.Button(src_btns, text="＋ Add folder…", bg="white", fg="black",
                  activebackground="white",
                  command=self._add_folder).pack(side="left", padx=(0, 4))
        tk.Button(src_btns, text="＋ Add file…", bg="white", fg="black",
                  activebackground="white",
                  command=self._add_file).pack(side="left", padx=4)
        tk.Button(src_btns, text="＋ Use current selection", bg="white", fg="black",
                  activebackground="white",
                  command=self._add_selection).pack(side="left", padx=4)
        tk.Button(src_btns, text="－ Remove", bg="white", fg="black",
                  activebackground="white",
                  command=self._remove_selected).pack(side="left", padx=4)

        # Destination
        tk.Label(body, text="Destination (local folder or  \\\\computer\\share):",
                 bg=C_BG, fg=C_FG, anchor="w").pack(fill="x")
        dest_wrap = tk.Frame(body, bg=C_BG)
        dest_wrap.pack(fill="x", pady=(0, 8))
        tk.Entry(dest_wrap, textvariable=self.var_dest, bg=C_BG2, fg=C_FG,
                 insertbackground=C_FG, insertofftime=0,
                 insertontime=9999999).pack(side="left", fill="x", expand=True)
        tk.Button(dest_wrap, text="Browse…", bg="white", fg="black",
                  activebackground="white",
                  command=self._browse_dest).pack(side="left", padx=(4, 0))
        tk.Button(dest_wrap, text="Other panel", bg="white", fg="black",
                  activebackground="white",
                  command=self._dest_other_panel).pack(side="left", padx=(4, 0))

        # Mode
        mode_row = tk.Frame(body, bg=C_BG)
        mode_row.pack(fill="x", pady=(0, 6))
        tk.Label(mode_row, text="Mode:", bg=C_BG, fg=C_FG,
                 width=10, anchor="w").pack(side="left")
        tk.Radiobutton(mode_row, text="Copy", variable=self.var_mode,
                       value="copy", bg=C_BG, fg=C_FG, selectcolor=C_BG2,
                       activebackground=C_BG,
                       activeforeground=C_FG).pack(side="left")
        tk.Radiobutton(mode_row, text="Move", variable=self.var_mode,
                       value="move", bg=C_BG, fg=C_FG, selectcolor=C_BG2,
                       activebackground=C_BG,
                       activeforeground=C_FG).pack(side="left", padx=(8, 0))

        # Conflict policy
        conf_row = tk.Frame(body, bg=C_BG)
        conf_row.pack(fill="x", pady=(0, 6))
        tk.Label(conf_row, text="On clash:", bg=C_BG, fg=C_FG,
                 width=10, anchor="w").pack(side="left")
        ttk.Combobox(conf_row, textvariable=self.var_conf,
                     values=[lbl for lbl, _m in _CONFLICT_CHOICES],
                     width=20, state="readonly").pack(side="left")

        # Destination sub-folder + dated
        sub_row = tk.Frame(body, bg=C_BG)
        sub_row.pack(fill="x", pady=(0, 4))
        tk.Label(sub_row, text="Sub-folder:", bg=C_BG, fg=C_FG,
                 width=10, anchor="w").pack(side="left")
        tk.Entry(sub_row, textvariable=self.var_sub, bg=C_BG2, fg=C_FG,
                 insertbackground=C_FG, insertofftime=0,
                 insertontime=9999999).pack(side="left", fill="x", expand=True)
        tk.Checkbutton(body,
                       text="Add date/time to the sub-folder  "
                            "(a fresh, versioned copy every run — good for backups)",
                       variable=self.var_dated, bg=C_BG, fg=C_FG_DIM,
                       selectcolor=C_BG2, activebackground=C_BG,
                       activeforeground=C_FG_DIM).pack(anchor="w", pady=(2, 6))

        # Buttons
        btn_row = tk.Frame(self, bg=C_BG)
        btn_row.pack(fill="x", padx=12, pady=(0, 12))
        tk.Button(btn_row, text="Save preset", bg="green", fg="white", width=14,
                  activebackground="green",
                  command=self._save).pack(side="left")
        tk.Button(btn_row, text="Cancel", bg="grey", fg="white", width=10,
                  activebackground="grey",
                  command=self.destroy).pack(side="right")
        self.bind("<Return>", lambda e: self._save())

    # ── Source helpers ──────────────────────────────────────────────────────
    def _add_folder(self):
        d = filedialog.askdirectory(parent=self, title="Add source folder")
        if d:
            self._lb.insert("end", os.path.normpath(d))

    def _add_file(self):
        fs = filedialog.askopenfilenames(parent=self, title="Add source file(s)")
        for f in fs:
            self._lb.insert("end", os.path.normpath(f))

    def _add_selection(self):
        panel = self.manager.get_active_panel()
        paths = panel.get_all_selected() if hasattr(panel, "get_all_selected") else []
        if not paths:
            messagebox.showinfo(
                "Add selection",
                "Nothing is selected in the active panel.\n"
                "Mark some files/folders first (Ctrl+A selects all).",
                parent=self)
            return
        for p in paths:
            self._lb.insert("end", os.path.normpath(p))

    def _remove_selected(self):
        for i in reversed(self._lb.curselection()):
            self._lb.delete(i)

    def _browse_dest(self):
        d = filedialog.askdirectory(parent=self, title="Destination folder")
        if d:
            self.var_dest.set(os.path.normpath(d))

    def _dest_other_panel(self):
        panel = self.manager.get_inactive_panel()
        path  = getattr(panel, "current_path", "")
        if path:
            self.var_dest.set(path)

    # ── Save ────────────────────────────────────────────────────────────────
    def _save(self):
        name = self.var_name.get().strip()
        if not name:
            messagebox.showwarning("Preset", "Give the preset a name.", parent=self)
            return
        sources = list(self._lb.get(0, "end"))
        if not sources:
            messagebox.showwarning("Preset", "Add at least one source.",
                                   parent=self)
            return
        dest = self.var_dest.get().strip()
        if not dest:
            messagebox.showwarning("Preset", "Set a destination.", parent=self)
            return
        conflict = next((m for lbl, m in _CONFLICT_CHOICES
                         if lbl == self.var_conf.get()), "overwrite_all")
        preset = {
            "name":      name,
            "sources":   sources,
            "dest":      dest,
            "mode":      self.var_mode.get(),
            "conflict":  conflict,
            "subfolder": self.var_sub.get().strip(),
            "dated":     bool(self.var_dated.get()),
        }
        presets = _load_transfer_presets()
        if self.edit_idx is not None and 0 <= self.edit_idx < len(presets):
            presets[self.edit_idx] = preset
        else:
            presets.append(preset)
        _save_transfer_presets(presets)
        try:
            self.parent.reload()
        except Exception:
            pass
        self.destroy()


# ══════════════════════════════════════════════════════════════════════════
#  DEL 35d — Smart-queue conflict rules  (auto clash policy per source→dest)
# ══════════════════════════════════════════════════════════════════════════
#
# A rule says: when you copy/move FROM one folder TO another (optionally only
# while a given Workspace is loaded), resolve name clashes automatically with a
# fixed policy — e.g. "from D:\Subs to \\TOWER\Subs, always Overwrite older".
# Then F5/F6 never stop to ask; the Task Queue just does the right thing.
# Matching lives in EditorFrame._match_conflict_rule.

class ConflictRulesWindow(tk.Toplevel):
    """Manage the automatic conflict-resolution rules used by copy/move."""

    def __init__(self, manager: "EditorFrame"):
        super().__init__(manager)
        self.manager = manager
        self.configure(bg=C_BG)
        self.geometry("820x440")
        _setup_toplevel(self, "Smart-queue conflict rules", manager, modal=False)
        self.rules = _load_conflict_rules()
        self._build_ui()
        self._render()

    def _build_ui(self):
        head = tk.Frame(self, bg=C_BG3)
        head.pack(fill="x")
        tk.Label(head, text="⚖  Conflict rules", bg=C_BG3, fg=C_ACCENT,
                 font=("Segoe UI", 12, "bold")).pack(side="left", padx=10, pady=7)
        tk.Label(head,
                 text="Auto-resolve name clashes for a source→destination "
                      "(optionally per Workspace)",
                 bg=C_BG3, fg=C_FG_DIM, font=("Segoe UI", 9)).pack(side="left")

        bar = tk.Frame(self, bg=C_BG)
        bar.pack(fill="x", padx=10, pady=(8, 2))
        tk.Button(bar, text="＋  New rule", bg="lightgreen", fg="black",
                  activebackground="lightgreen",
                  command=self._new).pack(side="left")
        tk.Button(bar, text="🔎  Which rule wins?", bg="white", fg="black",
                  activebackground="white",
                  command=self._explain).pack(side="left", padx=6)
        tk.Button(bar, text="Close", bg="grey", fg="white", width=9,
                  activebackground="grey",
                  command=self.destroy).pack(side="right")

        mid = tk.Frame(self, bg=C_BG)
        mid.pack(fill="both", expand=True, padx=10, pady=4)
        canvas = tk.Canvas(mid, bg=C_BG, highlightthickness=0)
        sb = ttk.Scrollbar(mid, orient="vertical", command=canvas.yview)
        canvas.configure(yscrollcommand=sb.set)
        sb.pack(side="right", fill="y")
        canvas.pack(side="left", fill="both", expand=True)
        self._inner = tk.Frame(canvas, bg=C_BG)
        self._inner_id = canvas.create_window((0, 0), window=self._inner,
                                              anchor="nw")
        self._inner.bind("<Configure>",
            lambda e: canvas.configure(scrollregion=canvas.bbox("all")))
        canvas.bind("<Configure>",
            lambda e: canvas.itemconfig(self._inner_id, width=e.width))
        canvas.bind("<MouseWheel>",
            lambda e: canvas.yview_scroll(-1 * (e.delta // 120), "units"))

    def _render(self):
        for w in self._inner.winfo_children():
            w.destroy()
        self._render_overlaps()
        if not self.rules:
            tk.Label(self._inner,
                     text="No rules yet.  Click  “＋ New rule”  to make copy/move "
                          "resolve clashes automatically for a folder pair.\n"
                          "Leave Source or Destination blank to mean “any”.",
                     bg=C_BG, fg=C_FG_DIM, font=("Segoe UI", 10),
                     wraplength=740, justify="left").pack(anchor="w", pady=20)
            return
        for idx, r in enumerate(self.rules):
            self._render_row(idx, r)

    def _render_overlaps(self):
        """Which rules cut into each other — asked for in so many words.

        A rule list is not a chain where the first one fires and the rest are
        never consulted: folder paths NEST, so one transfer can be described by
        several rules at once and the program has to choose.  This says which
        pairs describe the same ground and then disagree, before one of them
        surprises him."""
        try:
            pairs = _conflict_rule_overlaps(self.rules)
        except Exception:
            pairs = []
        if not pairs:
            return
        box = tk.Frame(self._inner, bg="#3a2f1a", padx=8, pady=6)
        box.pack(fill="x", pady=(0, 6))
        tk.Label(box,
                 text=f"⚠  {len(pairs)} pair(s) of rules cover the same folders "
                      f"and disagree",
                 bg="#3a2f1a", fg="#e8a33d",
                 font=("Segoe UI", 9, "bold"), anchor="w").pack(anchor="w")
        tk.Label(box,
                 text="Rules are not a chain — folder paths nest, so a transfer "
                      "can match several at once and one has to be chosen.  The "
                      "most specific wins; a Workspace on a rule can keep it out "
                      "of the running entirely.",
                 bg="#3a2f1a", fg=C_FG_DIM, font=("Segoe UI", 8), anchor="w",
                 wraplength=740, justify="left").pack(anchor="w", pady=(2, 4))
        for i, j, why in pairs[:12]:
            a, b = self.rules[i], self.rules[j]

            def _one(r):
                ws = (r.get("workspace") or "").strip()
                return (f"{_CONFLICT_LABEL.get(r.get('conflict',''), r.get('conflict',''))}"
                        f"   {r.get('src') or '(any)'} → {r.get('dst') or '(any)'}"
                        + (f"   [{ws}]" if ws else ""))

            tk.Label(box, text=f"•  #{i}  {_one(a)}", bg="#3a2f1a", fg=C_FG,
                     font=("Consolas", 8), anchor="w", wraplength=740,
                     justify="left").pack(anchor="w")
            tk.Label(box, text=f"   #{j}  {_one(b)}", bg="#3a2f1a", fg=C_FG,
                     font=("Consolas", 8), anchor="w", wraplength=740,
                     justify="left").pack(anchor="w")
            tk.Label(box, text=f"       └─ {why}", bg="#3a2f1a", fg=C_FG_DIM,
                     font=("Segoe UI", 8), anchor="w", wraplength=740,
                     justify="left").pack(anchor="w", pady=(0, 4))
        if len(pairs) > 12:
            tk.Label(box, text=f"   … and {len(pairs) - 12} more",
                     bg="#3a2f1a", fg=C_FG_DIM,
                     font=("Segoe UI", 8), anchor="w").pack(anchor="w")

    def _render_row(self, idx: int, r: dict):
        row = tk.Frame(self._inner, bg=C_BG2, padx=8, pady=6)
        row.pack(fill="x", pady=3)

        enabled = r.get("enabled", True)
        var = tk.BooleanVar(value=enabled)
        def _toggle(i=idx, v=var):
            self.rules[i]["enabled"] = bool(v.get())
            _save_conflict_rules(self.rules)
        # fg matters: the tick itself is drawn in the FOREGROUND colour, and the
        # default (black) on a dark indicator is invisible — an enabled rule
        # looked switched off.
        tk.Checkbutton(row, variable=var, bg=C_BG2, activebackground=C_BG2,
                       fg=C_FG, activeforeground=C_FG,
                       selectcolor=C_BG, command=_toggle).pack(side="left")

        left = tk.Frame(row, bg=C_BG2)
        left.pack(side="left", fill="x", expand=True, padx=(4, 0))
        ws = (r.get("workspace", "") or "").strip()
        ws_txt = f"[{ws}]  " if ws else ""
        conf = _CONFLICT_LABEL.get(r.get("conflict", ""), r.get("conflict", ""))
        title = f"{ws_txt}{r.get('src','(any)') or '(any)'}  →  {r.get('dst','(any)') or '(any)'}"
        tk.Label(left, text=title, bg=C_BG2, fg=(C_FG if enabled else C_FG_DIM),
                 font=("Segoe UI", 9, "bold"), anchor="w",
                 wraplength=520, justify="left").pack(anchor="w")
        tk.Label(left, text=f"On clash:  {conf}", bg=C_BG2, fg=C_FG_DIM,
                 font=("Segoe UI", 8), anchor="w").pack(anchor="w")
        # A whole-tree rule that DESTROYS the old file governs every folder
        # under it, including the ones with a careful rule of their own —
        # so it says so, instead of being one more grey line in the list.
        if _rule_is_catch_all(r) and r.get("conflict") in _DESTRUCTIVE_MODES:
            tk.Label(left,
                     text="⚠  Covers a whole drive or the whole tree, and "
                          "destroys the old file — it governs every folder "
                          "underneath.",
                     bg=C_BG2, fg="#e8a33d", font=("Segoe UI", 8),
                     anchor="w", wraplength=520,
                     justify="left").pack(anchor="w")

        btns = tk.Frame(row, bg=C_BG2)
        btns.pack(side="right")
        tk.Button(btns, text="✎ Edit", bg="white", fg="black", width=7,
                  activebackground="white",
                  command=lambda i=idx: self._edit(i)).pack(side="left", padx=2)
        tk.Button(btns, text="🗑", bg="grey", fg="white", width=3,
                  activebackground="grey",
                  command=lambda i=idx: self._delete(i)).pack(side="left", padx=2)

    def _explain(self):
        """"Which rule wins?" — the answer for one concrete transfer (revBF).

        A rule that "does nothing" is almost never a rule that failed to match:
        it matched and something else out-ranked it, or the Workspace it is
        scoped to is not loaded.  Neither is visible anywhere, which is how a
        Backup-rename rule silently became an Overwrite for a whole evening.
        This shows every rule whose FOLDERS cover the transfer, in the order
        they are considered, and says out loud why each one lost."""
        ConflictRuleExplainWindow(self, self.manager)

    def _new(self):
        ConflictRuleEditor(self, self.manager, rule=None)

    def _edit(self, idx: int):
        if 0 <= idx < len(self.rules):
            ConflictRuleEditor(self, self.manager, rule=self.rules[idx],
                               edit_idx=idx)

    def _delete(self, idx: int):
        if 0 <= idx < len(self.rules):
            if _ask_yes_no("Delete rule", "Delete this rule?", parent=self):
                del self.rules[idx]
                _save_conflict_rules(self.rules)
                self._render()
                try:
                    self.manager._rules_btn_sync(force=True)
                except Exception:
                    pass

    def reload(self):
        self.rules = _load_conflict_rules()
        self._render()
        # The ⚖ Rules button on the Workspace bar is about the folder pair in
        # the panels; a rule just saved or deleted can change whether it is lit.
        try:
            self.manager._rules_btn_sync(force=True)
        except Exception:
            pass


class MakeImageWindow(tk.Toplevel):
    """💿 Create an ISO / IMG image from the selection (DEL 53).

    Deliberately NOT routed through the Task Queue: that queue is about copies
    and moves between two folders, and an image is ONE output file built from
    many inputs.  It gets its own window with its own progress and its own
    Cancel — which also means a half-written image is deleted rather than left
    behind looking like a finished one."""

    def __init__(self, manager: "EditorFrame", sources: list):
        super().__init__(manager)
        self.manager = manager
        self.sources = list(sources)
        self.configure(bg=C_BG)
        self.geometry("760x430")
        _setup_toplevel(self, "💿  Create ISO / IMG image", manager, modal=False)
        self._cancel = threading.Event()
        self._thread = None
        self._done = []
        self._build()

    def _build(self):
        head = tk.Frame(self, bg=C_BG3)
        head.pack(fill="x")
        tk.Label(head, text="💿  Create ISO / IMG image", bg=C_BG3,
                 fg=C_ACCENT, font=("Segoe UI", 12, "bold")).pack(
            side="left", padx=10, pady=7)

        n_files = sum(1 for s in self.sources if os.path.isfile(s))
        n_dirs = len(self.sources) - n_files
        tk.Label(self,
                 text=f"{len(self.sources)} item(s) selected "
                      f"({n_files} file(s), {n_dirs} folder(s)).  A folder goes "
                      f"in whole, with everything under it.",
                 bg=C_BG, fg=C_FG_DIM, font=("Segoe UI", 9), anchor="w",
                 wraplength=720, justify="left").pack(fill="x", padx=12,
                                                      pady=(10, 6))

        form = tk.Frame(self, bg=C_BG)
        form.pack(fill="x", padx=12)
        first = self.sources[0] if self.sources else ""
        stem = os.path.basename(first.rstrip("\\/")) or "image"
        stem = os.path.splitext(stem)[0]
        try:
            dest_dir = self.manager.get_inactive_panel().current_path
        except Exception:
            dest_dir = os.path.expanduser("~")
        self.var_out = tk.StringVar(value=os.path.join(dest_dir, stem + ".iso"))
        self.var_label = tk.StringVar(value=stem[:32].upper() or "DATA")

        tk.Label(form, text="Image file:", bg=C_BG, fg=C_FG,
                 font=("Segoe UI", 9)).grid(row=0, column=0, sticky="w", pady=3)
        tk.Entry(form, textvariable=self.var_out, bg=C_BG2, fg=C_FG,
                 insertbackground=C_FG, insertofftime=0, insertontime=9999999,
                 relief="flat").grid(row=0, column=1, sticky="we", padx=6)
        tk.Button(form, text="Browse…", bg="white", fg="black",
                  activebackground="white", command=self._browse).grid(
            row=0, column=2, padx=2)

        tk.Label(form, text="Volume label:", bg=C_BG, fg=C_FG,
                 font=("Segoe UI", 9)).grid(row=1, column=0, sticky="w", pady=3)
        tk.Entry(form, textvariable=self.var_label, bg=C_BG2, fg=C_FG,
                 insertbackground=C_FG, insertofftime=0, insertontime=9999999,
                 relief="flat", width=34).grid(row=1, column=1, sticky="w",
                                               padx=6)
        form.columnconfigure(1, weight=1)

        tk.Label(self,
                 text="A data image is the same bytes either way — .iso and "
                      ".img differ only in the name.  Windows mounts it "
                      "directly (right-click ▸ Mount), and this program browses "
                      "it like any other archive.  It is not a bootable disc.",
                 bg=C_BG, fg=C_FG_DIM, font=("Segoe UI", 8), anchor="w",
                 wraplength=720, justify="left").pack(fill="x", padx=12,
                                                      pady=(8, 4))

        self.status = tk.StringVar(value="Ready.")
        tk.Label(self, textvariable=self.status, bg=C_BG, fg=C_FG,
                 font=("Consolas", 9), anchor="w").pack(fill="x", padx=12)
        self.bar = ttk.Progressbar(self, mode="determinate", maximum=1000)
        self.bar.pack(fill="x", padx=12, pady=(4, 8))

        self.log = tk.Text(self, height=6, bg=C_BG2, fg=C_FG_DIM, wrap="word",
                           relief="flat", insertofftime=0, insertontime=9999999,
                           highlightthickness=0, borderwidth=0,
                           font=("Consolas", 8))
        self.log.pack(fill="both", expand=True, padx=12, pady=(0, 6))

        btns = tk.Frame(self, bg=C_BG)
        btns.pack(fill="x", padx=12, pady=(0, 10))
        self.btn_go = tk.Button(btns, text="💿  Create image", bg="lightgreen",
                                fg="black", activebackground="lightgreen",
                                command=self._start)
        self.btn_go.pack(side="left")
        tk.Button(btns, text="Close", bg="grey", fg="white", width=9,
                  activebackground="grey", command=self._close).pack(side="right")

    def _browse(self):
        p = filedialog.asksaveasfilename(
            parent=self, title="Save the image as",
            defaultextension=".iso",
            initialfile=os.path.basename(self.var_out.get()),
            initialdir=os.path.dirname(self.var_out.get()),
            filetypes=[("ISO image", "*.iso"), ("IMG image", "*.img"),
                       ("All files", "*.*")])
        if p:
            self.var_out.set(p)

    def _say(self, line):
        try:
            self.log.insert("end", line + "\n")
            self.log.see("end")
        except Exception:
            pass

    def _start(self):
        if self._thread is not None and self._thread.is_alive():
            self._cancel.set()
            self.status.set("Cancelling…")
            return
        out = self.var_out.get().strip()
        if not out:
            self._say("Give the image a file name first.")
            return
        if os.path.exists(out) and not _ask_yes_no(
                "Create image",
                f"{os.path.basename(out)} already exists.\n\nReplace it?",
                parent=self):
            return
        try:
            os.makedirs(os.path.dirname(out) or ".", exist_ok=True)
        except Exception as exc:
            self._say(f"Cannot write there: {exc}")
            return

        builder = IsoBuilder(self.var_label.get())
        self._say("Reading the selection…")
        for s in self.sources:
            builder.add(s)
        nf, nd, nbytes = builder.totals()
        self._say(f"{nf} file(s), {nd} folder(s), {_human_size(nbytes)} of data")
        if not nf and not nd:
            self._say("Nothing to put in the image.")
            return
        # Free space on the destination — an image is as big as its contents,
        # and finding that out at 90 % is no use to anybody.
        free = _free_space(os.path.dirname(out) or ".")
        if 0 <= free < nbytes + 512 * 1024:
            self._say(f"⚠  Only {_human_size(free)} free where the image goes, "
                      f"and it needs about {_human_size(nbytes)}.")
        self._cancel.clear()
        self._done = []
        self.btn_go.config(text="■  Cancel", bg="#e8a33d")
        started = _time.time()

        def work():
            okw = builder.write(
                out,
                progress=lambda d, t, n: self._done.append((d, t, n)),
                is_cancelled=self._cancel.is_set)
            self._done.append(("END", okw, started))

        self._thread = threading.Thread(target=work, daemon=True)
        self._thread.start()
        # after() is started HERE, on the main thread — a worker's after() only
        # fires while mainloop happens to be running, which is how the last
        # update goes missing.
        self.after(120, lambda: self._drain(builder, out))

    def _drain(self, builder, out):
        end = last = None
        while self._done:
            item = self._done.pop(0)
            if item[0] == "END":
                end = item
            else:
                last = item
        if last:
            d, t, name = last
            try:
                self.bar["value"] = int(1000 * d / t) if t else 0
                self.status.set(f"{_human_size(d)} / {_human_size(t)}"
                                f"   ·   {name}")
            except Exception:
                pass
        if end is None:
            if self._thread is not None and self._thread.is_alive():
                self.after(120, lambda: self._drain(builder, out))
            return
        _, okw, started = end
        self.btn_go.config(text="💿  Create image", bg="lightgreen")
        for w in builder.warnings:
            self._say("⚠  " + w)
        if not okw:
            self.bar["value"] = 0
            self.status.set("Cancelled — the half-written image was deleted.")
            self._say("Cancelled.")
            return
        self.bar["value"] = 1000
        secs = max(0.1, _time.time() - started)
        size = os.path.getsize(out) if os.path.exists(out) else 0
        self.status.set(f"Done — {_human_size(size)} in {secs:.1f} s")
        self._say(f"Written: {out}")
        try:
            self.manager.refresh_panels()
        except Exception:
            pass

    def _close(self):
        self._cancel.set()
        self.destroy()


class PairRulesWindow(tk.Toplevel):
    """The ⚖ Rules button — the rules for the two folders in the panels.

    Everything here is about ONE pair of folders, both ways round.  A rule is
    otherwise invisible until it has already done something you did not want,
    and writing one down meant queueing a transfer first just to be asked the
    question.  From here you can see what governs the pair you are standing in
    and write a rule for it on the spot."""

    def __init__(self, manager: "EditorFrame"):
        super().__init__(manager)
        self.manager = manager
        self.configure(bg=C_BG)
        self.geometry("880x480")
        _setup_toplevel(self, "⚖  Rules for these two folders", manager,
                        modal=False)
        try:
            self.left  = manager.left_panel.current_path
            self.right = manager.right_panel.current_path
        except Exception:
            self.left = self.right = ""
        self._build()
        self._render()

    def _build(self):
        head = tk.Frame(self, bg=C_BG3)
        head.pack(fill="x")
        tk.Label(head, text="⚖  Rules for these two folders", bg=C_BG3,
                 fg=C_ACCENT, font=("Segoe UI", 12, "bold")).pack(
            side="left", padx=10, pady=7)

        paths = tk.Frame(self, bg=C_BG)
        paths.pack(fill="x", padx=10, pady=(8, 2))
        for label, path in (("LEFT ", self.left), ("RIGHT", self.right)):
            row = tk.Frame(paths, bg=C_BG)
            row.pack(fill="x")
            tk.Label(row, text=label, bg=C_BG, fg=C_FG_DIM,
                     font=("Consolas", 9)).pack(side="left")
            tk.Label(row, text="  " + (path or "(nothing)"), bg=C_BG, fg=C_FG,
                     font=("Consolas", 9), anchor="w").pack(side="left")

        bar = tk.Frame(self, bg=C_BG)
        bar.pack(fill="x", padx=10, pady=(8, 2))
        tk.Button(bar, text="＋  New rule   LEFT → RIGHT", bg="lightgreen",
                  fg="black", activebackground="lightgreen",
                  command=lambda: self._new(self.left, self.right)
                  ).pack(side="left")
        tk.Button(bar, text="＋  New rule   RIGHT → LEFT", bg="lightgreen",
                  fg="black", activebackground="lightgreen",
                  command=lambda: self._new(self.right, self.left)
                  ).pack(side="left", padx=6)
        tk.Button(bar, text="All rules…", bg="white", fg="black",
                  activebackground="white",
                  command=self._all_rules).pack(side="left", padx=6)
        tk.Button(bar, text="Close", bg="grey", fg="white", width=9,
                  activebackground="grey",
                  command=self.destroy).pack(side="right")

        self._body = tk.Frame(self, bg=C_BG)
        self._body.pack(fill="both", expand=True, padx=10, pady=6)

    def _render(self):
        for w in self._body.winfo_children():
            w.destroy()
        hits = []
        try:
            hits = self.manager._pair_rule_hits(self.left, self.right)
        except Exception:
            hits = []
        if not hits:
            tk.Label(self._body,
                     text="No rule covers these two folders.\n\n"
                          "A copy or move between them will stop and ASK you "
                          "what to do when a name clashes.\nMake a rule with "
                          "the green buttons above and it will not ask again.",
                     bg=C_BG, fg=C_FG_DIM, font=("Segoe UI", 10),
                     justify="left", anchor="w").pack(anchor="w", pady=16)
            return

        loaded = sorted({v for v in getattr(self.manager, "_ws_name", {}).values()
                         if v})
        tk.Label(self._body,
                 text="Workspace loaded right now:  "
                      + (", ".join(loaded) if loaded else "(none)"),
                 bg=C_BG, fg=C_FG_DIM, font=("Segoe UI", 9),
                 anchor="w").pack(anchor="w", pady=(0, 6))

        # One winner PER DIRECTION — a rule that loses left→right may well be
        # the one that acts right→left, and calling it "beaten" there would be
        # a plain lie.
        winners = {}
        for h in hits:
            if h["ws_ok"] and h["arrow"] not in winners:
                winners[h["arrow"]] = h

        for h in hits:
            r   = h["rule"]
            ws  = (r.get("workspace") or "").strip()
            win = winners.get(h["arrow"]) is h
            row = tk.Frame(self._body, bg=C_BG2, padx=8, pady=5)
            row.pack(fill="x", pady=2)
            if win:
                state, colour = "USED", "#7ee787"
            elif not h["ws_ok"]:
                state, colour = "skipped", "#e8a33d"
            else:
                state, colour = "beaten", C_FG_DIM
            top = tk.Frame(row, bg=C_BG2)
            top.pack(fill="x")
            tk.Label(top, text=f"{state:<8}", bg=C_BG2, fg=colour,
                     font=("Consolas", 9, "bold")).pack(side="left")
            tk.Label(top, text=f" {h['arrow']}  "
                     + _CONFLICT_LABEL.get(r.get("conflict", ""),
                                           r.get("conflict", "")),
                     bg=C_BG2, fg=C_FG,
                     font=("Segoe UI", 9, "bold")).pack(side="left")
            tk.Button(top, text="✎ Edit", bg="white", fg="black", width=7,
                      activebackground="white",
                      command=lambda i=h["index"]: self._edit(i)).pack(side="right")
            tk.Label(row,
                     text=f"{r.get('src') or '(any)'}  →  {r.get('dst') or '(any)'}"
                          + (f"   [{ws}]" if ws else "   [any Workspace]"),
                     bg=C_BG2, fg=C_FG_DIM, font=("Consolas", 8),
                     anchor="w", wraplength=760, justify="left").pack(anchor="w")
            if not h["ws_ok"]:
                tk.Label(row,
                         text=f"└─ not consulted: it only applies in Workspace "
                              f"\"{ws}\", which is not loaded.  Clear that box "
                              f"to make it apply everywhere.",
                         bg=C_BG2, fg="#e8a33d", font=("Segoe UI", 8),
                         anchor="w", wraplength=760,
                         justify="left").pack(anchor="w")
            elif not win:
                tk.Label(row,
                         text="└─ another rule pins these folders down more "
                              "precisely.",
                         bg=C_BG2, fg=C_FG_DIM, font=("Segoe UI", 8),
                         anchor="w").pack(anchor="w")
            if _rule_is_catch_all(r) and r.get("conflict") in _DESTRUCTIVE_MODES:
                tk.Label(row,
                         text="⚠  Covers a whole drive or the whole tree and "
                              "destroys the old file.",
                         bg=C_BG2, fg="#e8a33d", font=("Segoe UI", 8),
                         anchor="w").pack(anchor="w")

    # ── actions ───────────────────────────────────────────────────────────
    def _new(self, src, dst):
        if not src or not dst:
            return
        ConflictRuleEditor(self, self.manager,
                           rule={"src": src, "dst": dst,
                                 "workspace": "", "conflict": "backup_old",
                                 "enabled": True})

    def _edit(self, idx):
        rules = _load_conflict_rules()
        if 0 <= idx < len(rules):
            ConflictRuleEditor(self, self.manager, rule=rules[idx],
                               edit_idx=idx)

    def _all_rules(self):
        try:
            self.manager.open_conflict_rules()
        except Exception:
            pass

    def reload(self):
        """Called by ConflictRuleEditor after it saves."""
        self._render()
        try:
            self.manager._rules_btn_sync(force=True)
        except Exception:
            pass


class ConflictRuleExplainWindow(tk.Toplevel):
    """"Which rule wins?" — why a transfer resolves the way it does.

    Pre-filled with the two panels as they stand, so the common question
    ("why did THIS copy overwrite?") is one click away."""

    def __init__(self, parent: "ConflictRulesWindow", manager: "EditorFrame"):
        super().__init__(parent)
        self.manager = manager
        self.configure(bg=C_BG)
        self.geometry("900x520")
        _setup_toplevel(self, "Which rule wins?", parent, modal=False)

        try:
            src0 = manager.get_active_panel().current_path
            dst0 = manager.get_inactive_panel().current_path
        except Exception:
            src0 = dst0 = ""
        self.var_src = tk.StringVar(value=src0 or "")
        self.var_dst = tk.StringVar(value=dst0 or "")

        head = tk.Frame(self, bg=C_BG3)
        head.pack(fill="x")
        tk.Label(head, text="🔎  Which rule wins?", bg=C_BG3, fg=C_ACCENT,
                 font=("Segoe UI", 12, "bold")).pack(side="left", padx=10, pady=7)

        form = tk.Frame(self, bg=C_BG)
        form.pack(fill="x", padx=10, pady=(8, 4))
        for row, (label, var) in enumerate((("Copy FROM folder:", self.var_src),
                                            ("Copy TO folder:",   self.var_dst))):
            tk.Label(form, text=label, bg=C_BG, fg=C_FG,
                     font=("Segoe UI", 9)).grid(row=row, column=0, sticky="w",
                                                pady=2)
            tk.Entry(form, textvariable=var, bg=C_BG2, fg=C_FG,
                     insertbackground=C_FG, insertofftime=0,
                     insertontime=9999999,
                     relief="flat").grid(row=row, column=1, sticky="we",
                                         padx=6, pady=2)
        form.columnconfigure(1, weight=1)
        tk.Button(form, text="Test", bg="white", fg="black", width=10,
                  activebackground="white",
                  command=self._run).grid(row=0, column=2, rowspan=2, padx=4)

        self.out = tk.Text(self, bg=C_BG2, fg=C_FG, wrap="word",
                           relief="flat", insertbackground=C_FG,
                           insertofftime=0, insertontime=9999999,
                           highlightthickness=0, borderwidth=0,
                           font=("Consolas", 9))
        sb = ttk.Scrollbar(self, orient="vertical", command=self.out.yview)
        self.out.configure(yscrollcommand=sb.set)
        tk.Button(self, text="Close", bg="grey", fg="white", width=9,
                  activebackground="grey",
                  command=self.destroy).pack(side="bottom", pady=6)
        sb.pack(side="right", fill="y")
        self.out.pack(side="left", fill="both", expand=True, padx=(10, 0),
                      pady=(0, 6))
        self._run()

    def _say(self, line=""):
        self.out.insert("end", line + "\n")

    def _run(self):
        self.out.configure(state="normal")
        self.out.delete("1.0", "end")
        src = self.var_src.get().strip()
        dst = self.var_dst.get().strip()
        if not src or not dst:
            self._say("Fill in both folders.")
            self.out.configure(state="disabled")
            return
        mgr = self.manager
        loaded = sorted({v for v in getattr(mgr, "_ws_name", {}).values() if v})
        self._say(f"FROM  {src}")
        self._say(f"TO    {dst}")
        self._say("Workspace loaded right now:  "
                  + (", ".join(loaded) if loaded else "(none)"))
        self._say()
        # A rule is matched against the folder a file comes FROM, so a file
        # name has to be on the end for the scan to see the folder.
        probe = [os.path.join(src, "any-file")]
        try:
            cands = mgr._conflict_rule_candidates(probe, dst)
        except Exception as exc:
            self._say(f"Could not read the rules: {exc}")
            self.out.configure(state="disabled")
            return
        if not cands:
            self._say("NO RULE covers this pair of folders — the copy will ask "
                      "you what to do on a clash.")
            self.out.configure(state="disabled")
            return
        winner = next((c for c in cands if c["ws_ok"]), None)
        if winner:
            r = winner["rule"]
            self._say("WINNER:  "
                      + _CONFLICT_LABEL.get(r.get("conflict", ""),
                                            r.get("conflict", "")))
            self._say(f"         {r.get('src') or '(any)'}  →  "
                      f"{r.get('dst') or '(any)'}"
                      + (f"   [{r.get('workspace')}]"
                         if (r.get('workspace') or '').strip() else ""))
        else:
            self._say("NO RULE APPLIES — every rule that covers these folders "
                      "is scoped to a Workspace that is not loaded, so the "
                      "copy will ask you.")
        self._say()
        self._say("All rules covering these folders, most specific first:")
        self._say("-" * 78)
        for c in cands:
            r  = c["rule"]
            ws = (r.get("workspace") or "").strip()
            if c is winner:
                mark = "USED   "
            elif not c["ws_ok"]:
                mark = "skipped"
            else:
                mark = "beaten "
            self._say(f"  {mark} #{c['index']:<3} "
                      f"{_CONFLICT_LABEL.get(r.get('conflict',''), r.get('conflict','')):<20}"
                      f" {r.get('src') or '(any)'}  →  {r.get('dst') or '(any)'}")
            if not c["ws_ok"]:
                self._say(f"          └─ skipped: it only applies in Workspace "
                          f"\"{ws}\", which is not loaded.")
            elif c is not winner:
                self._say("          └─ another rule pins these folders down "
                          "more precisely.")
            if _rule_is_catch_all(r) and r.get("conflict") in _DESTRUCTIVE_MODES:
                self._say("          ⚠  This rule covers a WHOLE DRIVE OR TREE "
                          "and destroys the old file.")
        self._say()
        self._say("A rule that is 'skipped' matched the folders perfectly — it "
                  "was the Workspace that kept it out.  Clear the Workspace "
                  "box on that rule to make it apply everywhere.")
        self.out.configure(state="disabled")


class ConflictRuleEditor(tk.Toplevel):
    """Create or edit one conflict rule."""

    def __init__(self, parent: "ConflictRulesWindow", manager: "EditorFrame",
                 rule: dict = None, edit_idx: int = None):
        super().__init__(parent)
        self.parent   = parent
        self.manager  = manager
        self.edit_idx = edit_idx
        self.configure(bg=C_BG)
        self.geometry("620x360")
        _setup_toplevel(self, "Edit rule" if rule else "New rule", parent,
                        modal=False)
        r = rule or {}
        self.var_src  = tk.StringVar(value=r.get("src", ""))
        self.var_dst  = tk.StringVar(value=r.get("dst", ""))
        self.var_ws   = tk.StringVar(value=r.get("workspace", "") or "(any)")
        self.var_conf = tk.StringVar(
            value=_CONFLICT_LABEL.get(r.get("conflict", "overwrite_older"),
                                      "Overwrite older"))
        self.var_en   = tk.BooleanVar(value=bool(r.get("enabled", True)))
        self._build_ui()

    def _build_ui(self):
        body = tk.Frame(self, bg=C_BG)
        body.pack(fill="both", expand=True, padx=12, pady=10)

        def _path_row(label, var, other_getter):
            tk.Label(body, text=label, bg=C_BG, fg=C_FG, anchor="w").pack(fill="x")
            wrap = tk.Frame(body, bg=C_BG)
            wrap.pack(fill="x", pady=(0, 8))
            tk.Entry(wrap, textvariable=var, bg=C_BG2, fg=C_FG,
                     insertbackground=C_FG, insertofftime=0,
                     insertontime=9999999).pack(side="left", fill="x", expand=True)
            tk.Button(wrap, text="Browse…", bg="white", fg="black",
                      activebackground="white",
                      command=lambda: self._browse(var)).pack(side="left", padx=(4, 0))
            tk.Button(wrap, text="Use panel", bg="white", fg="black",
                      activebackground="white",
                      command=lambda: var.set(other_getter())).pack(side="left",
                                                                    padx=(4, 0))
            # One folder UP.  A rule already covers everything under the folder
            # it names, so climbing one level is how you make it cover the dated
            # sub-folders that get made from now on ("…\Claude_working\2026-…")
            # without writing a new rule for each of them.
            tk.Button(wrap, text="▲ up", bg="white", fg="black", width=5,
                      activebackground="white",
                      command=lambda: self._up_one(var)).pack(side="left",
                                                              padx=(4, 0))

        _path_row("Source folder  (blank = any, and it always covers sub-folders):",
                  self.var_src,
                  lambda: getattr(self.manager.get_active_panel(),
                                  "current_path", ""))
        _path_row("Destination folder  (blank = any):", self.var_dst,
                  lambda: getattr(self.manager.get_inactive_panel(),
                                  "current_path", ""))

        # Workspace scope
        ws_row = tk.Frame(body, bg=C_BG)
        ws_row.pack(fill="x", pady=(0, 6))
        tk.Label(ws_row, text="Workspace:", bg=C_BG, fg=C_FG,
                 width=12, anchor="w").pack(side="left")
        ws_names = ["(any)"] + list(getattr(self.manager, "workspaces", {}).keys())
        ttk.Combobox(ws_row, textvariable=self.var_ws, values=ws_names,
                     width=24, state="readonly").pack(side="left")

        # Conflict policy
        conf_row = tk.Frame(body, bg=C_BG)
        conf_row.pack(fill="x", pady=(0, 6))
        tk.Label(conf_row, text="On clash:", bg=C_BG, fg=C_FG,
                 width=12, anchor="w").pack(side="left")
        ttk.Combobox(conf_row, textvariable=self.var_conf,
                     values=[lbl for lbl, _m in _CONFLICT_CHOICES],
                     width=22, state="readonly").pack(side="left")

        tk.Checkbutton(body, text="Rule is enabled", variable=self.var_en,
                       bg=C_BG, fg=C_FG, selectcolor=C_BG2,
                       activebackground=C_BG,
                       activeforeground=C_FG).pack(anchor="w", pady=(2, 4))

        btn_row = tk.Frame(self, bg=C_BG)
        btn_row.pack(fill="x", padx=12, pady=(0, 12))
        tk.Button(btn_row, text="Save rule", bg="green", fg="white", width=14,
                  activebackground="green",
                  command=self._save).pack(side="left")
        tk.Button(btn_row, text="Cancel", bg="grey", fg="white", width=10,
                  activebackground="grey",
                  command=self.destroy).pack(side="right")
        self.bind("<Return>", lambda e: self._save())

    def _browse(self, var):
        d = filedialog.askdirectory(parent=self, title="Choose folder")
        if d:
            var.set(os.path.normpath(d))

    def _up_one(self, var):
        """Widen the typed path by one folder — never past the volume root."""
        cur = var.get().strip()
        if not cur:
            return
        wider = _rule_scope_path(cur, 1)
        if os.path.normcase(wider) == os.path.normcase(os.path.abspath(cur)):
            return                       # already at the root — nothing to do
        var.set(wider)

    def _save(self):
        conflict = next((m for lbl, m in _CONFLICT_CHOICES
                         if lbl == self.var_conf.get()), "overwrite_older")
        ws = self.var_ws.get().strip()
        if ws == "(any)":
            ws = ""
        rule = {
            "src":       self.var_src.get().strip(),
            "dst":       self.var_dst.get().strip(),
            "workspace": ws,
            "conflict":  conflict,
            "enabled":   bool(self.var_en.get()),
        }
        rules = _load_conflict_rules()
        if self.edit_idx is not None and 0 <= self.edit_idx < len(rules):
            rules[self.edit_idx] = rule
        else:
            rules.append(rule)
        _save_conflict_rules(rules)
        try:
            self.parent.reload()
        except Exception:
            pass
        self.destroy()


# ══════════════════════════════════════════════════════════════════════════
#  DEL 35e — Sub-folder tree jump  (Ctrl+Enter on a folder)
# ══════════════════════════════════════════════════════════════════════════
#
# A pop-up that shows the whole folder tree UNDER the chosen folder, so you can
# glide down to any level with the arrow keys (or a click) and jump straight
# there.  The tree is lazy-loaded — each branch is scanned only when you expand
# it — so it opens instantly even on a huge directory.

class DirTreePopup(tk.Toplevel):
    """Recursive sub-folder chooser opened with Ctrl+Enter on a folder."""

    def __init__(self, manager: "EditorFrame", panel, root_dir: str):
        super().__init__(manager)
        self.manager  = manager
        self.panel    = panel
        self.root_dir = root_dir
        self._path_of: dict = {}     # tree iid -> full folder path
        self.configure(bg=C_BG)
        self.geometry("560x520")
        base = os.path.basename(root_dir.rstrip("\\/")) or root_dir
        _setup_toplevel(self, f"Go to — under  {base}", manager, modal=True)
        self._build_ui()
        # Position near the mouse so it feels like it sprang from the folder
        try:
            self.geometry(f"+{self.winfo_pointerx() - 40}"
                          f"+{max(0, self.winfo_pointery() - 30)}")
        except Exception:
            pass

    def _build_ui(self):
        hint = tk.Label(self,
                        text=f"↑↓ move · → expand · ← collapse · "
                             f"Enter / double-click = go there · Esc = cancel",
                        bg=C_BG3, fg=C_FG_DIM, font=("Segoe UI", 8), anchor="w")
        hint.pack(fill="x")

        wrap = tk.Frame(self, bg=C_BG)
        wrap.pack(fill="both", expand=True)
        self.tree = ttk.Treeview(wrap, show="tree", selectmode="browse")
        sb = ttk.Scrollbar(wrap, orient="vertical", command=self.tree.yview)
        self.tree.configure(yscrollcommand=sb.set)
        sb.pack(side="right", fill="y")
        self.tree.pack(side="left", fill="both", expand=True)

        bar = tk.Frame(self, bg=C_BG)
        bar.pack(fill="x")
        tk.Button(bar, text="Go there", bg="green", fg="white",
                  activebackground="green", command=self._go).pack(side="left",
                                                                    padx=6, pady=6)
        tk.Button(bar, text="Cancel", bg="grey", fg="white",
                  activebackground="grey", command=self.destroy).pack(side="right",
                                                                      padx=6, pady=6)

        # Populate the first level (children of root_dir)
        self._populate(self.root_dir, "")
        self.tree.bind("<<TreeviewOpen>>", self._on_open)
        self.tree.bind("<Return>",   lambda e: self._go())
        self.tree.bind("<Double-1>", lambda e: self._go())
        # Select the first row so the arrow keys work immediately
        kids = self.tree.get_children("")
        if kids:
            self.tree.selection_set(kids[0])
            self.tree.focus(kids[0])
        self.tree.focus_set()

    def _has_subdir(self, path: str) -> bool:
        try:
            return bool(self.panel._subdirs_sorted(path))
        except Exception:
            return False

    def _populate(self, path: str, parent_iid: str):
        """Insert the immediate sub-folders of *path* under *parent_iid*.  Each
        folder that itself has sub-folders gets a dummy child so the expand arrow
        shows; the dummy is replaced with real content the first time it opens."""
        for full in self.panel._subdirs_sorted(path):
            name = os.path.basename(full) or full
            iid = self.tree.insert(parent_iid, "end", text="  " + name, open=False)
            self._path_of[iid] = full
            if self._has_subdir(full):
                # Dummy placeholder (no path) → triggers the expand arrow
                self.tree.insert(iid, "end", text="")

    def _on_open(self, event=None):
        iid = self.tree.focus()
        kids = self.tree.get_children(iid)
        # A single child with no recorded path is the lazy-load placeholder
        if len(kids) == 1 and kids[0] not in self._path_of:
            self.tree.delete(kids[0])
            self._populate(self._path_of.get(iid, ""), iid)

    def _go(self):
        iid = self.tree.focus() or (self.tree.selection()[0]
                                    if self.tree.selection() else "")
        path = self._path_of.get(iid)
        if not path:
            # A placeholder / empty row was focused — ignore
            return
        if os.path.isdir(path):
            self.destroy()
            self.panel.change_directory(path)
            # Hand the keyboard back to the panel so the arrow keys work at once
            try:
                self.panel.tree.focus_set()
            except Exception:
                pass
        else:
            messagebox.showinfo("Go to", "That folder no longer exists.",
                                parent=self)


# ══════════════════════════════════════════════════════════════════════════
#  DEL 36 — Configurable toolbar
# ══════════════════════════════════════════════════════════════════════════
#
# The button row is data, not code: a list saved in toolbar.json.  A button is
# one of four things — a built-in action, one of the drop-down menus, a
# separator, or something the user invented (a shell command or a folder to
# jump to).

# action id → (label, EditorFrame method, default button text)
TOOLBAR_ACTIONS = {
    "go_up":            ("Go up one directory",       "go_up",                 "↑"),
    "go_root":          ("Go to drive root",          "go_root",               "↖"),
    "view":             ("View file",                 "view_file",             "F3"),
    "edit":             ("Edit file",                 "edit_file",             "F4"),
    "copy":             ("Copy",                      "copy_files",            "F5"),
    "move":             ("Move / rename",             "move_files",            "F6"),
    "new_folder":       ("New folder",                "new_folder",            "F7"),
    "delete":           ("Delete",                    "delete_files",          "Del"),
    "pair_cycle":       ("Cycle tab pairs (L+R)",     "_cycle_tab_pairs",      "F8"),
    "pack":             ("Pack archive",              "pack_files_as",         "F9"),
    "unpack":           ("Unpack archive",            "unpack_any",            "F10"),
    "rename":           ("Rename",                    "_rename_selected",      "F2"),
    "refresh":          ("Refresh panels",            "refresh_panels",        "⟳"),
    "properties":       ("Properties",                "show_properties",       "ℹ"),
    "folder_sizes":     ("Measure folder sizes (once)",
                                                      "calc_folder_sizes",     "📐"),
    "auto_folder_sizes": ("Folder sizes: always on / off",
                                                      "toggle_auto_folder_sizes", "📁"),
    "disk_overview":    ("Disk overview",             "_show_disk_overview",   "💽"),
    "settings":         ("Settings",                  "_show_settings",        "⚙"),
    "about":            ("About",                     "_show_about",           "ℹ"),
    "help":             ("Help",                      "_show_help",            "?"),
    "search":           ("Search",                    "open_search",           "🔍"),
    "queue":            ("Task queue  (click = next state)",
                                                      "_cycle_queue_top_mode", "⚡"),
    "compare_sides":    ("Which one is newest? (left vs right)",
                                                      "toggle_compare_sides",  "⚖"),
    "trash":            ("Trash",                     "open_trash",            "🗑"),
    "ftp":              ("FTP client",                "open_ftp_client",       "FTP"),
    "network":          ("Network scan",              "open_network_window",   "NET"),
    "shares":           ("Browse network shares",     "open_shares",           "🖧"),
    "cmd_admin":        ("Command Prompt (Admin)",    "open_cmd",              "CMD"),
    "ps_admin":         ("PowerShell (Admin)",        "open_powershell",       "PS"),
    "save_selection":   ("Save selection to file",    "save_selection_to_file", "💾"),
    "copy_paths":       ("Copy paths to clipboard",   "copy_paths_to_clipboard", "📋"),
    "copy_names":       ("Copy names to clipboard",   "copy_names_to_clipboard", "📋"),
    "copy_folders":     ("Copy folders to clipboard", "copy_folders_to_clipboard", "📋"),
    # Tools added in the Total Commander parity pass
    "transfer_presets": ("Transfer presets (1-click jobs)", "open_transfer_presets", "⇪"),
    "conflict_rules":   ("Smart-queue conflict rules",  "open_conflict_rules",   "⚖"),
    "pair_rules":       ("Rules for these two folders",
                                                      "open_pair_rules",       "⚖"),
    "make_image":       ("Create ISO / IMG image",     "make_image",            "💿"),
    "multi_rename":     ("Multi-Rename tool",         "open_multi_rename",     "✎"),
    "backup_rename":    ("Backup rename",             "backup_rename_selected", "🗂"),
    "compare_files":    ("Compare files",             "open_compare",          "⇄"),
    "sync_dirs":        ("Synchronize directories",   "open_sync",             "⇆"),
    "duplicates":       ("Find duplicate files",      "open_duplicates",       "⧉"),
    "quick_view":       ("Quick View panel",          "toggle_quick_view",     "👁"),
    "branch_view":      ("Branch view",               "toggle_branch_view",    "🌿"),
    "hotlist":          ("Directory hotlist",         "open_hotlist",          "⭐"),
    "checksums":        ("Checksums",                 "open_checksums",        "🔐"),
    "split_file":       ("Split file",                "open_split",            "✂"),
    "combine_files":    ("Combine split parts",       "open_combine",          "🔗"),
    "browse_archive":   ("Browse archive",            "open_archive_browser",  "📦"),
    "print_listing":    ("Print / export listing",    "open_print_listing",    "🖨"),
    "command_bar":      ("Command bar",               "toggle_command_bar",    ">_"),
    "command_library":  ("Command library",           "open_command_library",  "📚"),
    "auto_refresh":     ("Toggle auto-refresh",       "toggle_auto_refresh",   "🔄"),
    "shortcuts":        ("Configure shortcuts",       "open_shortcut_config",  "⌨"),
    "toolbar_config":   ("Configure toolbar",         "open_toolbar_config",   "🔧"),
    "palette":          ("Command palette",           "open_palette",          "⌘"),
    "undo_history":     ("Undo history",              "open_undo",             "↶"),
    "treemap":          ("Disk usage (treemap)",      "open_treemap",          "▦"),
    "tools_config":     ("Configure my tools (Send to)", "open_tools_config",  "🔌"),
    "tags":             ("File tags",                 "open_tags",             "🏷"),
    "flag_toggle":      ("Flag / unflag the selection (the ★ column)",
                                                      "toggle_flag_selected",  FLAG_CHAR),
    "dates_delete":     ("Dates & deletion settings", "open_dates_delete",     "🕒"),
    "relocator":        ("Relocator — tidy files away by rule",
                                                      "open_relocator",        "⤴"),
}

# Toolbar buttons that do something ELSE on a right-click.  (id → method name)
TOOLBAR_RIGHTCLICK = {
    "relocator": "run_relocator_all",
    # ⚡ Task queue: right-click shuts the window from any of its four states.
    "queue":     "_close_queue_window",
}

# Extra lines appended to a toolbar button's hover tooltip, so the SHIFT / CTRL
# variants of the function keys are discoverable straight from the button.
TOOLBAR_SECONDARY_TIPS = {
    "copy":   "Shift+F5 = Copy As…  (choose the destination first)",
    "move":   "Shift+F6 = Move As…  (choose the destination first)",
    "edit":   ("Shift+F4 = open in your 2nd program\n"
               "Ctrl+F4 = Windows “Open with…” box"),
    "delete": "The Del key also deletes.",
    "relocator": ("Left-click = the rules, with what each one would move now.\n"
                  "RIGHT-click = run every enabled rule, in order, one at a\n"
                  "time — each rule waits for the one before it to finish."),
    "queue": ("LEFT-click steps through four states — the bolt changes colour:\n"
              "   1  🟢 green    open — no priority; other windows may cover it\n"
              "   2  🟠 orange   open — always above the FILE MANAGER\n"
              "   3  🔴 red      open — above EVERYTHING (the aggressive one)\n"
              "   4  ⚡ plain    closed\n"
              "RIGHT-click closes it from any state.  The number is how many\n"
              "tasks are pending; ⚠N ANSWER means one is waiting for you."),
    "flag_toggle": ("Puts ★ in the flag column, next to Type.\n"
                    "All selected already flagged → the button clears them.\n"
                    "Click the ★ header to sort the flagged ones to the top."),
}

TOOLBAR_MENUS = {
    "tools": "TOOLS ▾  (all the tools)",
    "net":   "NET ▾  (network)",
    "sel":   "SEL ▾  (selection)",
}

# The layout the program ships with — the same row it has always had
DEFAULT_TOOLBAR = [
    {"type": "action", "id": "settings"},
    {"type": "sep"},
    {"type": "action", "id": "go_up"},
    {"type": "action", "id": "go_root"},
    {"type": "action", "id": "view"},
    {"type": "action", "id": "edit"},
    {"type": "action", "id": "copy"},
    {"type": "action", "id": "move"},
    {"type": "action", "id": "new_folder"},
    {"type": "action", "id": "pair_cycle"},
    {"type": "action", "id": "pack"},
    {"type": "action", "id": "unpack"},
    {"type": "action", "id": "ftp"},
    {"type": "menu",   "id": "tools"},
    {"type": "menu",   "id": "net"},
    {"type": "menu",   "id": "sel"},
    {"type": "action", "id": "cmd_admin"},
    {"type": "action", "id": "ps_admin"},
    {"type": "action", "id": "help"},
    {"type": "sep"},
    {"type": "action", "id": "search"},
    {"type": "action", "id": "queue"},
    {"type": "action", "id": "compare_sides"},   # ⚖ between ⚡ and 🗑
    {"type": "action", "id": "browse_archive"},  # 📦 right before 🗑
    {"type": "action", "id": "flag_toggle"},     # ★ right before 🗑
    {"type": "action", "id": "relocator"},       # ⤴ right before 🗑
    {"type": "action", "id": "trash"},
]


def load_toolbar() -> list:
    """The saved toolbar layout, or the default one."""
    data = _load_json_list(TOOLBAR_PATH)
    if not data:
        return [dict(item) for item in DEFAULT_TOOLBAR]
    # Drop anything that no longer exists rather than failing to draw the bar
    clean = []
    have_pair = any(isinstance(it, dict) and it.get("id") == "pair_cycle"
                    for it in data)
    # One-time migration: give an existing saved layout the new ⚖ button, in
    # its intended place between ⚡ (queue) and 🗑 (trash).  Without this an old
    # toolbar.json would silently hide the feature.
    if not any(isinstance(it, dict) and it.get("id") == "compare_sides"
               for it in data):
        for i, it in enumerate(data):
            if isinstance(it, dict) and it.get("id") == "trash":
                data = data[:i] + [{"type": "action", "id": "compare_sides"}] + data[i:]
                break
        else:
            data = list(data) + [{"type": "action", "id": "compare_sides"}]
    # One-time migration: give an existing saved layout the 📦 Browse-archive
    # button — the popup archive viewer (Extract all / Extract here / Test)
    # used to only live in the SEL ▾ menu and a keyboard shortcut, invisible
    # unless you knew to look.  Placed right before 🗑, same spot as DEFAULT_TOOLBAR.
    if not any(isinstance(it, dict) and it.get("id") == "browse_archive"
               for it in data):
        for i, it in enumerate(data):
            if isinstance(it, dict) and it.get("id") == "trash":
                data = data[:i] + [{"type": "action", "id": "browse_archive"}] + data[i:]
                break
        else:
            data = list(data) + [{"type": "action", "id": "browse_archive"}]
    # One-time migration: the ★ flag button (DEL 42b).  Same treatment as the
    # two above — an existing toolbar.json would otherwise never show it.
    if not any(isinstance(it, dict) and it.get("id") == "flag_toggle"
               for it in data):
        for i, it in enumerate(data):
            if isinstance(it, dict) and it.get("id") == "trash":
                data = data[:i] + [{"type": "action", "id": "flag_toggle"}] + data[i:]
                break
        else:
            data = list(data) + [{"type": "action", "id": "flag_toggle"}]
    # One-time migration: the ⤴ Relocator button (DEL 50), in the same spot as
    # DEFAULT_TOOLBAR — right before 🗑, where the "throw it over there" arrow
    # belongs next to the bin.
    if not any(isinstance(it, dict) and it.get("id") == "relocator"
               for it in data):
        for i, it in enumerate(data):
            if isinstance(it, dict) and it.get("id") == "trash":
                data = data[:i] + [{"type": "action", "id": "relocator"}] + data[i:]
                break
        else:
            data = list(data) + [{"type": "action", "id": "relocator"}]
    for item in data:
        if not isinstance(item, dict):
            continue
        kind = item.get("type", "action")
        # One-time migration: the old "Del" button in the F-key row becomes the
        # F8 tab-pair-cycle button (Delete no longer needs a toolbar button —
        # the Del key still deletes).  Skip if a pair_cycle button already exists.
        if kind == "action" and item.get("id") == "delete":
            if have_pair:
                continue
            item = {"type": "action", "id": "pair_cycle"}
            have_pair = True
        if kind == "action" and item.get("id") not in TOOLBAR_ACTIONS:
            _log(f"Toolbar: dropping unknown action {item.get('id')!r}")
            continue
        if kind == "menu" and item.get("id") not in TOOLBAR_MENUS:
            _log(f"Toolbar: dropping unknown menu {item.get('id')!r}")
            continue
        clean.append(item)
    return clean or [dict(item) for item in DEFAULT_TOOLBAR]


def save_toolbar(layout: list):
    _save_json_list(TOOLBAR_PATH, layout)


def toolbar_item_label(item: dict) -> str:
    """Human-readable description of one toolbar entry."""
    kind = item.get("type", "action")
    if kind == "sep":
        return "──────────  separator  ──────────"
    if kind == "menu":
        return TOOLBAR_MENUS.get(item.get("id", ""), item.get("id", ""))
    if kind == "command":
        return f"Command:  {item.get('text', '')}"
    if kind == "folder":
        return f"Folder:  {item.get('text', '')}"
    entry = TOOLBAR_ACTIONS.get(item.get("id", ""))
    return entry[0] if entry else item.get("id", "?")


class ToolbarConfigWindow(tk.Toplevel):
    """Add, remove and reorder the toolbar buttons."""

    def __init__(self, manager: "EditorFrame"):
        super().__init__(manager)
        self.manager = manager
        self.working = [dict(item) for item in manager.toolbar_layout]

        self.configure(bg=C_BG)
        self.geometry("980x620")
        _setup_toplevel(self, "Configure toolbar", manager, modal=False)

        head = tk.Frame(self, bg=C_BG3)
        head.pack(fill="x")
        tk.Label(head, text="🔧  Configure toolbar", bg=C_BG3, fg=C_ACCENT,
                 font=("Segoe UI", 12, "bold")).pack(side="left", padx=10, pady=7)
        tk.Label(head, text="Pick from the left, arrange on the right",
                 bg=C_BG3, fg=C_FG_DIM, font=("Segoe UI", 9)).pack(side="left")

        body = tk.Frame(self, bg=C_BG)
        body.pack(fill="both", expand=True, padx=10, pady=8)

        # ── Available actions ─────────────────────────────────────────────
        left = tk.Frame(body, bg=C_BG)
        left.pack(side="left", fill="both", expand=True)
        tk.Label(left, text="Available", bg=C_BG, fg=C_FG,
                 anchor="w").pack(fill="x")
        self.avail = ttk.Treeview(left, columns=("kind",), selectmode="browse",
                                  show="tree headings")
        self.avail.heading("#0",   text="Action", anchor="w")
        self.avail.heading("kind", text="Type",   anchor="w")
        self.avail.column("#0", width=280, stretch=True)
        self.avail.column("kind", width=90)
        asb = ttk.Scrollbar(left, orient="vertical", command=self.avail.yview)
        self.avail.configure(yscrollcommand=asb.set)
        self.avail.pack(side="left", fill="both", expand=True)
        asb.pack(side="right", fill="y")
        self.avail.bind("<Double-1>", lambda e: self._add())

        # ── Middle buttons ────────────────────────────────────────────────
        mid = tk.Frame(body, bg=C_BG)
        mid.pack(side="left", fill="y", padx=8)
        tk.Label(mid, text="", bg=C_BG).pack(pady=20)
        tk.Button(mid, text="Add  →", bg="lightgreen", fg="black", width=10,
                  command=self._add).pack(pady=3)
        tk.Button(mid, text="←  Remove", bg="#ff8888", fg="black", width=10,
                  command=self._remove).pack(pady=3)
        tk.Label(mid, text="", bg=C_BG).pack(pady=10)
        tk.Button(mid, text="↑  Up", bg="white", fg="black", width=10,
                  command=lambda: self._move(-1)).pack(pady=3)
        tk.Button(mid, text="↓  Down", bg="white", fg="black", width=10,
                  command=lambda: self._move(1)).pack(pady=3)
        tk.Label(mid, text="", bg=C_BG).pack(pady=10)
        tk.Button(mid, text="Separator", bg="white", fg="black", width=10,
                  command=self._add_separator).pack(pady=3)
        tk.Button(mid, text="Command…", bg="white", fg="black", width=10,
                  command=self._add_command).pack(pady=3)
        tk.Button(mid, text="Folder…", bg="white", fg="black", width=10,
                  command=self._add_folder).pack(pady=3)
        tk.Button(mid, text="Rename…", bg="white", fg="black", width=10,
                  command=self._rename_button).pack(pady=3)

        # ── Current toolbar ───────────────────────────────────────────────
        right = tk.Frame(body, bg=C_BG)
        right.pack(side="left", fill="both", expand=True)
        tk.Label(right, text="On the toolbar (top = leftmost)", bg=C_BG, fg=C_FG,
                 anchor="w").pack(fill="x")
        self.current = ttk.Treeview(right, columns=("text",), selectmode="browse",
                                    show="tree headings")
        self.current.heading("#0",   text="Button", anchor="w")
        self.current.heading("text", text="Caption", anchor="w")
        self.current.column("#0", width=290, stretch=True)
        self.current.column("text", width=80)
        csb = ttk.Scrollbar(right, orient="vertical", command=self.current.yview)
        self.current.configure(yscrollcommand=csb.set)
        self.current.pack(side="left", fill="both", expand=True)
        csb.pack(side="right", fill="y")
        self.current.tag_configure("sep", foreground=TC_MUTED)
        self.current.tag_configure("custom", foreground=TC_INFO)
        self.current.bind("<Double-1>", lambda e: self._remove())

        bot = tk.Frame(self, bg=C_BG)
        bot.pack(fill="x", padx=10, pady=(0, 10))
        self._status = tk.Label(bot, text="", bg=C_BG, fg=C_FG_DIM, anchor="w")
        self._status.pack(side="left", fill="x", expand=True)
        tk.Button(bot, text="Close", bg="grey", fg="white", width=9,
                  command=self.destroy).pack(side="right", padx=3)
        tk.Button(bot, text="✔  Apply", bg="lightgreen", fg="black", width=11,
                  command=self._apply).pack(side="right", padx=3)
        tk.Button(bot, text="Restore default toolbar", bg="white", fg="black",
                  command=self._restore).pack(side="right", padx=3)

        self.bind("<Return>", lambda e: self._apply())
        self._render_available()
        self._render_current()

    # ── Rendering ─────────────────────────────────────────────────────────

    def _render_available(self):
        self.avail.delete(*self.avail.get_children())
        for menu_id, label in TOOLBAR_MENUS.items():
            self.avail.insert("", "end", iid=f"menu:{menu_id}", text=label,
                              values=("menu",))
        for action_id, (label, _m, text) in sorted(
                TOOLBAR_ACTIONS.items(), key=lambda kv: kv[1][0].lower()):
            self.avail.insert("", "end", iid=f"action:{action_id}",
                              text=f"{text}   {label}", values=("action",))

    def _render_current(self, select: int = None):
        self.current.delete(*self.current.get_children())
        for i, item in enumerate(self.working):
            kind = item.get("type", "action")
            tag = ("sep",) if kind == "sep" else (
                ("custom",) if kind in ("command", "folder") else ())
            caption = item.get("text", "")
            if kind == "action" and not caption:
                entry = TOOLBAR_ACTIONS.get(item.get("id", ""))
                caption = entry[2] if entry else ""
            self.current.insert("", "end", iid=str(i),
                                text=toolbar_item_label(item),
                                values=(caption,), tags=tag)
        if select is not None and 0 <= select < len(self.working):
            self.current.selection_set(str(select))
            self.current.see(str(select))
        self._status.configure(text=f"{len(self.working)} item(s) on the toolbar")

    def _sel_index(self):
        sel = self.current.selection()
        return int(sel[0]) if sel else None

    # ── Editing ───────────────────────────────────────────────────────────

    def _insert_at(self, item: dict):
        i = self._sel_index()
        pos = len(self.working) if i is None else i + 1
        self.working.insert(pos, item)
        self._render_current(pos)

    def _add(self):
        sel = self.avail.selection()
        if not sel:
            self._status.configure(text="Pick something in the Available list first.",
                                   fg=TC_WARN)
            return
        kind, _, ident = sel[0].partition(":")
        self._insert_at({"type": "menu" if kind == "menu" else "action",
                         "id": ident})

    def _add_separator(self):
        self._insert_at({"type": "sep"})

    def _add_command(self):
        self._command_dialog()

    def _add_folder(self):
        path = filedialog.askdirectory(
            title="Folder for this toolbar button", parent=self,
            initialdir=self.manager.get_active_panel().current_path)
        if not path:
            return
        name = _ask_text(self, "Toolbar folder", "Button caption:",
                         initial=os.path.basename(path.rstrip("\\/")) or path)
        if not name:
            return
        self._insert_at({"type": "folder", "text": name, "path": path})

    def _command_dialog(self):
        top = tk.Toplevel(self)
        top.configure(bg=C_BG)
        top.resizable(False, False)
        _setup_toplevel(top, "Toolbar command", self, modal=True)

        v_text  = tk.StringVar()
        v_shell = tk.StringVar(value="cmd")

        body = tk.Frame(top, bg=C_BG, padx=16, pady=14)
        body.pack(fill="both", expand=True)
        tk.Label(body, text="Button caption:", bg=C_BG, fg=C_FG,
                 anchor="w").pack(fill="x")
        e_text = tk.Entry(body, textvariable=v_text, width=46, bg=C_BG2, fg=C_FG,
                          insertbackground=C_FG,
                          insertofftime=0, insertontime=9999999)
        e_text.pack(fill="x", pady=(0, 8))

        tk.Label(body, text="Shell:", bg=C_BG, fg=C_FG, anchor="w").pack(fill="x")
        ttk.Combobox(body, textvariable=v_shell, width=16, state="readonly",
                     values=list(SHELLS.keys())).pack(anchor="w", pady=(0, 8))

        tk.Label(body, text="Command:", bg=C_BG, fg=C_FG, anchor="w").pack(fill="x")
        txt = tk.Text(body, width=46, height=5, bg=C_BG2, fg=C_FG,
                      insertbackground=C_FG, font=("Consolas", 9),
                      insertofftime=0, insertontime=9999999)
        txt.pack(fill="both", expand=True, pady=(0, 4))
        tk.Label(body, text=COMMAND_PLACEHOLDERS, bg=C_BG, fg=C_FG_DIM,
                 font=("Consolas", 8), justify="left",
                 anchor="w").pack(fill="x", pady=(2, 10))

        def save(event=None):
            text = v_text.get().strip()
            command = txt.get("1.0", "end-1c").strip()
            if not text or not command:
                messagebox.showerror("Toolbar",
                                     "Caption and command are both required.",
                                     parent=top)
                return
            self._insert_at({"type": "command", "text": text,
                             "command": command, "shell": v_shell.get()})
            top.destroy()

        btns = tk.Frame(body, bg=C_BG)
        btns.pack(fill="x")
        tk.Button(btns, text="Cancel", bg="grey", fg="white", width=10,
                  command=top.destroy).pack(side="right", padx=3)
        tk.Button(btns, text="Add", bg="lightgreen", fg="black", width=10,
                  command=save).pack(side="right", padx=3)
        e_text.bind("<Return>", save)
        txt.bind("<Control-Return>", save)
        e_text.focus_set()

    def _rename_button(self):
        """Change the caption shown on a button."""
        i = self._sel_index()
        if i is None:
            return
        item = self.working[i]
        if item.get("type") == "sep":
            return
        current = item.get("text", "")
        if not current and item.get("type") == "action":
            entry = TOOLBAR_ACTIONS.get(item.get("id", ""))
            current = entry[2] if entry else ""
        new = _ask_text(self, "Toolbar", "Button caption:", initial=current)
        if new:
            item["text"] = new
            self._render_current(i)

    def _remove(self):
        i = self._sel_index()
        if i is None:
            return
        del self.working[i]
        self._render_current(min(i, len(self.working) - 1))

    def _move(self, delta: int):
        i = self._sel_index()
        if i is None:
            return
        j = i + delta
        if 0 <= j < len(self.working):
            self.working[i], self.working[j] = self.working[j], self.working[i]
            self._render_current(j)

    def _restore(self):
        if _ask_yes_no("Toolbar",
                               "Restore the default toolbar?", parent=self):
            self.working = [dict(item) for item in DEFAULT_TOOLBAR]
            self._render_current()

    def _apply(self):
        if not self.working:
            messagebox.showerror("Toolbar",
                                 "The toolbar cannot be completely empty.",
                                 parent=self)
            return
        self.manager.toolbar_layout = [dict(item) for item in self.working]
        save_toolbar(self.manager.toolbar_layout)
        self.manager.build_toolbar()
        _flash_ok(self, "Toolbar updated.", "Toolbar")


# ══════════════════════════════════════════════════════════════════════════
#  DEL 37 — Command palette  (Ctrl+Shift+P)
# ══════════════════════════════════════════════════════════════════════════
#
# One searchable list of everything the program can do — every action, every
# hotlist folder, every saved command — so nothing has to be hunted for in a
# menu.  Matching is subsequence-based: "mrt" finds "Multi-Rename tool".

def fuzzy_score(query: str, text: str):
    """Score how well `query` matches `text`.

    Returns (score, [matched indices]) or None when it does not match at all.
    Higher is better.  Consecutive letters, word starts and an exact prefix
    all score more, which is what makes short queries land on the obvious
    candidate rather than an accidental one.
    """
    if not query:
        return (0, [])
    q, t = query.lower(), text.lower()
    if q in t:                       # substring — always the strongest match
        start = t.index(q)
        bonus = 200 if start == 0 else (120 if t[start - 1] in " -_/\\." else 60)
        return (1000 + bonus - start, list(range(start, start + len(q))))

    idx, positions, score, prev = 0, [], 0, -2
    for ch in q:
        found = t.find(ch, idx)
        if found < 0:
            return None
        positions.append(found)
        if found == prev + 1:
            score += 15                       # consecutive
        elif found == 0 or t[found - 1] in " -_/\\.":
            score += 10                       # start of a word
        else:
            score += 1
        prev = found
        idx = found + 1
    score -= len(text) * 0.05                 # prefer shorter, tighter matches
    return (score, positions)


class CommandPalette(tk.Toplevel):
    """Fuzzy-searchable list of every command in the program."""

    MAX_ROWS = 300

    def __init__(self, manager: "EditorFrame"):
        super().__init__(manager)
        self.manager = manager
        self.entries = self._collect()
        self.filtered: list = []

        self.configure(bg=C_BG)
        self.overrideredirect(False)
        _setup_toplevel(self, "Command palette", manager, modal=False)
        self._place_over_parent()

        self.var_query = tk.StringVar()
        box = tk.Frame(self, bg=C_BG3)
        box.pack(fill="x")
        tk.Label(box, text="▶", bg=C_BG3, fg=C_ACCENT,
                 font=("Segoe UI", 12, "bold")).pack(side="left", padx=(10, 4), pady=6)
        self.entry = tk.Entry(box, textvariable=self.var_query, bg=C_BG3, fg=C_FG,
                              insertbackground=C_FG, relief="flat",
                              font=("Segoe UI", 13),
                              insertofftime=0, insertontime=9999999)
        self.entry.pack(side="left", fill="x", expand=True, padx=(0, 10), pady=6)

        self.listbox = tk.Listbox(self, bg=C_BG2, fg=C_FG,
                                  selectbackground="#3a5a8c",
                                  selectforeground="#ffffff",
                                  font=("Segoe UI", 10), activestyle="none",
                                  highlightthickness=0, borderwidth=0)
        sb = ttk.Scrollbar(self, orient="vertical", command=self.listbox.yview)
        self.listbox.configure(yscrollcommand=sb.set)
        self.listbox.pack(side="left", fill="both", expand=True, padx=(6, 0), pady=6)
        sb.pack(side="left", fill="y", pady=6)

        self._hint = tk.Label(self, text="", bg=C_BG3, fg=C_FG_DIM, anchor="w",
                              font=("Segoe UI", 8))
        self._hint.pack(fill="x", side="bottom")

        self.var_query.trace_add("write", lambda *_: self._refilter())
        self.entry.bind("<Down>",   lambda e: self._move(1))
        self.entry.bind("<Up>",     lambda e: self._move(-1))
        self.entry.bind("<Next>",   lambda e: self._move(10))
        self.entry.bind("<Prior>",  lambda e: self._move(-10))
        self.entry.bind("<Return>", lambda e: self._run())
        self.listbox.bind("<Double-1>", lambda e: self._run())
        self.listbox.bind("<Return>",   lambda e: self._run())

        self._refilter()
        self.entry.focus_set()

    def _place_over_parent(self):
        """Centre the palette near the top of the main window."""
        try:
            top = self.manager.winfo_toplevel()
            w, h = 720, 460
            x = top.winfo_rootx() + (top.winfo_width() - w) // 2
            y = top.winfo_rooty() + 80
            self.geometry(f"{w}x{h}+{max(0, x)}+{max(0, y)}")
        except Exception:
            self.geometry("720x460")

    # ── Sources ───────────────────────────────────────────────────────────

    def _collect(self) -> list:
        """Every runnable thing: (category, label, detail, callable)."""
        out = []

        for action_id, (label, method_name, _text) in TOOLBAR_ACTIONS.items():
            method = getattr(self.manager, method_name, None)
            if method is None:
                continue
            key = self.manager.keymap.get(action_id, "")
            out.append(("Action", label,
                        key_to_label(key) if key else "", method))

        # Shortcut-only actions that are not on the toolbar list
        for action_id, _key, label, method_name in KEY_ACTIONS:
            if action_id in TOOLBAR_ACTIONS:
                continue
            method = getattr(self.manager, method_name, None)
            if method is None:
                continue
            key = self.manager.keymap.get(action_id, "")
            out.append(("Action", label,
                        key_to_label(key) if key else "", method))

        for fav in self.manager.hotlist:
            path = fav.get("path", "")
            out.append(("Folder", f"Go to  {fav.get('name', path)}", path,
                        lambda p=path: self._goto(p)))

        for cmd in self.manager.command_lib:
            name = cmd.get("name", "")
            out.append(("Command", f"Run  {name}",
                        f"{SHELLS.get(cmd.get('shell', 'cmd'))}: {cmd.get('command', '')[:60]}",
                        lambda c=cmd: self._run_command(c)))

        for ws_name in getattr(self.manager, "workspaces", {}):
            out.append(("Workspace", f"Load workspace  {ws_name}", "",
                        lambda n=ws_name: self.manager._ws_load(n)))

        return out

    def _goto(self, path: str):
        if not os.path.isdir(path):
            messagebox.showerror("Command palette",
                                 f"This folder no longer exists:\n{path}")
            return
        self.manager.get_active_panel().change_directory(path)

    def _run_command(self, cmd: dict):
        self.manager._toolbar_run_command(cmd.get("command", ""),
                                          cmd.get("shell", "cmd"))

    # ── Filtering ─────────────────────────────────────────────────────────

    def _refilter(self):
        query = self.var_query.get().strip()
        scored = []
        for entry in self.entries:
            category, label, detail, _fn = entry
            hit = fuzzy_score(query, label)
            if hit is None and detail:
                hit = fuzzy_score(query, detail)
                if hit is not None:
                    hit = (hit[0] - 50, [])      # detail matches rank lower
            if hit is None and query:
                continue
            scored.append((hit[0] if hit else 0, entry))

        scored.sort(key=lambda pair: -pair[0])
        self.filtered = [entry for _s, entry in scored[:self.MAX_ROWS]]

        self.listbox.delete(0, "end")
        for category, label, detail, _fn in self.filtered:
            line = f"  {label}"
            if detail:
                line = f"{line}    ·  {detail}"
            self.listbox.insert("end", line)
        if self.filtered:
            self.listbox.selection_set(0)
            self.listbox.see(0)
        self._hint.configure(
            text=f"  {len(self.filtered)} of {len(self.entries)} · "
                 "Enter runs · ↑ ↓ to move · Esc closes")

    def _move(self, delta: int):
        if not self.filtered:
            return "break"
        cur = self.listbox.curselection()
        i = (cur[0] if cur else 0) + delta
        i = max(0, min(len(self.filtered) - 1, i))
        self.listbox.selection_clear(0, "end")
        self.listbox.selection_set(i)
        self.listbox.see(i)
        return "break"

    def _run(self):
        if not self.filtered:
            return "break"
        cur = self.listbox.curselection()
        _cat, label, _detail, fn = self.filtered[cur[0] if cur else 0]
        self.destroy()
        try:
            fn()
        except Exception as exc:
            _log(f"Command palette: {label} failed: {exc}")
            _crash_report(type(exc), exc, exc.__traceback__, f"palette:{label}")
        return "break"


# ══════════════════════════════════════════════════════════════════════════
#  DEL 38 — Operation log with multi-step undo
# ══════════════════════════════════════════════════════════════════════════
#
# The soft trash already covers Delete.  This covers the rest: every copy,
# move, rename and new folder is written to a small JSON log, and the most
# recent steps can be reverted in order.
#
# What can honestly be undone, and what cannot:
#   move / rename    yes — the file is moved back where it came from
#   new folder       yes — removed, but only while it is still empty
#   copy             yes, unless the copy overwrote a file that was already
#                    there; deleting the copy then would leave nothing at all,
#                    so those items are reported instead of guessed at
#   unpack / pack    no — recorded for the history, not undoable
# An operation that overwrote something can never fully restore what it
# replaced.  The log says so rather than pretending otherwise.

OPLOG_MAX = 300           # entries kept in the log
OPLOG_ITEMS_PER_ENTRY = 500    # items stored per operation (rest is counted only)
OPLOG_TOTAL_ITEMS = 5000       # items stored in the whole log

UNDOABLE_KINDS = {"move", "rename", "copy", "new_folder", "delete_mark"}

KIND_LABELS = {
    "move":        "Move",
    "copy":        "Copy",
    "rename":      "Rename",
    "new_folder":  "New folder",
    "pack":        "Pack",
    "unpack":      "Unpack",
    "sync":        "Synchronize",
    "delete_mark": "Marked for deletion",
    "delete":      "Deleted",
}


class OperationLog:
    """Records file operations and reverts them newest-first."""

    def __init__(self, manager: "EditorFrame"):
        self.manager = manager
        self.entries: list = _load_json_list(OPLOG_PATH)
        self._next_id = max((e.get("id", 0) for e in self.entries), default=0) + 1
        self._lock = threading.Lock()
        self._save_lock = threading.Lock()
        self._pending_snapshot = None
        self._saver_running = False
        # Trim a log left over from the old unlimited versions (once, at start)
        shrunk = False
        for e in self.entries:
            its = e.get("items", [])
            if len(its) > OPLOG_ITEMS_PER_ENTRY:
                e["omitted"] = e.get("omitted", 0) + len(its) - OPLOG_ITEMS_PER_ENTRY
                e["items"] = its[:OPLOG_ITEMS_PER_ENTRY]
                shrunk = True
        before = len(self.entries)
        self._trim_total()
        if shrunk or len(self.entries) != before:
            self._save_async(list(self.entries))

    # ── Recording ─────────────────────────────────────────────────────────

    def record(self, kind: str, items: list, note: str = ""):
        """Append one operation. items = [{'src':…, 'dst':…, 'overwrote':bool}]"""
        items = [i for i in items if i.get("src") or i.get("dst")]
        if not items:
            return
        total = len(items)
        with self._lock:
            entry = {
                "id":        self._next_id,
                "time":      datetime.now().isoformat(timespec="seconds"),
                "kind":      kind,
                "note":      note,
                # ToDo: a huge operation (30,000 files) used to be stored in
                # full and made oplog.json 120 MB, which froze the window on
                # every save.  Now only the first OPLOG_ITEMS_PER_ENTRY items
                # are kept (so Undo reverts those); "omitted" counts the rest.
                "items":     items[:OPLOG_ITEMS_PER_ENTRY],
                "omitted":   max(0, total - OPLOG_ITEMS_PER_ENTRY),
                "undone":    False,
            }
            self._next_id += 1
            self.entries.append(entry)
            del self.entries[:-OPLOG_MAX]
            self._trim_total()
            snapshot = list(self.entries)
        self._save_async(snapshot)
        _log(f"oplog: {kind} — {total} item(s) {note}")

    def _trim_total(self):
        """Drop the oldest entries while the whole log holds too many items."""
        kept = sum(len(e.get("items", [])) for e in self.entries)
        while len(self.entries) > 1 and kept > OPLOG_TOTAL_ITEMS:
            kept -= len(self.entries[0].get("items", []))
            del self.entries[0]

    def _save_async(self, snapshot: list):
        """Write the log from a background thread.  If saves pile up, only
        the newest snapshot is written (the older ones are obsolete)."""
        with self._save_lock:
            self._pending_snapshot = snapshot
            if self._saver_running:
                return
            self._saver_running = True

        def _worker():
            while True:
                with self._save_lock:
                    snap = self._pending_snapshot
                    self._pending_snapshot = None
                    if snap is None:
                        self._saver_running = False
                        return
                try:
                    tmp = Path(str(OPLOG_PATH) + ".tmp")
                    with open(tmp, "w", encoding="utf-8") as fh:
                        json.dump(snap, fh, ensure_ascii=False,
                                  separators=(",", ":"))
                    os.replace(tmp, OPLOG_PATH)   # never leaves a half file
                except Exception as exc:
                    _log(f"Could not save oplog: {exc}")

        threading.Thread(target=_worker, daemon=True).start()

    def clear(self):
        with self._lock:
            self.entries = []
            snapshot = []
        self._save_async(snapshot)

    def pending(self) -> list:
        """Entries that have not been undone, newest first."""
        return [e for e in reversed(self.entries) if not e.get("undone")]

    # ── Undoing ───────────────────────────────────────────────────────────

    @staticmethod
    def describe(entry: dict) -> str:
        items = entry.get("items", [])
        kind = KIND_LABELS.get(entry.get("kind"), entry.get("kind", "?"))
        first = items[0] if items else {}
        target = first.get("dst") or first.get("src") or ""
        name = os.path.basename(target.rstrip("\\/")) or target
        more = max(0, len(items) - 1) + int(entry.get("omitted", 0))
        extra = f"  (+{more} more)" if more > 0 else ""
        return f"{kind}  {name}{extra}"

    @staticmethod
    def can_undo(entry: dict) -> tuple:
        """(possible, reason) — reason explains a 'no'."""
        if entry.get("undone"):
            return False, "already undone"
        kind = entry.get("kind")
        if kind not in UNDOABLE_KINDS:
            if kind == "delete":
                return False, ("already carried out — look in the Recycle Bin, "
                               "if that drive uses one")
            return False, f"{KIND_LABELS.get(kind, kind)} cannot be undone"
        items = entry.get("items", [])
        if kind == "delete_mark":
            # Undoing a mark just puts the items back in the panel, so it is
            # possible for as long as the files are still on disk.
            if not any(os.path.exists(i.get("dst") or i.get("src", ""))
                       for i in items):
                return False, "the items are gone — the deletion was carried out"
            return True, ""
        if kind == "copy":
            safe = [i for i in items if not i.get("overwrote")]
            if not safe:
                return False, "every copy overwrote an existing file"
        return True, ""

    def undo(self, entry: dict) -> tuple:
        """Revert one entry. Returns (done_count, [error strings])."""
        kind = entry.get("kind")
        items = entry.get("items", [])
        done, errors = 0, []

        if kind == "delete_mark":
            # Nothing was ever removed — just take the mark off again
            paths = [i.get("dst") or i.get("src", "") for i in items]
            paths = [p for p in paths if p]
            try:
                self.manager.unmark_deletion(paths)
                done = sum(1 for p in paths if os.path.exists(p))
                missing = [os.path.basename(p) for p in paths
                           if not os.path.exists(p)]
                if missing:
                    errors.append(
                        f"{len(missing)} item(s) are no longer on disk: "
                        + ", ".join(missing[:6]))
            except Exception as exc:
                errors.append(str(exc))
            entry["undone"] = True
            _save_json_list(OPLOG_PATH, self.entries)
            return done, errors

        # Reverse order, so a folder created before its files is removed last
        for item in reversed(items):
            src, dst = item.get("src", ""), item.get("dst", "")
            over = bool(item.get("overwrote"))
            try:
                if kind in ("move", "rename"):
                    if not dst or not os.path.exists(dst):
                        errors.append(f"{os.path.basename(dst or src)}: gone from {dst}")
                        continue
                    if os.path.exists(src):
                        errors.append(
                            f"{os.path.basename(src)}: something is already back at "
                            f"the original place")
                        continue
                    os.makedirs(os.path.dirname(src), exist_ok=True)
                    shutil.move(dst, src)
                    done += 1

                elif kind == "copy":
                    if over:
                        errors.append(
                            f"{os.path.basename(dst)}: skipped — this copy replaced "
                            f"an existing file, so removing it would leave nothing")
                        continue
                    if not os.path.exists(dst):
                        continue          # already gone; nothing to do
                    if os.path.isdir(dst):
                        shutil.rmtree(dst)
                    else:
                        os.remove(dst)
                    done += 1

                elif kind == "new_folder":
                    if not os.path.isdir(dst):
                        continue
                    if os.listdir(dst):
                        errors.append(
                            f"{os.path.basename(dst)}: not empty any more — "
                            f"left alone")
                        continue
                    os.rmdir(dst)
                    done += 1

            except Exception as exc:
                errors.append(f"{os.path.basename(dst or src)}: {exc}")

        # Only mark it undone when something actually moved back
        if done and not errors:
            entry["undone"] = True
        elif done:
            entry["undone"] = True
            entry["note"] = (entry.get("note", "") + " [partially undone]").strip()
        _save_json_list(OPLOG_PATH, self.entries)
        return done, errors


class UndoWindow(tk.Toplevel):
    """Browse recent operations and step back through them."""

    def __init__(self, manager: "EditorFrame"):
        super().__init__(manager)
        self.manager = manager
        self.log = manager.oplog

        self.configure(bg=C_BG)
        self.geometry("900x560")
        _setup_toplevel(self, "Undo history", manager, modal=False)

        head = tk.Frame(self, bg=C_BG3)
        head.pack(fill="x")
        tk.Label(head, text="↶  Undo history", bg=C_BG3, fg=C_ACCENT,
                 font=("Segoe UI", 12, "bold")).pack(side="left", padx=10, pady=7)
        tk.Label(head, text="Newest first — steps are undone from the top down",
                 bg=C_BG3, fg=C_FG_DIM, font=("Segoe UI", 9)).pack(side="left")

        mid = tk.Frame(self, bg=C_BG)
        mid.pack(fill="both", expand=True, padx=10, pady=8)
        cols = ("when", "items", "status")
        self.tree = ttk.Treeview(mid, columns=cols, selectmode="browse")
        self.tree.heading("#0",     text="Operation", anchor="w")
        self.tree.heading("when",   text="When",      anchor="w")
        self.tree.heading("items",  text="Items",     anchor="e")
        self.tree.heading("status", text="Status",    anchor="w")
        self.tree.column("#0", width=380, stretch=True)
        self.tree.column("when", width=150)
        self.tree.column("items", width=60, anchor="e")
        self.tree.column("status", width=260)
        sb = ttk.Scrollbar(mid, orient="vertical", command=self.tree.yview)
        self.tree.configure(yscrollcommand=sb.set)
        self.tree.pack(side="left", fill="both", expand=True)
        sb.pack(side="right", fill="y")
        self.tree.tag_configure("undone", foreground=TC_MUTED)
        self.tree.tag_configure("blocked", foreground=TC_WARN)
        self.tree.tag_configure("ready",   foreground=TC_OK)
        self.tree.bind("<Double-1>", lambda e: self._show_details())

        bot = tk.Frame(self, bg=C_BG)
        bot.pack(fill="x", padx=10, pady=(0, 10))
        self._status = tk.Label(bot, text="", bg=C_BG, fg=C_FG_DIM, anchor="w")
        self._status.pack(side="left", fill="x", expand=True)
        tk.Button(bot, text="Close", bg="grey", fg="white", width=9,
                  command=self.destroy).pack(side="right", padx=3)
        tk.Button(bot, text="Clear history", bg="white", fg="black",
                  command=self._clear).pack(side="right", padx=3)
        tk.Button(bot, text="↶↶  Undo last 5", bg="lightblue", fg="black",
                  command=lambda: self._undo_many(5)).pack(side="right", padx=3)
        tk.Button(bot, text="↶  Undo last step", bg="lightgreen", fg="black",
                  command=lambda: self._undo_many(1)).pack(side="right", padx=3)
        tk.Button(bot, text="Details…", bg="white", fg="black",
                  command=self._show_details).pack(side="right", padx=3)

        self.bind("<Return>", lambda e: self._undo_many(1))
        self._render()

    def _render(self):
        self.tree.delete(*self.tree.get_children())
        entries = list(reversed(self.log.entries))
        for e in entries:
            ok, reason = OperationLog.can_undo(e)
            if e.get("undone"):
                tag, status = "undone", "undone"
            elif ok:
                tag, status = "ready", "can be undone"
            else:
                tag, status = "blocked", reason
            when = e.get("time", "").replace("T", "  ")
            self.tree.insert("", "end", iid=str(e.get("id")),
                             text=OperationLog.describe(e),
                             values=(when, len(e.get("items", [])), status),
                             tags=(tag,))
        pending = self.log.pending()
        self._status.configure(
            text=(f"{len(self.log.entries)} operation(s) logged · "
                  f"{len(pending)} can still be stepped back"
                  if self.log.entries else "Nothing logged yet."))

    def _selected_entry(self):
        sel = self.tree.selection()
        if not sel:
            return None
        for e in self.log.entries:
            if str(e.get("id")) == sel[0]:
                return e
        return None

    def _show_details(self):
        e = self._selected_entry()
        if not e:
            return
        top = tk.Toplevel(self)
        top.configure(bg=C_BG)
        top.geometry("820x460")
        _setup_toplevel(top, f"{OperationLog.describe(e)} — details", self,
                        modal=False)
        txt = tk.Text(top, bg=C_BG2, fg=C_FG, wrap="none", font=("Consolas", 9),
                      padx=8, pady=6,
                      insertofftime=0, insertontime=9999999)
        sb = ttk.Scrollbar(top, orient="vertical", command=txt.yview)
        txt.configure(yscrollcommand=sb.set)
        txt.pack(side="left", fill="both", expand=True)
        sb.pack(side="right", fill="y")
        lines = [f"{KIND_LABELS.get(e.get('kind'), e.get('kind'))}   "
                 f"{e.get('time', '')}   {e.get('note', '')}", ""]
        for item in e.get("items", []):
            mark = "  [overwrote existing]" if item.get("overwrote") else ""
            lines.append(f"{item.get('src', '')}\n   →  {item.get('dst', '')}{mark}\n")
        txt.insert("1.0", "\n".join(lines))
        txt.configure(state="disabled")

    def _undo_many(self, count: int):
        pending = [e for e in self.log.pending()
                   if OperationLog.can_undo(e)[0]]
        if not pending:
            messagebox.showinfo("Undo", "There is nothing left to undo.",
                                parent=self)
            return
        batch = pending[:count]

        summary = "\n".join(f"  • {OperationLog.describe(e)}" for e in batch)
        warn = ""
        if any(i.get("overwrote") for e in batch for i in e.get("items", [])):
            warn = ("\n\nNote: some of these replaced files that were already "
                    "there.  What was replaced cannot be brought back.")
        if not _ask_yes_no(
                "Undo",
                f"Step back {len(batch)} operation(s)?\n\n{summary}{warn}",
                parent=self):
            return

        total_done, all_errors = 0, []
        for entry in batch:               # newest first
            done, errors = self.log.undo(entry)
            total_done += done
            all_errors.extend(errors)

        self.manager.refresh_panels()
        self._render()
        if all_errors:
            messagebox.showwarning(
                "Undo",
                f"Reverted {total_done} item(s).\n\n"
                f"{len(all_errors)} could not be reverted:\n"
                + "\n".join(all_errors[:12])
                + ("\n…" if len(all_errors) > 12 else ""), parent=self)
        else:
            _flash_ok(self, f"Stepped back {total_done} item(s).", "Undone")

    def _clear(self):
        if _ask_yes_no(
                "Undo history",
                "Clear the whole history?\n\n"
                "The files stay exactly as they are — only the record of what "
                "happened is removed, so nothing can be stepped back after this.",
                parent=self):
            self.log.clear()
            self._render()


# ══════════════════════════════════════════════════════════════════════════
#  DEL 39 — Visual disk usage  (treemap)
# ══════════════════════════════════════════════════════════════════════════
#
# The disk overview shows numbers; this shows shape.  Every file is a
# rectangle sized by how much room it takes, so the thing eating the drive is
# simply the biggest block on screen.

TREEMAP_MIN_LABEL = (54, 20)      # a rect must be this big to carry a label
TREEMAP_NEST_MIN  = (70, 46)      # …and this big before its contents nest


class SizeNode:
    """One entry in the scanned size tree."""

    __slots__ = ("name", "path", "size", "is_dir", "children", "parent")

    def __init__(self, name, path, size=0, is_dir=False, parent=None):
        self.name = name
        self.path = path
        self.size = size
        self.is_dir = is_dir
        self.children: list = []
        self.parent = parent


def scan_sizes(root: str, cancel=None, progress=None, max_depth: int = 12) -> SizeNode:
    """Walk a folder tree and total up sizes. Returns the root SizeNode."""
    root_node = SizeNode(os.path.basename(root.rstrip("\\/")) or root, root,
                         0, True)
    counted = [0]

    def walk(node: SizeNode, depth: int) -> int:
        if cancel and cancel():
            return 0
        total = 0
        try:
            with os.scandir(node.path) as it:
                for entry in it:
                    if cancel and cancel():
                        break
                    try:
                        if entry.is_dir(follow_symlinks=False):
                            if depth >= max_depth:
                                continue
                            child = SizeNode(entry.name, entry.path, 0, True, node)
                            child.size = walk(child, depth + 1)
                            if child.size > 0:
                                node.children.append(child)
                                total += child.size
                        elif entry.is_file(follow_symlinks=False):
                            size = entry.stat(follow_symlinks=False).st_size
                            if size > 0:
                                node.children.append(
                                    SizeNode(entry.name, entry.path, size,
                                             False, node))
                                total += size
                            counted[0] += 1
                            if progress and counted[0] % 500 == 0:
                                progress(counted[0], node.path)
                    except OSError:
                        continue          # unreadable entry — skip it
        except OSError:
            return 0
        node.children.sort(key=lambda n: -n.size)
        return total

    root_node.size = walk(root_node, 0)
    return root_node


def squarify(items: list, x: float, y: float, w: float, h: float) -> list:
    """Squarified treemap layout.

    items: list of (value, payload), largest first.
    Returns [(payload, (x, y, w, h))] — rectangles kept as close to square as
    possible, which is what makes areas comparable by eye.
    """
    out = []
    if w <= 0 or h <= 0:
        return out
    values = [v for v, _p in items if v > 0]
    if not values:
        return out
    total = sum(values)
    if total <= 0:
        return out

    # Work in area units scaled to the rectangle
    scale = (w * h) / total
    queue = [(v * scale, p) for v, p in items if v > 0]

    def worst(row, side):
        if not row or side <= 0:
            return float("inf")
        s = sum(a for a, _p in row)
        if s <= 0:
            return float("inf")
        rmax, rmin = max(a for a, _p in row), min(a for a, _p in row)
        return max((side * side * rmax) / (s * s), (s * s) / (side * side * rmin))

    def layout_row(row, x, y, w, h, horizontal):
        s = sum(a for a, _p in row)
        results = []
        if s <= 0:
            return results, x, y, w, h
        if horizontal:
            row_h = s / w if w else 0
            cx = x
            for a, p in row:
                cw = a / row_h if row_h else 0
                results.append((p, (cx, y, cw, row_h)))
                cx += cw
            return results, x, y + row_h, w, h - row_h
        else:
            row_w = s / h if h else 0
            cy = y
            for a, p in row:
                ch = a / row_w if row_w else 0
                results.append((p, (x, cy, row_w, ch)))
                cy += ch
            return results, x + row_w, y, w - row_w, h

    row = []
    while queue:
        horizontal = w >= h
        side = w if horizontal else h
        item = queue[0]
        if not row or worst(row + [item], side) <= worst(row, side):
            row.append(queue.pop(0))
        else:
            placed, x, y, w, h = layout_row(row, x, y, w, h, horizontal)
            out.extend(placed)
            row = []
            if w <= 0 or h <= 0:
                break
    if row:
        placed, x, y, w, h = layout_row(row, x, y, w, h, w >= h)
        out.extend(placed)
    return out


# Colour per file category — chosen to stay distinguishable side by side
TREEMAP_COLOURS = {
    "Video":      "#e05d5d",
    "Image":      "#5da9e0",
    "Audio":      "#c07ae0",
    "Archive":    "#e0a75d",
    "ZIP":        "#e0a75d",
    "RAR":        "#e0a75d",
    "Program":    "#7ae0a7",
    "Installer":  "#7ae0a7",
    "Library":    "#8a9bb5",
    "System":     "#8a9bb5",
    "Python":     "#5de0c0",
    "Text":       "#d5d5a0",
    "PDF":        "#e07a7a",
    "Word":       "#7a95e0",
    "Excel":      "#7ac07a",
    "PowerPoint": "#e0955d",
    "Web":        "#c0d55d",
    "JSON":       "#d5c05d",
    "XML":        "#d5c05d",
    "CSV":        "#b0d57a",
    "Database":   "#e0c15d",
    "Backup":     "#9c8f7a",
    "Config":     "#a5b5c5",
    "Font":       "#d59ac0",
    "Disc image": "#e08a5d",
    "Subtitle":   "#c5c5d5",
    "Batch":      "#8fd5a0",
    "PowerShell": "#7a9ad5",
}
TREEMAP_DEFAULT_COLOUR = "#9aa4b8"


def treemap_colour(node: SizeNode) -> str:
    if node.is_dir:
        return "#44506b"
    ext = os.path.splitext(node.name)[1].lower()
    return TREEMAP_COLOURS.get(_EXT_TYPE.get(ext, ""), TREEMAP_DEFAULT_COLOUR)


class TreemapWindow(tk.Toplevel):
    """WinDirStat-style picture of where the space actually went."""

    def __init__(self, manager: "EditorFrame", path: str):
        super().__init__(manager)
        self.manager = manager
        self.root_path = path
        self.root_node: SizeNode = None
        self.view: SizeNode = None          # node currently filling the canvas
        self._rects: list = []              # [(node, (x, y, w, h))]
        self._stop = threading.Event()
        self._busy = False
        self._hover = None

        self.configure(bg=C_BG)
        self.geometry("1100x740")
        _setup_toplevel(self, "Disk usage", manager, modal=False)

        self._build_ui()
        self.after(80, self._start_scan)

    def _build_ui(self):
        head = tk.Frame(self, bg=C_BG3)
        head.pack(fill="x")
        tk.Label(head, text="▦  Disk usage", bg=C_BG3, fg=C_ACCENT,
                 font=("Segoe UI", 12, "bold")).pack(side="left", padx=10, pady=7)
        self._crumb = tk.Label(head, text="", bg=C_BG3, fg=C_FG,
                               font=("Segoe UI", 9), anchor="w")
        self._crumb.pack(side="left", fill="x", expand=True)
        tk.Button(head, text="↑  Up", bg="white", fg="black",
                  command=self._go_up).pack(side="right", padx=4, pady=4)
        tk.Button(head, text="⟳  Rescan", bg="white", fg="black",
                  command=self._start_scan).pack(side="right", padx=4, pady=4)
        tk.Button(head, text="■  Stop", bg="white", fg="black",
                  command=lambda: self._stop.set()).pack(side="right", pady=4)

        self.canvas = tk.Canvas(self, bg="#12121c", highlightthickness=0)
        self.canvas.pack(fill="both", expand=True, padx=8, pady=6)
        self.canvas.bind("<Configure>", lambda e: self._draw())
        self.canvas.bind("<Motion>", self._on_motion)
        self.canvas.bind("<Button-1>", self._on_click)
        self.canvas.bind("<Double-1>", self._on_double)
        self.canvas.bind("<Button-3>", lambda e: self._go_up())
        self.canvas.bind("<Leave>", lambda e: self._set_info(""))

        legend = tk.Frame(self, bg=C_BG2)
        legend.pack(fill="x")
        tk.Label(legend, text="  ", bg=C_BG2).pack(side="left")
        for label in ("Video", "Image", "Audio", "Archive", "Program",
                      "Text", "PDF"):
            tk.Label(legend, text="■", bg=C_BG2, fg=TREEMAP_COLOURS[label],
                     font=("Segoe UI", 11)).pack(side="left", padx=(6, 1))
            tk.Label(legend, text=label, bg=C_BG2, fg=C_FG_DIM,
                     font=("Segoe UI", 8)).pack(side="left")
        tk.Label(legend, text="■", bg=C_BG2, fg="#44506b",
                 font=("Segoe UI", 11)).pack(side="left", padx=(10, 1))
        tk.Label(legend, text="folder", bg=C_BG2, fg=C_FG_DIM,
                 font=("Segoe UI", 8)).pack(side="left")

        self._info = tk.Label(self, text="", bg=C_BG3, fg=C_FG_DIM, anchor="w",
                              font=("Segoe UI", 9))
        self._info.pack(fill="x", side="bottom")

        tip = tk.Label(self, text="  Click a folder to go in · right-click or "
                                  "Up to go back · double-click a file to open it",
                       bg=C_BG3, fg=C_FG_DIM, anchor="w", font=("Segoe UI", 8))
        tip.pack(fill="x", side="bottom")

    # ── Scanning ──────────────────────────────────────────────────────────

    def _start_scan(self):
        if self._busy:
            return
        self._busy = True
        self._stop.clear()
        self._set_info(f"Scanning {self.root_path} …")
        self.canvas.delete("all")
        self.canvas.create_text(
            self.canvas.winfo_width() // 2 or 400,
            self.canvas.winfo_height() // 2 or 300,
            text="Scanning…", fill=C_FG_DIM, font=("Segoe UI", 14))

        def worker():
            try:
                node = scan_sizes(
                    self.root_path,
                    cancel=self._stop.is_set,
                    progress=lambda n, p: _ui_call(
                        self, lambda: self._set_info(f"Scanning… {n:,} files")))
                _ui_call(self, lambda: self._scan_done(node))
            except Exception as exc:
                _ui_call(self, lambda e=exc: self._set_info(f"Scan failed: {e}"))
                self._busy = False

        threading.Thread(target=worker, daemon=True).start()

    def _scan_done(self, node: SizeNode):
        self._busy = False
        self.root_node = node
        self.view = node
        self._draw()

    # ── Drawing ───────────────────────────────────────────────────────────

    def _draw(self):
        self.canvas.delete("all")
        self._rects = []
        node = self.view
        if node is None:
            return

        w = self.canvas.winfo_width()
        h = self.canvas.winfo_height()
        if w < 10 or h < 10:
            return
        if not node.children:
            self.canvas.create_text(w // 2, h // 2,
                                    text="(empty)", fill=C_FG_DIM,
                                    font=("Segoe UI", 12))
            self._update_crumb()
            return

        self._draw_node(node, 2, 2, w - 4, h - 4, depth=0)
        self._update_crumb()

    def _draw_node(self, node: SizeNode, x, y, w, h, depth: int):
        """Lay out one node's children, nesting into folders that are big enough."""
        items = [(c.size, c) for c in node.children if c.size > 0]
        if not items:
            return
        for child, (cx, cy, cw, ch) in squarify(items, x, y, w, h):
            if cw < 1 or ch < 1:
                continue
            colour = treemap_colour(child)
            self.canvas.create_rectangle(
                cx, cy, cx + cw, cy + ch,
                fill=colour, outline="#12121c", width=1)
            self._rects.append((child, (cx, cy, cw, ch)))

            nest = (child.is_dir and child.children
                    and cw >= TREEMAP_NEST_MIN[0] and ch >= TREEMAP_NEST_MIN[1]
                    and depth < 2)
            if nest:
                # Title strip, then the children inside the remaining space
                self.canvas.create_text(
                    cx + 4, cy + 2, anchor="nw", text=child.name,
                    fill="#dfe6f5", font=("Segoe UI", 8, "bold"),
                    width=max(10, cw - 8))
                self._draw_node(child, cx + 3, cy + 14,
                                cw - 6, ch - 17, depth + 1)
            elif cw >= TREEMAP_MIN_LABEL[0] and ch >= TREEMAP_MIN_LABEL[1]:
                self.canvas.create_text(
                    cx + cw / 2, cy + ch / 2, text=child.name,
                    fill="#12121c" if not child.is_dir else "#dfe6f5",
                    font=("Segoe UI", 8), width=max(10, cw - 6))

    def _update_crumb(self):
        node = self.view
        if node is None:
            return
        self._crumb.configure(
            text=f"   {node.path}   —   {_human_size(node.size)}"
                 f"   ·   {len(node.children)} item(s)")

    def _set_info(self, text: str):
        self._info.configure(text="  " + text)

    # ── Interaction ───────────────────────────────────────────────────────

    def _hit(self, x, y):
        """Innermost rectangle under the cursor (drawn last = deepest)."""
        for node, (rx, ry, rw, rh) in reversed(self._rects):
            if rx <= x <= rx + rw and ry <= y <= ry + rh:
                return node
        return None

    def _on_motion(self, event):
        node = self._hit(event.x, event.y)
        if node is self._hover:
            return
        self._hover = node
        if node is None:
            self._set_info("")
            return
        share = (node.size / self.view.size * 100) if self.view.size else 0
        kind = "folder" if node.is_dir else (
            _EXT_TYPE.get(os.path.splitext(node.name)[1].lower(), "file"))
        self._set_info(f"{node.path}   —   {_human_size(node.size)}   "
                       f"({share:.1f}% of this view)   ·   {kind}")

    def _on_click(self, event):
        node = self._hit(event.x, event.y)
        if node and node.is_dir and node.children:
            self.view = node
            self._draw()

    def _on_double(self, event):
        node = self._hit(event.x, event.y)
        if node is None or node.is_dir:
            return
        # Send the panel to the file, so it can be acted on normally
        panel = self.manager.get_active_panel()
        if getattr(panel, "is_remote", False):
            return
        panel.change_directory(os.path.dirname(node.path),
                               select_name=os.path.basename(node.path))

    def _go_up(self):
        if self.view is not None and self.view.parent is not None:
            self.view = self.view.parent
            self._draw()

    def stop(self):
        self._stop.set()

# ══════════════════════════════════════════════════════════════════════════
#  DEL 40 — "Send to" hooks into your own programs
# ══════════════════════════════════════════════════════════════════════════
#
# A generic file manager cannot know about the rest of your toolbox.  This one
# can: define a tool once — which program, which file types it applies to —
# and it appears on the right-click menu for exactly those files.
#
# A tool is: name, command, shell, and the extensions it applies to.
# The command uses the same placeholders as the command library, so %F is the
# selected file and %L is every selected file, each quoted.

DEFAULT_TOOLS = [
    {
        "name": "Open with Notepad",
        "command": 'notepad "%F"',
        "shell": "cmd",
        "extensions": [".txt", ".log", ".ini", ".md", ".csv"],
        "folders": False,
        "detach": True,
    },
    {
        "name": "Open folder in Explorer",
        "command": 'explorer "%P"',
        "shell": "cmd",
        "extensions": ["*"],
        "folders": True,
        "detach": True,
    },
]


def load_tools() -> list:
    tools = _load_json_list(TOOLS_PATH)
    return tools if tools else [dict(t) for t in DEFAULT_TOOLS]


def save_tools(tools: list):
    _save_json_list(TOOLS_PATH, tools)


def tool_matches(tool: dict, paths: list) -> bool:
    """Does this tool apply to the current selection?

    An empty extension list means "no file types" — use "*" for any file.
    That way a tool meant for folders only (folders ticked, no extensions)
    does not quietly turn up on every file in the panel.
    """
    if not paths:
        return False
    exts = [e.lower().strip() for e in tool.get("extensions", []) if e.strip()]
    allow_folders = bool(tool.get("folders"))

    for p in paths:
        if os.path.isdir(p):
            if allow_folders:
                return True
            continue
        if "*" in exts:
            return True
        if os.path.splitext(p)[1].lower() in exts:
            return True
    return False


class ToolsConfigWindow(tk.Toplevel):
    """Manage the tools that appear on the “Send to” menu."""

    def __init__(self, manager: "EditorFrame"):
        super().__init__(manager)
        self.manager = manager
        self.configure(bg=C_BG)
        self.geometry("940x600")
        _setup_toplevel(self, "Send to — my tools", manager, modal=False)

        head = tk.Frame(self, bg=C_BG3)
        head.pack(fill="x")
        tk.Label(head, text="🔌  Send to — my tools", bg=C_BG3, fg=C_ACCENT,
                 font=("Segoe UI", 12, "bold")).pack(side="left", padx=10, pady=7)
        tk.Label(head, text="Each tool shows up on the right-click menu for the "
                            "file types you give it",
                 bg=C_BG3, fg=C_FG_DIM, font=("Segoe UI", 9)).pack(side="left")

        mid = tk.Frame(self, bg=C_BG)
        mid.pack(fill="both", expand=True, padx=10, pady=8)
        cols = ("types", "shell", "command")
        self.tree = ttk.Treeview(mid, columns=cols, selectmode="browse")
        self.tree.heading("#0",      text="Tool",       anchor="w")
        self.tree.heading("types",   text="File types", anchor="w")
        self.tree.heading("shell",   text="Shell",      anchor="w")
        self.tree.heading("command", text="Command",    anchor="w")
        self.tree.column("#0", width=200, stretch=True)
        self.tree.column("types", width=190)
        self.tree.column("shell", width=90)
        self.tree.column("command", width=420)
        sb = ttk.Scrollbar(mid, orient="vertical", command=self.tree.yview)
        self.tree.configure(yscrollcommand=sb.set)
        self.tree.pack(side="left", fill="both", expand=True)
        sb.pack(side="right", fill="y")
        self.tree.bind("<Double-1>", lambda e: self._edit())

        bot = tk.Frame(self, bg=C_BG)
        bot.pack(fill="x", padx=10, pady=(0, 10))
        self._status = tk.Label(bot, text="", bg=C_BG, fg=C_FG_DIM, anchor="w")
        self._status.pack(side="left", fill="x", expand=True)
        tk.Button(bot, text="Close", bg="grey", fg="white", width=9,
                  command=self.destroy).pack(side="right", padx=3)
        tk.Button(bot, text="🗑  Delete", bg="#ff8888", fg="black",
                  command=self._delete).pack(side="right", padx=3)
        tk.Button(bot, text="↓", width=3, bg="white", fg="black",
                  command=lambda: self._move(1)).pack(side="right", padx=2)
        tk.Button(bot, text="↑", width=3, bg="white", fg="black",
                  command=lambda: self._move(-1)).pack(side="right", padx=2)
        tk.Button(bot, text="Edit", bg="white", fg="black",
                  command=self._edit).pack(side="right", padx=3)
        tk.Button(bot, text="＋  New tool", bg="lightgreen", fg="black",
                  command=self._new).pack(side="right", padx=3)

        self.bind("<Return>", lambda e: self._edit())
        self._render()

    def _render(self):
        self.tree.delete(*self.tree.get_children())
        for i, tool in enumerate(self.manager.tools):
            exts = tool.get("extensions", [])
            types = ", ".join(exts) if exts else "(any file)"
            if tool.get("folders"):
                types += "  + folders"
            self.tree.insert("", "end", iid=str(i), text=tool.get("name", ""),
                             values=(types,
                                     SHELLS.get(tool.get("shell", "cmd"), "cmd"),
                                     tool.get("command", "")))
        self._status.configure(text=f"{len(self.manager.tools)} tool(s)")

    def _sel(self):
        sel = self.tree.selection()
        return int(sel[0]) if sel else None

    def _new(self):
        self._dialog()

    def _edit(self):
        i = self._sel()
        if i is not None:
            self._dialog(dict(self.manager.tools[i]), i)

    def _delete(self):
        i = self._sel()
        if i is None:
            return
        name = self.manager.tools[i].get("name", "")
        if _ask_yes_no("Delete", f"Delete the tool “{name}”?", parent=self):
            del self.manager.tools[i]
            self.manager.save_tools()
            self._render()

    def _move(self, delta: int):
        i = self._sel()
        if i is None:
            return
        j = i + delta
        t = self.manager.tools
        if 0 <= j < len(t):
            t[i], t[j] = t[j], t[i]
            self.manager.save_tools()
            self._render()
            self.tree.selection_set(str(j))

    def _dialog(self, initial: dict = None, index: int = None):
        top = tk.Toplevel(self)
        top.configure(bg=C_BG)
        top.resizable(False, False)
        _setup_toplevel(top, "Tool", self, modal=True)

        initial = initial or {"name": "", "command": "", "shell": "cmd",
                              "extensions": [], "folders": False, "detach": True}
        v_name   = tk.StringVar(value=initial.get("name", ""))
        v_shell  = tk.StringVar(value=initial.get("shell", "cmd"))
        v_ext    = tk.StringVar(value=" ".join(initial.get("extensions", [])))
        v_folder = tk.BooleanVar(value=bool(initial.get("folders")))
        v_detach = tk.BooleanVar(value=bool(initial.get("detach", True)))

        body = tk.Frame(top, bg=C_BG, padx=16, pady=14)
        body.pack(fill="both", expand=True)

        tk.Label(body, text="Name (as it appears on the menu):", bg=C_BG, fg=C_FG,
                 anchor="w").pack(fill="x")
        e_name = tk.Entry(body, textvariable=v_name, width=56, bg=C_BG2, fg=C_FG,
                          insertbackground=C_FG,
                          insertofftime=0, insertontime=9999999)
        e_name.pack(fill="x", pady=(0, 8))

        tk.Label(body, text="File types  (e.g.  .mp3 .wav .flac    or  *  for any):",
                 bg=C_BG, fg=C_FG, anchor="w").pack(fill="x")
        tk.Entry(body, textvariable=v_ext, width=56, bg=C_BG2, fg=C_FG,
                 insertbackground=C_FG,
                 insertofftime=0, insertontime=9999999).pack(fill="x", pady=(0, 2))
        tk.Label(body, text="Leave empty and tick the box below for a "
                            "folders-only tool.",
                 bg=C_BG, fg=C_FG_DIM, font=("Segoe UI", 8, "italic"),
                 anchor="w").pack(fill="x", pady=(0, 4))
        tk.Checkbutton(body, text="Also offer this tool for folders",
                       variable=v_folder, bg=C_BG, fg=C_FG, selectcolor=C_BG2,
                       activebackground=C_BG,
                       activeforeground=C_FG).pack(anchor="w", pady=(0, 8))

        tk.Label(body, text="Shell:", bg=C_BG, fg=C_FG, anchor="w").pack(fill="x")
        ttk.Combobox(body, textvariable=v_shell, width=16, state="readonly",
                     values=list(SHELLS.keys())).pack(anchor="w", pady=(0, 8))

        tk.Label(body, text="Command:", bg=C_BG, fg=C_FG, anchor="w").pack(fill="x")
        txt = tk.Text(body, width=56, height=5, bg=C_BG2, fg=C_FG,
                      insertbackground=C_FG, font=("Consolas", 9),
                      insertofftime=0, insertontime=9999999)
        txt.pack(fill="both", expand=True, pady=(0, 4))
        txt.insert("1.0", initial.get("command", ""))

        tk.Checkbutton(body, text="Start it and let go  (untick to capture the "
                                  "output in the command bar)",
                       variable=v_detach, bg=C_BG, fg=C_FG, selectcolor=C_BG2,
                       activebackground=C_BG,
                       activeforeground=C_FG).pack(anchor="w", pady=(0, 6))

        tk.Label(body, text=COMMAND_PLACEHOLDERS, bg=C_BG, fg=C_FG_DIM,
                 font=("Consolas", 8), justify="left",
                 anchor="w").pack(fill="x", pady=(2, 6))
        tk.Label(body,
                 text='Example:   python "C:\\1---Python\\MyTool.py" "%F"',
                 bg=C_BG, fg=C_FG_DIM, font=("Consolas", 8),
                 anchor="w").pack(fill="x", pady=(0, 10))

        def save(event=None):
            name = v_name.get().strip()
            command = txt.get("1.0", "end-1c").strip()
            if not name or not command:
                messagebox.showerror("Tool", "Name and command are both required.",
                                     parent=top)
                return
            exts = [e if e.startswith(".") or e == "*" else "." + e
                    for e in v_ext.get().replace(",", " ").split() if e.strip()]
            entry = {"name": name, "command": command, "shell": v_shell.get(),
                     "extensions": exts, "folders": v_folder.get(),
                     "detach": v_detach.get()}
            if index is None:
                self.manager.tools.append(entry)
            else:
                self.manager.tools[index] = entry
            self.manager.save_tools()
            self._render()
            top.destroy()

        btns = tk.Frame(body, bg=C_BG)
        btns.pack(fill="x")
        tk.Button(btns, text="Cancel", bg="grey", fg="white", width=10,
                  command=top.destroy).pack(side="right", padx=3)
        tk.Button(btns, text="Save", bg="lightgreen", fg="black", width=10,
                  command=save).pack(side="right", padx=3)
        e_name.bind("<Return>", save)
        txt.bind("<Control-Return>", save)
        e_name.focus_set()


# ══════════════════════════════════════════════════════════════════════════
#  DEL 41 — Fuzzy duplicates  (visually similar images, acoustically similar audio)
# ══════════════════════════════════════════════════════════════════════════
#
# Exact hashing only finds byte-identical files.  These two find the cases it
# misses: the same photo saved at another resolution or quality, and the same
# track ripped at another bitrate or into another format.
#
# Images  — dHash: shrink to 9x8 greyscale and record whether each pixel is
#           brighter than the one to its right.  That survives rescaling,
#           re-compression and small brightness shifts; it does NOT survive
#           cropping or rotation, which is the honest limit of the method.
# Audio   — ffmpeg decodes to 8 kHz mono, then a Philips-style fingerprint of
#           band-energy differences per frame.  Comparison slides one against
#           the other, so a track with a different amount of leading silence
#           still matches.

IMAGE_HASH_EXTS = {".jpg", ".jpeg", ".png", ".gif", ".bmp", ".webp", ".tiff", ".tif"}
AUDIO_HASH_EXTS = {".mp3", ".wav", ".flac", ".ogg", ".m4a", ".aac", ".wma", ".opus"}


def _find_ffmpeg() -> str:
    """Locate ffmpeg.exe — program folder first, then the shared Helpfiles."""
    candidates = [APP_ROOT / "Helpfiles" / "1---Movie" / "ffmpeg.exe",
                  APP_ROOT / "Helpfiles" / "ffmpeg.exe"]
    # Walk a few levels up: the shared movie helpers live above the program
    parent = APP_ROOT
    for _ in range(4):
        parent = parent.parent
        candidates.append(parent / "Helpfiles" / "1---Movie" / "ffmpeg.exe")
        candidates.append(parent / "Helpfiles" / "ffmpeg.exe")
    for c in candidates:
        try:
            if c.is_file():
                return str(c)
        except OSError:
            continue
    return shutil.which("ffmpeg") or ""


_FFMPEG = None


def ffmpeg_path() -> str:
    """Cached lookup of ffmpeg.exe (empty string when not found)."""
    global _FFMPEG
    if _FFMPEG is None:
        _FFMPEG = _find_ffmpeg()
    return _FFMPEG


# ── Images ────────────────────────────────────────────────────────────────

def image_phash(path: str) -> int:
    """64-bit difference hash of an image, or 0 if it cannot be read."""
    try:
        from PIL import Image
    except ImportError:
        raise RuntimeError("Image matching needs Pillow:  pip install pillow")
    try:
        with Image.open(path) as im:
            im = im.convert("L").resize((9, 8), Image.LANCZOS)
            px = list(im.getdata())
    except Exception:
        return 0

    bits = 0
    for row in range(8):
        base = row * 9
        for col in range(8):
            bits <<= 1
            if px[base + col] > px[base + col + 1]:
                bits |= 1
    return bits


def hamming(a: int, b: int) -> int:
    """Number of differing bits — how far apart two fingerprints are."""
    return bin(a ^ b).count("1")


# ── Audio ─────────────────────────────────────────────────────────────────

AUDIO_RATE      = 8000       # decode to 8 kHz mono; plenty for a fingerprint
AUDIO_SECONDS   = 90         # only the first 90 s are fingerprinted
AUDIO_FRAME     = 2048       # ~256 ms window
AUDIO_HOP       = 1024       # 50 % overlap
AUDIO_BANDS     = 17         # 17 band edges → 16 bands per frame
AUDIO_LOW_HZ    = 100        # band range — wide enough to hold real music
AUDIO_HIGH_HZ   = 3800       # (just under the 4 kHz Nyquist of 8 kHz audio)


def _decode_audio(path: str, seconds: int = AUDIO_SECONDS):
    """Decode any audio file to a mono float array via ffmpeg."""
    exe = ffmpeg_path()
    if not exe:
        raise RuntimeError(
            "Audio matching needs ffmpeg.\n\n"
            "Put ffmpeg.exe in Helpfiles/1---Movie/ next to the program, "
            "or anywhere on the PATH.")
    import numpy as np
    cmd = [exe, "-v", "quiet", "-i", path, "-t", str(seconds),
           "-f", "s16le", "-acodec", "pcm_s16le",
           "-ac", "1", "-ar", str(AUDIO_RATE), "-"]
    try:
        res = subprocess.run(cmd, capture_output=True, timeout=180,
                             **_no_window_kwargs())
    except subprocess.TimeoutExpired:
        raise RuntimeError(f"ffmpeg timed out on {os.path.basename(path)}")
    if not res.stdout:
        raise RuntimeError(f"ffmpeg could not decode {os.path.basename(path)}")
    samples = np.frombuffer(res.stdout, dtype="<i2").astype("float32") / 32768.0
    return samples


def audio_fingerprint(path: str):
    """A spectral profile of the audio: one normalised band vector per frame.

    A first attempt used single-bit "did this band rise?" flags (the classic
    Philips scheme).  It was too fragile here: where a band holds almost no
    energy, encoder noise flips the bit at random, and a 320 kbps MP3 of a
    file only scored ~78 % against the original.  Keeping the values
    continuous and normalising each frame is far steadier — loudness and
    bitrate fall out of the comparison, the SHAPE of the spectrum is what
    remains.

    Returns a float32 array of shape (frames, 16), or None if unreadable.
    """
    import numpy as np
    samples = _decode_audio(path)
    if samples.size < AUDIO_FRAME * 4:
        return None

    n_frames = 1 + (samples.size - AUDIO_FRAME) // AUDIO_HOP
    if n_frames < 8:
        return None

    window = np.hanning(AUDIO_FRAME).astype("float32")
    edges = np.logspace(np.log10(AUDIO_LOW_HZ), np.log10(AUDIO_HIGH_HZ),
                        AUDIO_BANDS)
    bin_hz = AUDIO_RATE / AUDIO_FRAME
    bins = np.clip((edges / bin_hz).astype(int), 1, AUDIO_FRAME // 2 - 1)

    n_bands = AUDIO_BANDS - 1
    energies = np.zeros((n_frames, n_bands), dtype="float32")
    for i in range(n_frames):
        start = i * AUDIO_HOP
        frame = samples[start:start + AUDIO_FRAME] * window
        spec = np.abs(np.fft.rfft(frame)) ** 2
        for b in range(n_bands):
            lo, hi = bins[b], max(bins[b] + 1, bins[b + 1])
            energies[i, b] = spec[lo:hi].sum()

    energies = np.log10(energies + 1e-10)

    # Drop near-silent frames: they carry no information and would otherwise
    # let two unrelated quiet recordings look alike.
    frame_level = energies.mean(axis=1)
    loud_enough = frame_level > (frame_level.max() - 6.0)
    if loud_enough.sum() >= 8:
        energies = energies[loud_enough]

    # Normalise every frame on its own — this is what removes loudness and
    # bitrate from the comparison and leaves the spectral shape.
    energies -= energies.mean(axis=1, keepdims=True)
    norms = np.linalg.norm(energies, axis=1, keepdims=True)
    energies /= np.maximum(norms, 1e-6)
    return energies.astype("float32")


def audio_similarity(fp_a, fp_b, max_shift: int = 30) -> float:
    """Best alignment between two spectral profiles, as a 0..1 similarity.

    One profile is slid against the other, so a different amount of leading
    silence or a trimmed start does not spoil an otherwise perfect match.
    """
    import numpy as np
    if fp_a is None or fp_b is None:
        return 0.0
    if len(fp_a) == 0 or len(fp_b) == 0:
        return 0.0

    best = 0.0
    for shift in range(-max_shift, max_shift + 1):
        if shift >= 0:
            a, b = fp_a[shift:], fp_b
        else:
            a, b = fp_a, fp_b[-shift:]
        n = min(len(a), len(b))
        if n < 8:                       # too little overlap to mean anything
            continue
        # Both are unit vectors per frame, so the row-wise dot product IS the
        # cosine similarity; -1..1 mapped onto 0..1.
        score = float(np.sum(a[:n] * b[:n], axis=1).mean())
        best = max(best, (score + 1.0) / 2.0)
    return best


def group_by_similarity(items: list, is_similar) -> list:
    """Union-find grouping — every file that matches any other lands together."""
    parent = list(range(len(items)))

    def find(i):
        while parent[i] != i:
            parent[i] = parent[parent[i]]
            i = parent[i]
        return i

    def union(i, j):
        ri, rj = find(i), find(j)
        if ri != rj:
            parent[rj] = ri

    for i in range(len(items)):
        for j in range(i + 1, len(items)):
            if is_similar(items[i], items[j]):
                union(i, j)

    groups = {}
    for i in range(len(items)):
        groups.setdefault(find(i), []).append(items[i])
    return [g for g in groups.values() if len(g) > 1]


# ══════════════════════════════════════════════════════════════════════════
#  DEL 42 — File tags  (colour labels independent of folder structure)
# ══════════════════════════════════════════════════════════════════════════
#
# Tags live in a sidecar file, not in the filesystem, so they work on any
# drive and never touch the files themselves.  A file may carry several
# labels, and a label can be found anywhere in the tree.
#
# The weak point of any path-keyed sidecar is that renaming or moving a file
# breaks the link.  This one is told about both: the rename and copy/move
# paths call remap(), so tags follow their files.

DEFAULT_LABELS = [
    {"name": "Important", "colour": "#d64545"},
    {"name": "Work",      "colour": "#d98324"},
    {"name": "Personal",  "colour": "#c9a227"},
    {"name": "Done",      "colour": "#3f9142"},
    {"name": "To sort",   "colour": "#3572b0"},
    {"name": "Keep",      "colour": "#7a4fb5"},
    {"name": "Junk",      "colour": "#6b6b6b"},
]


class TagStore:
    """Colour labels attached to files, kept in one JSON sidecar.

    Each entry records not just the labels but a small fingerprint of the file
    (its size and a hash of the first and last 64 KB).  That fingerprint is
    what makes it possible to find a tagged file again after somebody renames
    it in Explorer, where this program never got the chance to follow it.
    """

    SIG_CHUNK = 64 * 1024

    def __init__(self):
        self.labels: list = []
        self.tags: dict = {}          # normalised path → {labels, size, sig}
        # ── The ★ flag (DEL 42b) ──────────────────────────────────────────
        # A deliberately dumb second store: just a SET of paths, no labels, no
        # colours, no fingerprints.  It is the "I am done with this one" tick
        # you put on a file by hand, shown as ★ in its own narrow column and
        # toggled with one toolbar button.  Folders can carry it too, which is
        # why there is no fingerprint here — a folder has none.
        # It lives inside TagStore rather than beside it so that every place
        # that already calls remap() / clear() / prune() when files are moved,
        # renamed, trashed or purged keeps the flags right for free.
        self.flags: set = set()
        self.load()

    # ── Persistence ───────────────────────────────────────────────────────

    @staticmethod
    def _key(path: str) -> str:
        return os.path.normcase(os.path.abspath(path))

    def load(self):
        try:
            with open(TAGS_PATH, "r", encoding="utf-8") as fh:
                # Keys are paths here, and they are lower-cased - fm_unpack
                # gives them back in the same form the lookups build.
                data = fm_unpack_tree(json.load(fh))
            self.labels = data.get("labels") or [dict(l) for l in DEFAULT_LABELS]
            raw = data.get("tags") or {}
            raw_flags = data.get("flags") or []
        except FileNotFoundError:
            self.labels = [dict(l) for l in DEFAULT_LABELS]
            raw = {}
            raw_flags = []
        except Exception as exc:
            _log(f"Could not read tags.json: {exc}")
            self.labels = [dict(l) for l in DEFAULT_LABELS]
            raw = {}
            raw_flags = []

        self.flags = {self._key(p) for p in raw_flags if isinstance(p, str) and p}

        self.tags = {}
        for key, value in raw.items():
            if isinstance(value, list):        # older format: bare label list
                self.tags[key] = {"labels": list(value), "size": None, "sig": ""}
            elif isinstance(value, dict):
                self.tags[key] = {
                    "labels": list(value.get("labels", [])),
                    "size":   value.get("size"),
                    "sig":    value.get("sig", ""),
                }

    def save(self):
        try:
            with open(TAGS_PATH, "w", encoding="utf-8") as fh:
                json.dump(fm_pack_tree(
                    {"labels": self.labels, "tags": self.tags,
                     "flags": sorted(self.flags)}), fh,
                    indent=2, ensure_ascii=False)
        except Exception as exc:
            _log(f"Could not save tags.json: {exc}")

    # ── Fingerprints ──────────────────────────────────────────────────────

    @classmethod
    def fingerprint(cls, path: str):
        """(size, signature) for a file, or (None, "") if it cannot be read.

        Hashing the first and last chunk rather than the whole file keeps this
        instant even on a multi-gigabyte video, and is more than enough to
        tell one file from another in the same folder.
        """
        try:
            if not os.path.isfile(path):
                return None, ""
            size = os.path.getsize(path)
            h = hashlib.sha1()
            h.update(str(size).encode())
            with open(path, "rb") as fh:
                h.update(fh.read(cls.SIG_CHUNK))
                if size > cls.SIG_CHUNK * 2:
                    fh.seek(-cls.SIG_CHUNK, os.SEEK_END)
                    h.update(fh.read(cls.SIG_CHUNK))
            return size, h.hexdigest()
        except OSError:
            return None, ""

    # ── Labels ────────────────────────────────────────────────────────────

    def label_names(self) -> list:
        return [l.get("name", "") for l in self.labels]

    def colour_of(self, name: str) -> str:
        for l in self.labels:
            if l.get("name") == name:
                return l.get("colour", TC_MUTED)
        return TC_MUTED

    def rename_label(self, old: str, new: str):
        """Rename a label everywhere it is used."""
        if not new or old == new:
            return
        for l in self.labels:
            if l.get("name") == old:
                l["name"] = new
        for entry in self.tags.values():
            entry["labels"] = [new if n == old else n for n in entry["labels"]]
        self.save()

    def delete_label(self, name: str):
        self.labels = [l for l in self.labels if l.get("name") != name]
        for key in list(self.tags):
            remaining = [n for n in self.tags[key]["labels"] if n != name]
            if remaining:
                self.tags[key]["labels"] = remaining
            else:
                del self.tags[key]
        self.save()

    # ── Tagging ───────────────────────────────────────────────────────────

    def get(self, path: str) -> list:
        entry = self.tags.get(self._key(path))
        return list(entry["labels"]) if entry else []

    def set(self, path: str, names: list):
        key = self._key(path)
        names = [n for n in dict.fromkeys(names) if n]
        if not names:
            self.tags.pop(key, None)
            return
        size, sig = self.fingerprint(path)
        self.tags[key] = {"labels": names, "size": size, "sig": sig}

    def toggle(self, paths: list, name: str) -> bool:
        """Add the label to every path, or remove it if they all have it."""
        everyone_has = all(name in self.get(p) for p in paths) if paths else False
        for p in paths:
            current = list(self.get(p))
            if everyone_has:
                current = [n for n in current if n != name]
            elif name not in current:
                current.append(name)
            self.set(p, current)
        self.save()
        return not everyone_has          # True when the label was added

    def clear(self, paths: list):
        for p in paths:
            key = self._key(p)
            self.tags.pop(key, None)
            self.flags.discard(key)
        self.save()

    # ── The ★ flag ────────────────────────────────────────────────────────
    #
    # One tick per file or folder, nothing else.  Meant for the "I have dealt
    # with this one" pass over a working folder: flag what is finished, leave
    # the rest bare, and the ★ column tells you at a glance which is which.

    def is_flagged(self, path: str) -> bool:
        return self._key(path) in self.flags

    def set_flag(self, path: str, on: bool):
        key = self._key(path)
        if on:
            self.flags.add(key)
        else:
            self.flags.discard(key)

    def toggle_flags(self, paths: list) -> bool:
        """Flag every path, or clear them all if they are ALREADY all flagged.

        The all-or-nothing rule is the same one the colour labels use: with a
        mixed selection the button FILLS the gaps rather than inverting each
        row, because "make these all done" is what you meant far more often
        than "swap whatever each one happens to be".

        Returns True when the flag was put ON.
        """
        if not paths:
            return False
        everyone_has = all(self.is_flagged(p) for p in paths)
        for p in paths:
            self.set_flag(p, not everyone_has)
        self.save()
        return not everyone_has

    def clear_flags(self, paths: list):
        for p in paths:
            self.flags.discard(self._key(p))
        self.save()

    def clear_all_flags(self) -> int:
        n = len(self.flags)
        self.flags.clear()
        self.save()
        return n

    def flagged_paths(self) -> list:
        return sorted(self.flags)

    # ── Keeping up with the filesystem ────────────────────────────────────

    def remap(self, pairs: list):
        """Follow files that moved: pairs of (old_path, new_path)."""
        changed = False
        for old, new in pairs:
            if not old or not new:
                continue
            old_key, new_key = self._key(old), self._key(new)
            if old_key == new_key:
                continue
            entry = self.tags.pop(old_key, None)
            if entry:
                self.tags[new_key] = entry
                changed = True
            else:
                # The old path may be a FOLDER that was moved — carry every
                # tagged file underneath it along with the folder.
                prefix = old_key + os.sep
                moved = [k for k in self.tags if k.startswith(prefix)]
                for k in moved:
                    self.tags[new_key + k[len(old_key):]] = self.tags.pop(k)
                    changed = True
            # ★ flags follow the very same moves — the item itself, and, when a
            # folder moved, everything flagged underneath it.
            if old_key in self.flags:
                self.flags.discard(old_key)
                self.flags.add(new_key)
                changed = True
            f_prefix = old_key + os.sep
            f_moved = [k for k in self.flags if k.startswith(f_prefix)]
            for k in f_moved:
                self.flags.discard(k)
                self.flags.add(new_key + k[len(old_key):])
                changed = True
        if changed:
            self.save()

    def reattach(self, extra_folders: list = None, progress=None) -> list:
        """Re-find tagged files renamed OUTSIDE this program.

        A rename done in Explorer leaves a tag pointing at a path that no
        longer exists.  Each orphan is matched against untagged files by size
        and content signature — never by name, which is exactly the thing that
        changed.  A match is only accepted when it is unambiguous: if two
        files in the search area have the same size and signature, neither is
        chosen, because there is no way to know which one was meant.

        Returns [(old_path, new_path)] for what was re-attached.
        """
        orphans = [(k, e) for k, e in self.tags.items()
                   if not os.path.exists(k) and e.get("sig")]
        if not orphans:
            return []

        # Look in each orphan's own folder, plus anywhere else asked for
        folders = {os.path.dirname(k) for k, _e in orphans}
        for extra in (extra_folders or []):
            if os.path.isdir(extra):
                folders.add(os.path.abspath(extra))

        # Fingerprint every untagged file in those folders, once
        pool = {}
        for folder in folders:
            try:
                names = os.listdir(folder)
            except OSError:
                continue
            for name in names:
                cand = os.path.join(folder, name)
                if not os.path.isfile(cand):
                    continue
                if self._key(cand) in self.tags:
                    continue                      # already carries tags
                size, sig = self.fingerprint(cand)
                if not sig:
                    continue
                pool.setdefault((size, sig), []).append(cand)

        reattached = []
        for i, (old_key, entry) in enumerate(orphans, 1):
            if progress:
                progress(i, len(orphans), old_key)
            match = pool.get((entry.get("size"), entry.get("sig")))
            if not match or len(match) != 1:
                continue                          # missing, or ambiguous
            new_path = match[0]
            new_key = self._key(new_path)
            if new_key in self.tags:
                continue                          # claimed by an earlier orphan
            self.tags[new_key] = self.tags.pop(old_key)
            reattached.append((old_key, new_path))

        if reattached:
            self.save()
        return reattached

    def find(self, label: str = "") -> list:
        """Every tagged path, optionally only those carrying one label."""
        out = []
        for key, entry in self.tags.items():
            names = entry["labels"]
            if label and label not in names:
                continue
            out.append((key, names))
        return sorted(out)

    def prune(self) -> int:
        """Drop entries whose file no longer exists. Returns how many went."""
        gone = [k for k in self.tags if not os.path.exists(k)]
        for k in gone:
            del self.tags[k]
        gone_flags = [k for k in self.flags if not os.path.exists(k)]
        for k in gone_flags:
            self.flags.discard(k)
        if gone or gone_flags:
            self.save()
        return len(gone) + len(gone_flags)



class TagManagerWindow(tk.Toplevel):
    """Edit the labels and see everything that carries them."""

    def __init__(self, manager: "EditorFrame"):
        super().__init__(manager)
        self.manager = manager
        self.store = manager.tagstore

        self.configure(bg=C_BG)
        self.geometry("980x620")
        _setup_toplevel(self, "File tags", manager, modal=False)

        head = tk.Frame(self, bg=C_BG3)
        head.pack(fill="x")
        tk.Label(head, text="🏷  File tags", bg=C_BG3, fg=C_ACCENT,
                 font=("Segoe UI", 12, "bold")).pack(side="left", padx=10, pady=7)
        tk.Label(head, text="Tags follow their files when you rename or move them",
                 bg=C_BG3, fg=C_FG_DIM, font=("Segoe UI", 9)).pack(side="left")

        body = tk.Frame(self, bg=C_BG)
        body.pack(fill="both", expand=True, padx=10, pady=8)

        # ── Labels ────────────────────────────────────────────────────────
        left = tk.Frame(body, bg=C_BG)
        left.pack(side="left", fill="y")
        tk.Label(left, text="Labels", bg=C_BG, fg=C_FG, anchor="w").pack(fill="x")
        self.label_list = tk.Listbox(left, width=22, height=16, bg=C_BG2, fg=C_FG,
                                     selectbackground="#3a5a8c",
                                     highlightthickness=0, activestyle="none",
                                     font=("Segoe UI", 10))
        self.label_list.pack(fill="y", expand=True)
        self.label_list.bind("<<ListboxSelect>>", lambda e: self._render_files())

        lb = tk.Frame(left, bg=C_BG)
        lb.pack(fill="x", pady=4)
        tk.Button(lb, text="＋", width=3, bg="lightgreen", fg="black",
                  command=self._new_label).pack(side="left", padx=1)
        tk.Button(lb, text="Rename", bg="white", fg="black",
                  command=self._rename_label).pack(side="left", padx=1)
        tk.Button(lb, text="Colour", bg="white", fg="black",
                  command=self._recolour_label).pack(side="left", padx=1)
        tk.Button(lb, text="🗑", width=3, bg="#ff8888", fg="black",
                  command=self._delete_label).pack(side="left", padx=1)

        # ── Tagged files ──────────────────────────────────────────────────
        right = tk.Frame(body, bg=C_BG)
        right.pack(side="left", fill="both", expand=True, padx=(10, 0))
        tk.Label(right, text="Tagged files", bg=C_BG, fg=C_FG,
                 anchor="w").pack(fill="x")
        self.tree = ttk.Treeview(right, columns=("labels", "folder"),
                                 selectmode="browse")
        self.tree.heading("#0",     text="File",   anchor="w")
        self.tree.heading("labels", text="Labels", anchor="w")
        self.tree.heading("folder", text="Folder", anchor="w")
        self.tree.column("#0", width=220, stretch=True)
        self.tree.column("labels", width=170)
        self.tree.column("folder", width=330)
        sb = ttk.Scrollbar(right, orient="vertical", command=self.tree.yview)
        self.tree.configure(yscrollcommand=sb.set)
        self.tree.pack(side="left", fill="both", expand=True)
        sb.pack(side="right", fill="y")
        self.tree.tag_configure("missing", foreground=TC_BAD)
        self.tree.bind("<Double-1>", lambda e: self._goto())

        bot = tk.Frame(self, bg=C_BG)
        bot.pack(fill="x", padx=10, pady=(0, 10))
        self._status = tk.Label(bot, text="", bg=C_BG, fg=C_FG_DIM, anchor="w")
        self._status.pack(side="left", fill="x", expand=True)
        tk.Button(bot, text="Close", bg="grey", fg="white", width=9,
                  command=self.destroy).pack(side="right", padx=3)
        tk.Button(bot, text="Remove tags from missing files", bg="white",
                  fg="black", command=self._prune).pack(side="right", padx=3)
        tk.Button(bot, text="🔎  Find renamed files", bg="lightgreen", fg="black",
                  command=self._reattach).pack(side="right", padx=3)
        tk.Button(bot, text="Go to file", bg="lightblue", fg="black",
                  command=self._goto).pack(side="right", padx=3)

        self.bind("<Return>", lambda e: self._goto())
        self._render_labels()
        self._render_files()

    # ── Rendering ─────────────────────────────────────────────────────────

    def _render_labels(self, keep: str = ""):
        self.label_list.delete(0, "end")
        self.label_list.insert("end", "(all tagged files)")
        for l in self.store.labels:
            self.label_list.insert("end", f"●  {l.get('name', '')}")
            self.label_list.itemconfig("end", foreground=l.get("colour", C_FG))
        # Restore the selection where possible
        idx = 0
        if keep:
            names = self.store.label_names()
            if keep in names:
                idx = names.index(keep) + 1
        self.label_list.selection_clear(0, "end")
        self.label_list.selection_set(idx)

    def _selected_label(self) -> str:
        sel = self.label_list.curselection()
        if not sel or sel[0] == 0:
            return ""
        names = self.store.label_names()
        i = sel[0] - 1
        return names[i] if 0 <= i < len(names) else ""

    def _render_files(self):
        label = self._selected_label()
        self.tree.delete(*self.tree.get_children())
        rows = self.store.find(label)
        missing = 0
        for path, names in rows:
            exists = os.path.exists(path)
            if not exists:
                missing += 1
            self.tree.insert("", "end", iid=path,
                             text=os.path.basename(path),
                             values=("  ".join(names), os.path.dirname(path)),
                             tags=() if exists else ("missing",))
        what = f"“{label}”" if label else "all labels"
        self._status.configure(
            text=f"{len(rows)} file(s) with {what}"
                 + (f"   ·   {missing} no longer exist (shown in red)"
                    if missing else ""))

    # ── Label editing ─────────────────────────────────────────────────────

    def _new_label(self):
        name = _ask_text(self, "New label", "Label name:")
        if not name:
            return
        if name in self.store.label_names():
            messagebox.showerror("Tags", "That label already exists.", parent=self)
            return
        colour = self._ask_colour("#3572b0")
        if not colour:
            return
        self.store.labels.append({"name": name, "colour": colour})
        self.store.save()
        self._render_labels(name)
        self._render_files()
        self.manager.refresh_panels()

    def _ask_colour(self, initial: str) -> str:
        try:
            from tkinter import colorchooser
            rgb, hexval = colorchooser.askcolor(color=initial, parent=self,
                                                title="Label colour")
            return hexval or ""
        except Exception:
            return _ask_text(self, "Colour", "Colour as #rrggbb:",
                             initial=initial) or ""

    def _rename_label(self):
        old = self._selected_label()
        if not old:
            return
        new = _ask_text(self, "Rename label", "New name:", initial=old)
        if new and new != old:
            if new in self.store.label_names():
                messagebox.showerror("Tags", "That label already exists.",
                                     parent=self)
                return
            self.store.rename_label(old, new)
            self._render_labels(new)
            self._render_files()
            self.manager.refresh_panels()

    def _recolour_label(self):
        name = self._selected_label()
        if not name:
            return
        colour = self._ask_colour(self.store.colour_of(name))
        if colour:
            for l in self.store.labels:
                if l.get("name") == name:
                    l["colour"] = colour
            self.store.save()
            self._render_labels(name)
            self.manager.refresh_panels()

    def _delete_label(self):
        name = self._selected_label()
        if not name:
            return
        used = len(self.store.find(name))
        if not _ask_yes_no(
                "Delete label",
                f"Delete the label “{name}”?\n\n"
                f"It will be removed from {used} file(s).\n"
                "The files themselves are not touched.", parent=self):
            return
        self.store.delete_label(name)
        self._render_labels()
        self._render_files()
        self.manager.refresh_panels()

    # ── Files ─────────────────────────────────────────────────────────────

    def _goto(self):
        sel = self.tree.selection()
        if not sel:
            return
        path = sel[0]
        if not os.path.exists(path):
            messagebox.showerror("Tags", f"This file no longer exists:\n{path}",
                                 parent=self)
            return
        panel = self.manager.get_active_panel()
        if getattr(panel, "is_remote", False):
            messagebox.showinfo("Tags", "The active panel is mounted on FTP.",
                                parent=self)
            return
        panel.change_directory(os.path.dirname(path),
                               select_name=os.path.basename(path))

    def _reattach(self):
        """Hunt down tagged files that were renamed outside this program."""
        orphans = [k for k in self.store.tags if not os.path.exists(k)]
        if not orphans:
            _flash_ok(self, "Every tagged file is where it should be.", "Tags")
            return

        # Also search both panel folders — a file may have been renamed and
        # moved in one go
        extra = []
        for side in ("left", "right"):
            panel = getattr(self.manager, f"{side}_panel", None)
            if panel is not None and not getattr(panel, "is_remote", False):
                extra.append(panel.current_path)

        found = self.store.reattach(extra_folders=extra)
        self._render_files()
        self.manager.refresh_panels()

        if not found:
            messagebox.showinfo(
                "Find renamed files",
                f"{len(orphans)} tagged file(s) are missing, but no match was "
                "found.\n\n"
                "A file is only matched when its size and content signature "
                "are an exact, unambiguous match — if two files look identical "
                "neither is chosen, and a file that was edited after being "
                "renamed no longer matches at all.", parent=self)
            return

        detail = "\n".join(
            f"   {os.path.basename(old)}  →  {os.path.basename(new)}"
            for old, new in found[:15])
        messagebox.showinfo(
            "Find renamed files",
            f"Re-attached {len(found)} of {len(orphans)} missing tag(s):\n\n"
            + detail + ("\n   …" if len(found) > 15 else ""), parent=self)

    def _prune(self):
        gone = self.store.prune()
        self._render_files()
        self.manager.refresh_panels()
        _flash_ok(self, f"Removed tags from {gone} missing file(s).", "Tags")


# ══════════════════════════════════════════════════════════════════════════
#  DEL 43 — Dates & deletion settings
# ══════════════════════════════════════════════════════════════════════════

class DatesDeleteSettingsWindow(tk.Toplevel):
    """One place for "what may change a file's date" and how Delete behaves."""

    def __init__(self, manager: "EditorFrame"):
        super().__init__(manager)
        self.manager = manager
        s = manager.settings

        self.configure(bg=C_BG)
        self.resizable(False, False)
        _setup_toplevel(self, "Dates & deletion", manager, modal=False)

        self.v_unpack = tk.BooleanVar(value=s.get("keep_dates_unpack", True))
        self.v_copy   = tk.BooleanVar(value=s.get("keep_dates_copy", True))
        self.v_trash  = tk.BooleanVar(value=s.get("delete_use_trash", True))
        self.v_small  = tk.StringVar(value=str(s.get("trash_small_max_mb", 5)))
        self.v_weeks  = tk.StringVar(value=str(s.get("trash_small_weeks", 2)))
        self.v_hours  = tk.StringVar(value=str(s.get("trash_large_hours", 24)))
        self.v_delay  = tk.StringVar(value=str(s.get("trash_startup_delay_min", 5)))

        body = tk.Frame(self, bg=C_BG, padx=18, pady=14)
        body.pack(fill="both", expand=True)

        # ── Dates ─────────────────────────────────────────────────────────
        tk.Label(body, text="🕒  File dates", bg=C_BG, fg=C_ACCENT,
                 font=("Segoe UI", 12, "bold")).pack(anchor="w")
        tk.Label(body,
                 text="What each operation does to the “Modified” date:",
                 bg=C_BG, fg=C_FG_DIM, font=("Segoe UI", 9),
                 anchor="w").pack(fill="x", pady=(2, 8))

        tk.Checkbutton(
            body, text="Unpacking  —  keep the dates stored in the archive",
            variable=self.v_unpack, bg=C_BG, fg=C_FG, selectcolor=C_BG2,
            activebackground=C_BG, activeforeground=C_FG,
            anchor="w").pack(fill="x")
        tk.Label(body,
                 text="       Off = everything you unpack gets today's date.\n"
                      "       ZIP used to lose the original date whatever you\n"
                      "       wanted; it now follows this setting like the rest.",
                 bg=C_BG, fg=C_FG_DIM, font=("Segoe UI", 8),
                 justify="left", anchor="w").pack(fill="x", pady=(0, 6))

        tk.Checkbutton(
            body, text="Copying  —  the copy keeps the original's date",
            variable=self.v_copy, bg=C_BG, fg=C_FG, selectcolor=C_BG2,
            activebackground=C_BG, activeforeground=C_FG,
            anchor="w").pack(fill="x")
        tk.Label(body,
                 text="       Off = every copy is dated now, as if newly made.",
                 bg=C_BG, fg=C_FG_DIM, font=("Segoe UI", 8),
                 justify="left", anchor="w").pack(fill="x", pady=(0, 6))

        tk.Label(body,
                 text="Never changes a file's date, whatever you set here:\n"
                      "   •  Renaming a file or folder\n"
                      "   •  Moving it (the file keeps its date; only the\n"
                      "      folder it left and the one it arrived in are touched\n"
                      "      — that is Windows, not this program)\n"
                      "   •  Changing attributes (read-only, hidden, …)\n"
                      "   •  Packing — archives store the original dates\n"
                      "To set a date deliberately, use right-click →\n"
                      "“Change attributes…”, which can stamp a date you choose.",
                 bg=C_BG, fg=C_FG_DIM, font=("Segoe UI", 8),
                 justify="left", anchor="w").pack(fill="x", pady=(2, 10))

        tk.Frame(body, bg=C_SEP, height=1).pack(fill="x", pady=6)

        # ── Deletion ──────────────────────────────────────────────────────
        tk.Label(body, text="🗑  Deletion", bg=C_BG, fg=C_ACCENT,
                 font=("Segoe UI", 12, "bold")).pack(anchor="w", pady=(4, 0))
        tk.Label(body,
                 text="Delete RENAMES the item in place to a ~deleted~<date>~ name,\n"
                      "freeing the original name at once and hiding it from the panels.\n"
                      "A start-up sweep then physically removes old trash — small files\n"
                      "after some weeks, larger files after some hours — so nothing\n"
                      "lingers, yet a mistake gives you time to Restore it (🗑 window).",
                 bg=C_BG, fg=C_FG_DIM, font=("Segoe UI", 9),
                 justify="left", anchor="w").pack(fill="x", pady=(2, 8))

        tk.Checkbutton(
            body, text="Use the in-place trash (off = delete straight to the Recycle Bin)",
            variable=self.v_trash, bg=C_BG, fg=C_FG, selectcolor=C_BG2,
            activebackground=C_BG, activeforeground=C_FG,
            anchor="w").pack(fill="x", pady=(0, 6))

        def _num_row(label_before, var, label_after):
            r = tk.Frame(body, bg=C_BG); r.pack(fill="x", pady=1)
            tk.Label(r, text=label_before, bg=C_BG, fg=C_FG).pack(side="left")
            tk.Entry(r, textvariable=var, width=5, bg=C_BG2, fg=C_FG,
                     insertbackground=C_FG,
                     insertofftime=0, insertontime=9999999).pack(side="left", padx=4)
            tk.Label(r, text=label_after, bg=C_BG, fg=C_FG).pack(side="left")

        _num_row("A file is “small” when it is under", self.v_small, "MB")
        _num_row("Small trash is purged after", self.v_weeks, "weeks")
        _num_row("Larger trash is purged after", self.v_hours, "hours   (max 30)")
        _num_row("At start-up, wait", self.v_delay, "minutes before sweeping")

        tk.Label(body,
                 text="       “Empty ALL now” in the 🗑 window purges everything\n"
                      "       immediately, ignoring these limits.  Purged items go to\n"
                      "       the Windows Recycle Bin.",
                 bg=C_BG, fg=C_FG_DIM, font=("Segoe UI", 8),
                 justify="left", anchor="w").pack(fill="x", pady=(4, 10))

        btns = tk.Frame(body, bg=C_BG)
        btns.pack(fill="x", pady=(6, 0))
        tk.Button(btns, text="Cancel", bg="grey", fg="white", width=10,
                  command=self.destroy).pack(side="right", padx=3)
        tk.Button(btns, text="✔  Save", bg="lightgreen", fg="black", width=11,
                  command=self._save).pack(side="right", padx=3)
        self.bind("<Return>", lambda e: self._save())

    def _save(self):
        s = self.manager.settings
        s["keep_dates_unpack"] = self.v_unpack.get()
        s["keep_dates_copy"]   = self.v_copy.get()
        s["delete_use_trash"]  = self.v_trash.get()
        try:
            s["trash_small_max_mb"]      = max(0.0, float(self.v_small.get()))
            s["trash_small_weeks"]       = max(0.0, float(self.v_weeks.get()))
            s["trash_large_hours"]       = max(0.0, min(30.0, float(self.v_hours.get())))
            s["trash_startup_delay_min"] = max(0.0, float(self.v_delay.get()))
        except ValueError:
            messagebox.showerror("Deletion",
                                 "Enter numbers for the size / time fields.",
                                 parent=self)
            return
        self.manager.apply_date_policy()
        self.manager.save_settings()
        _flash_ok(self, "Saved.", "Deletion")
        self.destroy()


# ══════════════════════════════════════════════════════════════════════════
#  DEL 46 — Network location chooser  (ready-made lists + scanning)
# ══════════════════════════════════════════════════════════════════════════
#
# The old "Network drive…" item was a bare text box: it blinked, and it assumed
# you already knew the exact \\server\share by heart.  This window instead SHOWS
# you what is there — the drives Windows has mapped, your saved favourites, the
# paths you used recently — and can go looking for more (ARP sweep of the local
# subnet, then the SMB shares each machine offers).

class NetSignInDialog(tk.Toplevel):
    """Sign in to a computer that answers but shows no drives.

    The sign-in is kept in Windows AND in File manager's own list
    (Helpfiles\\redigerare\\net_logins.json), so the computer is found again
    next time - also after Windows is reinstalled - without typing it again."""

    def __init__(self, parent, host: str, on_done=None):
        super().__init__(parent)
        self._host = host.strip().strip("\\/")
        self._on_done = on_done
        self._busy = False
        self.configure(bg=C_BG)
        self.geometry("460x250")
        self.resizable(False, False)
        _setup_toplevel(self, f"Sign in to {self._host}", parent, modal=True)

        saved = _net_logins_load().get(_net_host_key(self._host), {})
        self.var_user = tk.StringVar(value=saved.get("user", ""))
        self.var_pw   = tk.StringVar(value=_net_decode_pw(saved.get("_pw", "")))

        tk.Label(self, text=f"🔑  Sign in to {self._host}", bg=C_BG, fg=C_ACCENT,
                 font=("Segoe UI", 12, "bold")).pack(anchor="w", padx=14,
                                                     pady=(12, 2))
        tk.Label(self, text="Use a user name and password that works ON that "
                            "computer.\nIt is saved, so the drives are found "
                            "again next time.",
                 bg=C_BG, fg=C_FG_DIM, justify="left",
                 font=("Segoe UI", 9)).pack(anchor="w", padx=14)

        form = tk.Frame(self, bg=C_BG)
        form.pack(fill="x", padx=14, pady=10)
        tk.Label(form, text="User:", bg=C_BG, fg=C_FG, width=10,
                 anchor="w").grid(row=0, column=0, pady=2)
        eu = tk.Entry(form, textvariable=self.var_user, bg=C_BG2, fg=C_FG,
                      insertbackground=C_FG, insertofftime=0,
                      insertontime=9999999)
        eu.grid(row=0, column=1, sticky="ew", pady=2)
        tk.Label(form, text="Password:", bg=C_BG, fg=C_FG, width=10,
                 anchor="w").grid(row=1, column=0, pady=2)
        ep = tk.Entry(form, textvariable=self.var_pw, show="●", bg=C_BG2,
                      fg=C_FG, insertbackground=C_FG, insertofftime=0,
                      insertontime=9999999)
        ep.grid(row=1, column=1, sticky="ew", pady=2)
        form.columnconfigure(1, weight=1)
        eu.bind("<Return>", lambda e: ep.focus_set())
        ep.bind("<Return>", lambda e: self._ok())

        self.msg = tk.Label(self, text="", bg=C_BG, fg=TC_BAD, anchor="w",
                            justify="left", wraplength=430,
                            font=("Segoe UI", 9))
        self.msg.pack(fill="x", padx=14)

        bar = tk.Frame(self, bg=C_BG)
        bar.pack(side="bottom", fill="x", padx=14, pady=10)
        tk.Button(bar, text="Cancel", bg="grey", fg="white", width=9,
                  command=self.destroy).pack(side="right", padx=3)
        tk.Button(bar, text="Sign in", bg="lightgreen", fg="black", width=9,
                  command=self._ok).pack(side="right", padx=3)
        (ep if self.var_user.get() else eu).focus_set()

    def _ok(self):
        if self._busy:
            return
        self._busy = True
        self.msg.config(text="Signing in …", fg=C_FG_DIM)
        host, user, pw = self._host, self.var_user.get(), self.var_pw.get()

        def work():
            ok, text = _net_sign_in(host, user, pw, remember=True)
            _ui_call(self, lambda: self._finished(ok, text))

        threading.Thread(target=work, daemon=True).start()

    def _finished(self, ok: bool, text: str):
        self._busy = False
        if not ok:
            self.msg.config(text=text, fg=TC_BAD)
            return
        cb = self._on_done
        self.destroy()
        if cb:
            cb()


class NetworkDriveDialog(tk.Toplevel):
    """Pick (or find) a network location and open it in a panel.

    Everything is a row you can double-click.  The manual path field is still
    there for when you do know the address, but it is now the last resort
    rather than the only option.
    """

    GRP_MAPPED = "Mapped network drives"
    GRP_FAV    = "Saved favourites"
    GRP_RECENT = "Recently opened"
    GRP_FOUND  = "Computers found on the network"

    def __init__(self, manager: "EditorFrame", side: str = None):
        super().__init__(manager)
        self.manager = manager
        self.side    = side or manager.active_panel
        self._stop   = threading.Event()
        self._busy   = False
        self._groups = {}        # group title → tree iid
        self._paths  = {}        # tree iid    → UNC path (or "" for a host row)
        self._hosts  = {}        # tree iid    → host name/IP (expandable)
        self._loaded = set()     # host iids whose shares are already listed
        self._signin = {}        # tree iid    → host that needs a sign-in

        self.configure(bg=C_BG)
        self.geometry("860x600")
        _setup_toplevel(self, "Network locations", manager, modal=False)
        self.protocol("WM_DELETE_WINDOW", self._close)

        self._build()
        self.refresh_lists()

    # ── Layout ────────────────────────────────────────────────────────────

    def _build(self):
        head = tk.Frame(self, bg=C_BG)
        head.pack(fill="x", padx=12, pady=(12, 6))
        tk.Label(head, text="🖧  Network locations", bg=C_BG, fg=C_ACCENT,
                 font=("Segoe UI", 13, "bold")).pack(anchor="w")
        tk.Label(head,
                 text="Double-click anything below to open it in the "
                      f"{self.side.upper()} panel.  Expand a computer to see "
                      "what it shares.",
                 bg=C_BG, fg=C_FG_DIM, font=("Segoe UI", 9),
                 justify="left").pack(anchor="w", pady=(2, 0))

        # ── Manual path (still no-blink) ──────────────────────────────────
        manual = tk.Frame(self, bg=C_BG)
        manual.pack(fill="x", padx=12, pady=(4, 6))
        tk.Label(manual, text="Path:", bg=C_BG, fg=C_FG,
                 font=("Segoe UI", 9)).pack(side="left")
        self.e_path = tk.Entry(manual, insertofftime=0, insertontime=9999999)
        self.e_path.pack(side="left", fill="x", expand=True, padx=(6, 6))
        self.e_path.bind("<Return>", lambda e: self._open_typed())
        tk.Button(manual, text="Open", bg="lightgreen", fg="black", width=9,
                  command=self._open_typed).pack(side="left", padx=2)
        tk.Button(manual, text="Map drive letter…", bg="lightblue", fg="black",
                  command=self._map_typed).pack(side="left", padx=2)
        tk.Button(manual, text="Connection file…", bg="lightblue", fg="black",
                  command=lambda: self.manager.open_connect_pc(
                      on_done=self.refresh_lists)).pack(side="left", padx=2)

        # ── The list ──────────────────────────────────────────────────────
        mid = tk.Frame(self, bg=C_BG)
        mid.pack(fill="both", expand=True, padx=12, pady=(2, 6))
        self.tree = ttk.Treeview(mid, columns=("what", "state"),
                                 selectmode="browse")
        self.tree.heading("#0",    text="Location")
        self.tree.heading("what",  text="Kind")
        self.tree.heading("state", text="Status")
        self.tree.column("#0",    width=440, anchor="w")
        self.tree.column("what",  width=190, anchor="w")
        self.tree.column("state", width=150, anchor="w")
        sb = ttk.Scrollbar(mid, orient="vertical", command=self.tree.yview)
        self.tree.configure(yscrollcommand=sb.set)
        sb.pack(side="right", fill="y")
        self.tree.pack(side="left", fill="both", expand=True)
        self.tree.tag_configure("group",  foreground=TC_INFO)
        self.tree.tag_configure("ok",     foreground=TC_OK)
        self.tree.tag_configure("bad",    foreground=TC_BAD)
        self.tree.tag_configure("muted",  foreground=TC_MUTED)
        self.tree.bind("<Double-1>", self._on_activate)
        self.tree.bind("<Return>",   self._on_activate)
        self.tree.bind("<<TreeviewOpen>>", self._on_expand)
        self.tree.bind("<Button-3>", self._on_right_click)

        # ── Buttons ───────────────────────────────────────────────────────
        bar = tk.Frame(self, bg=C_BG)
        bar.pack(fill="x", padx=12, pady=(0, 10))
        tk.Button(bar, text="⚡  Quick scan (ARP)", bg="lightblue", fg="black",
                  command=self._quick_scan).pack(side="left", padx=(0, 4))
        tk.Button(bar, text="📡  Ping sweep this subnet", bg="lightblue",
                  fg="black", command=self._ping_sweep).pack(side="left", padx=4)
        tk.Button(bar, text="🔍  Full scanner…", bg="lightgrey", fg="black",
                  command=lambda: self.manager.open_network_window()
                  ).pack(side="left", padx=4)
        tk.Button(bar, text="🔄  Refresh", bg="lightgrey", fg="black",
                  command=self.refresh_lists).pack(side="left", padx=4)
        tk.Button(bar, text="Close", bg="grey", fg="white", width=9,
                  command=self._close).pack(side="right")

        self.status = tk.Label(self, text="", bg=C_BG, fg=C_FG_DIM,
                               anchor="w", font=("Segoe UI", 9))
        self.status.pack(fill="x", padx=12, pady=(0, 8))

    # ── Filling the list ──────────────────────────────────────────────────

    def _group(self, title: str):
        """Get (or create) a top-level group row."""
        iid = self._groups.get(title)
        if iid and self.tree.exists(iid):
            return iid
        iid = self.tree.insert("", "end", text=title, values=("", ""),
                               open=True, tags=("group",))
        self._groups[title] = iid
        return iid

    def refresh_lists(self):
        """Rebuild everything except the scan results people just produced."""
        for iid in self.tree.get_children():
            self.tree.delete(iid)
        self._groups.clear()
        self._paths.clear()
        self._hosts.clear()
        self._loaded.clear()
        self._signin.clear()

        # 1. Drive letters Windows already has mapped to a share
        try:
            _avail, mapped = _net_get_drive_info_cached(0)   # always fresh here
        except Exception:
            mapped = []
        if mapped:
            g = self._group(self.GRP_MAPPED)
            for letter, unc in mapped:
                iid = self.tree.insert(g, "end", text=f"🔗  {letter}\\   →   {unc}",
                                       values=("Mapped drive", "connected"),
                                       tags=("ok",))
                self._paths[iid] = f"{letter}\\"

        # 2. Favourites saved in the Network window
        favs = [f for f in _net_load_favorites() if f.get("path")]
        if favs:
            g = self._group(self.GRP_FAV)
            for fav in favs:
                lbl = fav["path"]
                ltr = fav.get("letter", "")
                iid = self.tree.insert(g, "end",
                                       text=f"📌  {lbl}" + (f"   ({ltr})" if ltr else ""),
                                       values=("Favourite", ""))
                self._paths[iid] = fav["path"]

        # 3. What you opened last
        recent = self.manager.settings.get("net_recent", [])
        if recent:
            g = self._group(self.GRP_RECENT)
            for p in recent:
                iid = self.tree.insert(g, "end", text=f"🕘  {p}",
                                       values=("Recent", ""))
                self._paths[iid] = p

        if not (mapped or favs or recent):
            g = self._group("Nothing saved yet")
            self.tree.insert(g, "end",
                             text="Use “Quick scan (ARP)” below to find the "
                                  "computers on your network.",
                             values=("", ""), tags=("muted",))
        self._set_status("Ready.")

    # ── Scanning ──────────────────────────────────────────────────────────

    def _set_status(self, text: str):
        try:
            self.status.config(text=text)
        except Exception:
            pass

    def _quick_scan(self):
        """Instant: read the ARP cache — every machine this PC talked to."""
        if self._busy:
            return
        self._busy = True
        self._set_status("Reading the ARP cache…")

        def work():
            hosts = []
            try:
                for ip in _net_get_arp():
                    if ip.endswith(".255") or ip.startswith("224."):
                        continue
                    hosts.append(ip)
            except Exception as exc:
                _log(f"ARP scan failed: {exc}")
            _ui_call(self, lambda: self._show_hosts(hosts, "ARP cache"))

        threading.Thread(target=work, daemon=True).start()

    def _ping_sweep(self):
        """Slower but complete: ping every address on the local subnet."""
        if self._busy:
            return
        ifaces = _net_get_local_interfaces()
        if not ifaces:
            messagebox.showinfo("Network",
                                "No local network interface was found.",
                                parent=self)
            return
        cidr = ifaces[0]["cidr"]
        self._busy = True
        self._stop.clear()
        self._set_status(f"Pinging {cidr} …")

        def work():
            found = []
            try:
                net = ipaddress.IPv4Network(cidr, strict=False)
                addrs = [str(a) for a in net.hosts()][:512]
                lock = threading.Lock()

                def probe(ip):
                    if self._stop.is_set():
                        return
                    if _net_ping(ip, 0.6):
                        with lock:
                            found.append(ip)

                threads = []
                for ip in addrs:
                    t = threading.Thread(target=probe, args=(ip,), daemon=True)
                    threads.append(t)
                    t.start()
                    while sum(1 for x in threads if x.is_alive()) > 64:
                        _time.sleep(0.02)
                for t in threads:
                    t.join(timeout=3)
            except Exception as exc:
                _log(f"Ping sweep failed: {exc}")
            _ui_call(self, lambda: self._show_hosts(sorted(found), cidr))

        threading.Thread(target=work, daemon=True).start()

    def _show_hosts(self, ips: list, source: str):
        self._busy = False
        g = self._group(self.GRP_FOUND)
        for child in self.tree.get_children(g):
            self.tree.delete(child)
        if not ips:
            self.tree.insert(g, "end", text="(nothing answered)",
                             values=("", ""), tags=("muted",))
            self._set_status(f"{source}: no machines answered.")
            return
        for ip in ips:
            iid = self.tree.insert(
                g, "end", text=f"🖥  {ip}", values=("Computer", "expand to list shares"),
                open=False)
            self._hosts[iid] = ip
            # A dummy child makes the row expandable; it is replaced on open.
            self.tree.insert(iid, "end", text="…", values=("", ""), tags=("muted",))
        self.tree.item(g, open=True)
        self._set_status(f"{source}: {len(ips)} machine(s).  "
                         "Expand one to see its shares.")
        # Names make the list usable — resolve them in the background.
        threading.Thread(target=self._resolve_names, args=(list(self._hosts.items()),),
                         daemon=True).start()

    def _resolve_names(self, pairs):
        for iid, ip in pairs:
            if self._stop.is_set():
                return
            name = _net_resolve(ip, 1.0) or _net_netbios(ip)
            if name:
                _ui_call(self, lambda i=iid, n=name, a=ip:
                         self._rename_host(i, n, a))

    def _rename_host(self, iid, name, ip):
        try:
            if self.tree.exists(iid):
                short = name.split(".")[0]
                self.tree.item(iid, text=f"🖥  {short}   ({ip})")
                self._hosts[iid] = short
        except Exception:
            pass

    def _on_expand(self, _event=None):
        """Listing a host's shares costs a `net view` call, so it happens the
        first time you actually open that row — not for all of them up front."""
        iid = self.tree.focus()
        if iid not in self._hosts or iid in self._loaded:
            return
        self._loaded.add(iid)
        host = self._hosts[iid]
        for child in self.tree.get_children(iid):
            self.tree.delete(child)
        self.tree.insert(iid, "end", text="listing shares…", values=("", ""),
                         tags=("muted",))

        def work():
            # The hard drives (C$, D$ ...) first - this also puts a saved
            # sign-in back into Windows - then whatever `net view` adds.
            try:
                drives = _net_discover_drives(host)
            except Exception as exc:
                _log(f"Drive discovery on {host} failed: {exc}")
                drives = []
            shares, err, needs_login = [], "", False
            try:
                shares = list_smb_shares(host, timeout=15)
            except NetNeedsSignIn as exc:
                needs_login, err = True, str(exc)
            except Exception as exc:
                err = str(exc)
            if any(d.get("status") == "denied" for d in drives):
                needs_login = True
            _ui_call(self, lambda: self._fill_shares(iid, host, shares, err,
                                                     drives, needs_login))

        threading.Thread(target=work, daemon=True).start()

    def _fill_shares(self, iid, host, shares, err, drives=None,
                     needs_login=False):
        if not self.tree.exists(iid):
            return
        drives = drives or []
        for child in self.tree.get_children(iid):
            self.tree.delete(child)
        shown = set()

        # A computer that answers but wants a sign-in: say so, and offer it.
        if needs_login:
            row = self.tree.insert(
                iid, "end",
                text=f"🔑  Sign in to {host} …  (saved, so it is found again)",
                values=("Sign-in", "needed"), tags=("bad",))
            self._signin[row] = host

        for d in drives:
            shown.add(d["unc"].lower())
            if d.get("status") == "open":
                child = self.tree.insert(iid, "end", text=f"🖴  {d['unc']}",
                                         values=("Hard drive", "opens"),
                                         tags=("ok",))
                self._paths[child] = d["unc"]
            else:
                child = self.tree.insert(iid, "end", text=f"🖴  {d['unc']}",
                                         values=("Hard drive", "needs sign-in"),
                                         tags=("muted",))
                self._signin[child] = host

        if err and not needs_login and not drives:
            self.tree.insert(iid, "end", text=f"✘  {err}", values=("", ""),
                             tags=("bad",))
            return
        usable = [s for s in shares
                  if "print" not in (s.get("type", "") or "").lower()
                  and not s["name"].upper().startswith("IPC")
                  and f"\\\\{host}\\{s['name']}".lower() not in shown]
        if not usable and not drives and not needs_login:
            self.tree.insert(iid, "end", text="(no disk shares offered)",
                             values=("", ""), tags=("muted",))
            return
        for s in usable:
            unc = f"\\\\{host}\\{s['name']}"
            child = self.tree.insert(
                iid, "end", text=f"📁  {unc}",
                values=("Share", s.get("comment", "")))
            self._paths[child] = unc

    def _ask_sign_in(self, iid, host):
        """Sign-in box for a computer that is there but shows no drives."""
        def done():
            self._loaded.discard(iid)
            try:
                self.tree.focus(iid)
            except Exception:
                pass
            self._on_expand()
        NetSignInDialog(self, host, on_done=done)

    # ── Acting on a row ───────────────────────────────────────────────────

    def _selected_path(self) -> str:
        sel = self.tree.selection()
        if not sel:
            return ""
        return self._paths.get(sel[0], "")

    def _on_activate(self, _event=None):
        sel = self.tree.selection()
        if not sel:
            return
        iid = sel[0]
        if iid in self._signin:
            self._ask_sign_in(self.tree.parent(iid), self._signin[iid])
            return
        if iid in self._hosts and iid not in self._loaded:
            self.tree.item(iid, open=True)
            self._on_expand()
            return
        path = self._paths.get(iid, "")
        if path:
            self._open(path)

    def _open_typed(self):
        path = self.e_path.get().strip()
        if not path:
            messagebox.showinfo("Network",
                                "Type a path, or pick one from the list.",
                                parent=self)
            return
        self._open(path)

    def _open(self, path: str):
        if not os.path.isdir(path):
            if not _ask_yes_no(
                    "Network",
                    f"{path}\n\nThis path did not answer just now.  "
                    "Open it anyway?", parent=self):
                return
        self.manager._change_disk(self.side, path)
        self._close()

    def _map_typed(self):
        path = self.e_path.get().strip() or self._selected_path()
        if not path.startswith("\\\\"):
            messagebox.showinfo("Map drive",
                                "Pick a \\\\server\\share row first (a bare "
                                "computer name cannot be mapped — only a share "
                                "on it can).", parent=self)
            return
        try:
            free, _mapped = _net_get_drive_info_cached(0)
        except Exception:
            free = []
        letter = _ask_text(self, "Map drive letter",
                           f"Give {path} a drive letter:",
                           initial=(free[0] if free else "Z:"),
                           choices=free[:20])
        if not letter:
            return
        _net_connect_favorite({"letter": letter.strip().rstrip("\\"),
                               "path": path},
                              status_cb=lambda msg, ok: _ui_call(
                                  self, lambda: self._set_status(msg)))

    def _on_right_click(self, event):
        iid = self.tree.identify_row(event.y)
        if not iid:
            return
        self.tree.selection_set(iid)
        path = self._paths.get(iid, "")
        menu = tk.Menu(self, tearoff=0)
        if path:
            menu.add_command(label=f"Open in {self.side.upper()} panel",
                             command=lambda: self._open(path))
            menu.add_command(label="Open in the OTHER panel",
                             command=lambda: self._open_other(path))
            menu.add_separator()
            menu.add_command(label="Copy path to the text box",
                             command=lambda: (self.e_path.delete(0, "end"),
                                              self.e_path.insert(0, path)))
            if path.startswith("\\\\"):
                menu.add_command(label="💾  Save as network favourite",
                                 command=lambda: self._save_favourite(path))
        if iid in self._hosts:
            menu.add_command(label="🖧  Open the full Shares window for this host",
                             command=lambda: self.manager.open_shares(
                                 host=self._hosts[iid]))
        if menu.index("end") is None:
            return
        menu.tk_popup(event.x_root, event.y_root)

    def _open_other(self, path: str):
        other = "right" if self.side == "left" else "left"
        self.manager._change_disk(other, path)
        self._close()

    def _save_favourite(self, path: str):
        favs = _net_load_favorites()
        if any(f.get("path", "").lower() == path.lower() for f in favs):
            self._set_status("Already saved as a favourite.")
            return
        favs.append({"name": path, "path": path, "letter": "", "user": "", "_pw": ""})
        _net_save_favorites(favs)
        self.refresh_lists()
        _flash_ok(self, "Saved as favourite.", "Network")

    def _close(self):
        self._stop.set()
        try:
            self.destroy()
        except Exception:
            pass


# ══════════════════════════════════════════════════════════════════════════
#  DEL 47 — Portable devices  (phones, cameras, MP3 players — MTP)
# ══════════════════════════════════════════════════════════════════════════
#
# A phone plugged in with "File transfer / MTP" gets NO drive letter, so it can
# never show up in a drive list — that is why a connected phone looked missing.
# Windows exposes it only through the shell namespace ("This PC"), so that is
# what is read here, through Shell.Application (pywin32, else comtypes).
#
# Everything is addressed by a NAME CHAIN ("Galaxy S23" ▸ "Internal storage" ▸
# "DCIM") rather than by a COM object, because a COM pointer cannot be handed
# to another thread — re-walking the chain in the worker thread is both simple
# and safe.  Listings therefore always start from This PC and use ParseName()
# for each step, which is one fast lookup per level.

_MTP_LIB = None          # "pywin32" | "comtypes" | "" (none available)


def _mtp_shell():
    """A fresh Shell.Application for the CURRENT thread, or None.

    Worker threads must call CoInitialize first; this does it for them.  A new
    object per thread is deliberate — COM objects are not thread-safe.
    """
    global _MTP_LIB
    if platform.system() != "Windows":
        return None
    try:
        import pythoncom                       # noqa: F401  (pywin32)
        import win32com.client as _wc
        try:
            pythoncom.CoInitialize()
        except Exception:
            pass
        _MTP_LIB = "pywin32"
        return _wc.Dispatch("Shell.Application")
    except Exception:
        pass
    try:
        import comtypes
        import comtypes.client as _cc
        try:
            comtypes.CoInitialize()
        except Exception:
            pass
        _MTP_LIB = "comtypes"
        return _cc.CreateObject("Shell.Application")
    except Exception as exc:
        _MTP_LIB = ""
        _log(f"No COM library for portable devices: {exc}")
        return None


_SHELL_THIS_PC = 17      # ssfDRIVES — the "This PC" folder


def _mtp_is_drive_letter(path: str) -> bool:
    """True for 'C:\\' and friends — those already appear in the drive list."""
    p = (path or "").strip()
    return len(p) >= 2 and p[1] == ":" and p[0].isalpha()


def mtp_list_devices() -> list:
    """Everything under "This PC" that is NOT a plain drive letter.

    Returns [{'name', 'path'}].  On a machine with no phone attached this is
    simply an empty list; it never raises.
    """
    out = []
    sh = _mtp_shell()
    if sh is None:
        return out
    try:
        ns = sh.NameSpace(_SHELL_THIS_PC)
        if ns is None:
            return out
        for item in ns.Items():
            try:
                name = str(item.Name)
                try:
                    path = str(item.Path)
                except Exception:
                    path = ""
                if _mtp_is_drive_letter(path):
                    continue
                if not bool(item.IsFolder):
                    continue
                out.append({"name": name, "path": path})
            except Exception:
                continue
    except Exception as exc:
        _log(f"mtp_list_devices: {exc}")
    return out


# Same reasoning as the network-drive cache: enumerating the shell namespace
# is usually quick, but a sleeping phone can take a moment, and the drive menu
# must never feel sluggish.
_MTP_CACHE = {"when": 0.0, "value": []}


def mtp_list_devices_cached(max_age: float = 5.0) -> list:
    now = _time.monotonic()
    if now - _MTP_CACHE["when"] > max_age:
        try:
            _MTP_CACHE["value"] = mtp_list_devices()
        except Exception:
            _MTP_CACHE["value"] = []
        _MTP_CACHE["when"] = now
    return _MTP_CACHE["value"]


def _mtp_warm_caches():
    """Fill both menu caches in the background so the FIRST Alt+F1 is instant
    too.  Runs once at start-up; every call inside is exception-safe."""
    def work():
        try:
            _net_get_drive_info_cached(0)
        except Exception:
            pass
        try:
            mtp_list_devices_cached(0)
        except Exception:
            pass
    threading.Thread(target=work, daemon=True).start()


def _mtp_folder_for(sh, chain: list):
    """Walk This PC ▸ chain[0] ▸ chain[1] … and return the Folder, or None."""
    ns = sh.NameSpace(_SHELL_THIS_PC)
    if ns is None:
        return None
    for step in chain:
        item = None
        try:
            item = ns.ParseName(step)
        except Exception:
            item = None
        if item is None:
            # ParseName can fail on some MTP names (odd characters); fall back
            # to a plain scan of the children.
            try:
                for cand in ns.Items():
                    if str(cand.Name) == step:
                        item = cand
                        break
            except Exception:
                return None
        if item is None:
            return None
        try:
            ns = item.GetFolder
        except Exception:
            return None
        if ns is None:
            return None
    return ns


def mtp_list_folder(chain: list) -> list:
    """Contents of a device folder: [{'name','is_dir','size','modified'}].

    Runs on whatever thread calls it, so callers doing this in the background
    must not touch Tk from here.
    """
    rows = []
    sh = _mtp_shell()
    if sh is None:
        return rows
    folder = _mtp_folder_for(sh, chain)
    if folder is None:
        return rows
    try:
        for item in folder.Items():
            try:
                is_dir = bool(item.IsFolder)
                try:
                    size = int(item.Size)
                except Exception:
                    size = 0
                try:
                    modified = str(item.ModifyDate)
                except Exception:
                    modified = ""
                rows.append({"name": str(item.Name), "is_dir": is_dir,
                             "size": size, "modified": modified})
            except Exception:
                continue
    except Exception as exc:
        _log(f"mtp_list_folder {chain}: {exc}")
    return rows


def _mtp_item_by_name(folder, name):
    """FolderItem for *name* inside *folder*, or None.

    ParseName fails on some MTP names (odd Unicode, trailing spaces, names
    the phone reports slightly differently than Explorer displays them) —
    exactly the problem _mtp_folder_for already had to work around while
    walking INTO folders, with a fallback scan of Items().  Copying files
    OUT of a folder hit the very same problem, silently ("Copy to panel"
    reporting an error for files whose name ParseName choked on), because
    this fallback was missing here.  Every device transfer now goes through
    this one place instead of calling ParseName directly.
    """
    item = None
    try:
        item = folder.ParseName(name)
    except Exception:
        item = None
    if item is None:
        try:
            for cand in folder.Items():
                if str(cand.Name) == name:
                    item = cand
                    break
        except Exception:
            return None
    return item


def _mtp_index_folder(folder, names: list) -> dict:
    """{name: FolderItem} for *names*, walking the device folder AT MOST ONCE.

    REPORTED (2026-09-18 — "51 bilder tar 15 sekunder med Total Commander.
    Jag gick ut och plockade fallfrukt … 13 av 51 hade kopierats"):  roughly
    90 seconds PER PHOTO, for photos a cable can carry in a fraction of a
    second.  This is where most of it went.
    _mtp_item_by_name() falls back to scanning folder.Items() whenever
    ParseName chokes on a name — and on a phone it chokes often, which is
    exactly why that fallback was added.  But the transfer loops called it
    once PER FILE, so a 51-file job walked the whole DCIM folder 51 times,
    and every `cand.Name` in that walk is its own COM round trip to the
    device over MTP.  On a folder holding a couple of thousand photos one
    walk is already a minute; fifty-one of them is the afternoon he lost.
    It is O(files x folder) where it only ever needed to be O(folder).

    So: ask ParseName for everything first (one cheap round trip each, and
    when it works there is no walk at all), and walk ONCE for whatever is
    left — stopping the moment the last wanted name is found.
    """
    want  = set(names)
    found = {}
    for n in list(want):
        try:
            it = folder.ParseName(n)
        except Exception:
            it = None
        if it is not None:
            found[n] = it
            want.discard(n)
    if want:
        try:
            for cand in folder.Items():
                nm = str(cand.Name)
                if nm in want:
                    found[nm] = cand
                    want.discard(nm)
                    if not want:
                        break
        except Exception:
            pass
    return found


# ── Waiting for the shell's copy engine (revAO) ───────────────────────────
#
# Folder.CopyHere() / MoveHere() are ASYNCHRONOUS: they hand the job to the
# shell and return at once.  Every transfer here runs on a worker thread that
# called CoInitialize(), so the thread was dying the instant CopyHere returned
# — and a single-threaded apartment going away takes the copy it started with
# it.  That is the whole of "it looks like it starts and then nothing happens":
# nothing was ever copied, and the status line still said "Handed to Windows".
#
# So: after issuing the copy, stay on the thread, PUMP the apartment's message
# queue (an STA that does not pump deadlocks the shell's own callbacks) and
# watch the destination until the item turns up.  The deadline is pushed
# forward every time something actually happens, so a big file is given all
# the time it needs while a genuinely stuck transfer still gives up.

_MTP_STALL_SECS = 120.0     # no progress at all for this long = give up

# How the waiting is paced (2026-09-18).  The old loop polled every 0.25 s and
# called a file finished only after FOUR identical readings, so every single
# file — a 2 MB photo included — paid a full second of doing nothing before the
# next one was even started.  Fifty-one photos is a minute of pure waiting.
# The settle window is now measured in SECONDS rather than in polls, so it can
# be polled finely without shortening it: a file counts as finished when its
# size has not moved for _MTP_SETTLE_SECS.  That is the same caution as before
# — a big video that pauses mid-write is still not mistaken for a finished one
# — but because transfers are now issued as a batch, the window is paid once
# for the whole batch instead of once per file.
_MTP_POLL_SECS   = 0.10
_MTP_SETTLE_SECS = 1.0
# How many items are handed to the shell before waiting for them.  One at a
# time meant the device session was torn down and set up again between every
# photo; the whole batch at once would put a progress window on screen for each
# one.  A dozen keeps the pipe full without covering the screen.
_MTP_BATCH       = 12
# How long to wait for a pre-copy delete to take on the device before giving
# up on it (see _mtp_transfer_in).  Deliberately short: if the clash will not
# clear we fall through to the copy anyway, so the shell asks about that one
# file rather than the whole batch hanging.
_MTP_CLEAR_SECS  = 15.0


def _mtp_pump():
    """Let the worker thread's COM apartment service its message queue."""
    try:
        import pythoncom
        pythoncom.PumpWaitingMessages()
    except Exception:
        try:
            import comtypes
            comtypes.CoWaitForMultipleHandles     # noqa: B018  (probe only)
        except Exception:
            pass


def _mtp_wait_for(probe, stall: float = _MTP_STALL_SECS) -> bool:
    """Wait for a transfer, pumping COM.  *probe* returns a progress marker:

        None      — nothing there yet
        anything  — there; a CHANGING value (a growing size) means "still
                    working", so the stall clock is pushed forward

    True once the marker has stopped changing while being non-None (finished),
    False if nothing happened at all for *stall* seconds.
    """
    last, last_change, steady = None, _time.time(), 0
    while True:
        _mtp_pump()
        try:
            now = probe()
        except Exception:
            now = None
        if now != last:
            last, last_change, steady = now, _time.time(), 0
        elif now is not None:
            steady += 1
            # Same non-None value four polls (~1 s) running = it has landed.
            if steady >= 4:
                return True
        if _time.time() - last_change > stall:
            return last is not None
        _time.sleep(0.25)


def _mtp_wait_batch(probes: dict, stall: float = _MTP_STALL_SECS,
                    on_done=None) -> set:
    """Wait for a whole BATCH of transfers at once.  Returns the names that
    landed.

    Same rule as _mtp_wait_for — stay on the thread, pump the apartment, watch
    the markers — but for several items in flight together, which is the whole
    point of handing the shell more than one file at a time.  A name is done
    when its marker has held still for _MTP_SETTLE_SECS; the batch gives up
    only when NOTHING among the whole lot has moved for *stall* seconds, so one
    slow file does not start the clock on its neighbours.

    *on_done*, if given, is called as on_done(name, done_count) the moment an
    item lands — that is what finally makes the status line count upwards
    while a transfer runs instead of sitting on the same number.

    A file already at the destination with exactly the same size reads as
    "settled" straight away, so an overwrite by an identical file can be
    counted done before the shell has touched it.  That was true of the
    one-at-a-time wait as well; presence is all MTP gives us to go on.
    """
    pending     = dict(probes)
    landed      = set()
    last        = {}
    steady_at   = {}
    for n, p in pending.items():
        try:
            last[n] = p()
        except Exception:
            last[n] = None
        steady_at[n] = _time.time()
    last_change = _time.time()

    while pending:
        _mtp_pump()
        now_t = _time.time()
        for n in list(pending):
            try:
                val = pending[n]()
            except Exception:
                val = None
            if val != last[n]:
                last[n], steady_at[n] = val, now_t
                last_change = now_t
            elif val is not None and now_t - steady_at[n] >= _MTP_SETTLE_SECS:
                landed.add(n)
                pending.pop(n)
                last_change = now_t
                if on_done:
                    try:
                        on_done(n, len(landed))
                    except Exception:
                        pass
        if not pending:
            break
        if _time.time() - last_change > stall:
            break
        _time.sleep(_MTP_POLL_SECS)
    return landed


def _mtp_wait_gone(folder, name: str, stall: float = _MTP_STALL_SECS) -> bool:
    """Wait for an item to disappear from a device folder.

    InvokeVerb("delete") is asynchronous just like CopyHere, so the same rule
    applies: stay on the thread, pump the apartment, and check.

    Uses the throttled probe rather than _mtp_item_by_name for the same reason
    it does (2026-09-18): _mtp_item_by_name walks the whole device folder
    whenever ParseName draws a blank, which here is precisely the answer we are
    hoping for — so confirming a delete used to cost a full folder walk, and a
    poll loop of them if the phone was slow to let go.
    """
    probe    = _mtp_device_probe(folder, name)
    deadline = _time.time() + stall
    while _time.time() < deadline:
        _mtp_pump()
        try:
            if probe() is None:
                return True
        except Exception:
            return True
        _time.sleep(_MTP_POLL_SECS)
    return False


def _mtp_verdict(done: int, total: int, missing: list, stalled: list,
                 verb: str) -> str:
    """Turn a transfer's tally into "" (all good) or one plain-English error.

    A transfer used to report success unconditionally, so a batch where the
    shell quietly refused every single file still said "Handed to Windows —
    watch its copy dialog" and left you waiting for a dialog that was never
    coming.  Now the count is checked and what went wrong is named.
    """
    if done == total and not missing and not stalled:
        return ""
    bits = []
    if done:
        bits.append(f"{done} of {total} {verb}")
    else:
        bits.append(f"Nothing was {verb}")
    if missing:
        bits.append("not found: " + ", ".join(missing[:5])
                    + (f" (+{len(missing) - 5} more)" if len(missing) > 5 else ""))
    if stalled:
        bits.append("no sign of arrival within "
                    f"{int(_MTP_STALL_SECS)}s: " + ", ".join(stalled[:5])
                    + (f" (+{len(stalled) - 5} more)" if len(stalled) > 5 else ""))
    tail = ("\n\nA device that is asleep, locked, or plugged in as “Charging "
            "only” accepts nothing.  Unlock the phone, make sure it is in "
            "“File transfer / MTP” mode, and try again — “Open in Explorer” "
            "is a good cross-check: if Explorer cannot copy there either, it "
            "is the device or the cable, not this program.")
    return "  ·  ".join(bits) + tail


def _mtp_local_probe(path: str):
    """Progress marker for a file/folder being written to a LOCAL disk."""
    def probe():
        if not os.path.exists(path):
            return None
        try:
            if os.path.isdir(path):
                total = 0
                for root, _dirs, files in os.walk(path):
                    for f in files:
                        try:
                            total += os.path.getsize(os.path.join(root, f))
                        except OSError:
                            pass
                return ("dir", total)
            return ("file", os.path.getsize(path))
        except OSError:
            return None
    return probe


def _mtp_device_probe(folder, name: str, walk_every: float = 5.0):
    """Progress marker for an item being written onto the DEVICE.

    MTP exposes no partial object, so the name simply appears once Windows has
    finished writing it — presence is the whole signal.

    THE TRAP (2026-09-18).  This used to call _mtp_item_by_name, which falls
    back to walking the entire device folder whenever ParseName comes back
    empty — and while we are WAITING for a file, ParseName comes back empty
    every single time, by definition.  So the wait loop walked the whole phone
    folder on every poll, several times a second, purely to confirm that the
    file it was waiting for had still not arrived.  The waiting was costing
    more device traffic than the transfer.
    ParseName is one cheap round trip, so that is what the poll uses; the walk
    is kept for the names ParseName cannot see, but at most once every
    *walk_every* seconds instead of ten times a second.
    """
    state = {"next_walk": 0.0}

    def probe():
        try:
            if folder.ParseName(name) is not None:
                return "there"
        except Exception:
            pass
        now = _time.time()
        if now >= state["next_walk"]:
            state["next_walk"] = now + walk_every
            try:
                for cand in folder.Items():
                    if str(cand.Name) == name:
                        return "there"
            except Exception:
                return None
        return None
    return probe


def mtp_copy_out(chain: list, names: list, dest_dir: str,
                  progress=None, on_clash=None) -> str:
    """Copy items off the device into dest_dir.  Returns "" or an error text.

    Windows' own copy engine does the work (CopyHere), so you get its progress
    dialog and its resume/retry handling for a flaky USB cable — far more
    robust than trying to stream MTP by hand.  *progress*, if given, is called
    as progress(done, total, name) after each item, so a caller's status line
    can show "3/12" instead of a single unchanging "Copying…" for the whole
    batch — this runs on the calling (worker) thread, so the caller must hop
    back to the Tk thread itself before touching any widget.

    *on_clash*, if given, is asked once when some of the files are already in
    dest_dir — see _mtp_transfer_out.
    """
    return _mtp_transfer_out(chain, names, dest_dir, "copy", progress, on_clash)


def _mtp_transfer_out(chain: list, names: list, dest_dir: str,
                      how: str, progress=None, on_clash=None) -> str:
    """The engine behind mtp_copy_out / mtp_move_out.  *how* is "copy" or
    "move"; everything else about the two is identical, so they are one
    function and one place to fix.

    WHAT CHANGED (2026-09-18).  This used to be a strictly serial loop:
    look the file up on the device, hand it to the shell, then sit and wait
    for that one file to land before even looking up the next.  Three costs
    stacked on top of each other, and the batch paid all three per file:

      1. the folder walk — see _mtp_index_folder; by far the biggest,
      2. a device session set up and torn down between every photo,
      3. a full second of settle time each, doing nothing at all.

    Now the whole selection is looked up in one pass, handed to the shell a
    dozen at a time so the pipe stays full, and waited for together.  The
    shell's own copy engine still does the transfer — the resume/retry
    handling for a flaky cable is exactly as before, and nothing here streams
    MTP by hand.

    *progress* keeps its contract, progress(done, total, name), but is now
    called as each item actually LANDS rather than around the serial loop —
    so it counts 1, 2, 3 … through a running batch instead of freezing on the
    number it happened to reach when the current file started.

    NAME CLASHES IN THE DESTINATION FOLDER (2026-09-27).  Fetching FROM a
    device had the same hole that sending TO one had before 2026-09-23, only
    on the other side of the cable.  The 16 handed to CopyHere is
    FOF_NOCONFIRMATION — "overwrite, do not ask" — and with a portable device
    in the job the shell ignores it and pops its own *Replace or Skip* window
    anyway, ONE PER FILE.  Worse:

      * its "do this for all current items" tick covers only the ONE item that
        CopyHere call was given, so ticking it changed nothing: the next file
        in the queue asked again, exactly as reported;
      * the dialog blocks the CopyHere call that raised it, so the loop never
        reached the second file — no probe was ever armed, nothing landed, and
        the status line sat on "0/31" for the whole batch however many windows
        were answered.  That is the "superslött" as well: every file waited for
        a human, one at a time.

    So the clash is settled HERE, once, before the shell is handed anything:

      * on_clash(existing_names) is asked once and returns "overwrite", "skip"
        or "cancel".  With no asker the answer is "overwrite", which is what
        the 16 promised in the first place and which never hangs.
      * "overwrite" moves each clashing file ASIDE first (to a .fm-old name in
        the same folder), so the shell has nothing to ask about.  The old file
        is deleted once the new one has landed, and put back if it has not —
        an unplugged cable half way through must not cost the copy you already
        had.
      * "skip" leaves those files alone and fetches only the new ones.
      * "cancel" fetches nothing.
    """
    sh = _mtp_shell()
    if sh is None:
        return "No COM support available (pywin32 / comtypes missing)."
    folder = _mtp_folder_for(sh, chain)
    if folder is None:
        return "The device folder could not be opened (unplugged?)."
    dest = sh.NameSpace(os.path.abspath(dest_dir))
    if dest is None:
        return f"Destination folder not available: {dest_dir}"

    if progress:
        try:
            progress(0, len(names), "looking up files on the device…")
        except Exception:
            pass

    # ONE walk of the device folder for the whole job (was one per file).
    index   = _mtp_index_folder(folder, names)
    missing = [n for n in names if n not in index]
    todo    = [n for n in names if n in index]

    # ── settle the name clash once, before the shell sees anything ─────────
    clashers = [n for n in todo
                if os.path.exists(os.path.join(dest_dir, n))]
    backups: dict = {}                      # name -> where the old file waits
    if clashers:
        policy = "overwrite"
        if on_clash:
            try:
                policy = (on_clash(list(clashers)) or "overwrite").lower()
            except Exception:
                policy = "overwrite"
        if policy == "cancel":
            return "Cancelled — nothing was copied."
        if policy == "skip":
            skip_set = set(clashers)
            todo = [n for n in todo if n not in skip_set]
        else:                               # overwrite: move the old one aside
            for name in clashers:
                dstp = os.path.join(dest_dir, name)
                tmp  = dstp + ".fm-old"
                k = 0
                while os.path.exists(tmp):
                    k += 1
                    tmp = f"{dstp}.fm-old{k}"
                try:
                    os.replace(dstp, tmp)
                    backups[name] = tmp
                except Exception:
                    # Could not rename it (locked by another program?).  Delete
                    # it outright; if even that fails, leave it and let the
                    # shell ask about that ONE file rather than lose the batch.
                    _force_remove(dstp)

    total = len(todo)
    done, stalled = 0, []
    landed_all: set = set()
    verb = "copied" if how == "copy" else "moved"
    if progress:
        try:
            progress(0, total, "starting…")
        except Exception:
            pass

    def _settle_backups():
        """Drop every old file whose replacement arrived, put back every old
        file whose replacement did not.  Runs however this function leaves —
        an error return half way through a batch must not leave the user's
        own file parked under a .fm-old name."""
        for name, tmp in backups.items():
            try:
                if name in landed_all:
                    _force_remove(tmp)
                else:
                    os.replace(tmp, os.path.join(dest_dir, name))
            except Exception:
                pass
        backups.clear()

    try:
        for start in range(0, len(todo), _MTP_BATCH):
            batch  = todo[start:start + _MTP_BATCH]
            probes = {}
            for name in batch:
                try:
                    item = index[name]
                    # 16 is FOF_NOCONFIRMATION.  It is kept because it does the
                    # right thing on a plain folder, but it is NOT what stops
                    # the per-file "Replace or Skip" window any more — the
                    # shell ignores it with a device in the job.  The clash was
                    # already settled above; this flag is just belt and braces.
                    if how == "copy":
                        dest.CopyHere(item, 16)
                    else:
                        dest.MoveHere(item, 16)
                    # CopyHere/MoveHere are asynchronous — see _mtp_wait_batch.
                    # Returning before they finish would kill the apartment and
                    # take the transfer with it.
                    probes[name] = _mtp_local_probe(os.path.join(dest_dir, name))
                except Exception as exc:
                    return f"{name}: {exc}"

            base = done

            def _landed(_name, count, _base=base, _total=total):
                if progress:
                    try:
                        progress(_base + count, _total, _name)
                    except Exception:
                        pass

            got = _mtp_wait_batch(probes, on_done=_landed)
            done += len(got)
            landed_all |= got
            stalled.extend(n for n in batch if n not in got)
    finally:
        _settle_backups()

    return _mtp_verdict(done, total, missing, stalled, verb)


def mtp_copy_in(chain: list, local_paths: list, progress=None,
                on_clash=None) -> str:
    """Copy local files/folders ONTO the device.  Returns "" or an error.

    *progress*, if given, is called as progress(done, total, name) after
    each item — same contract as mtp_copy_out.  *on_clash*, if given, is
    asked once when some files already exist on the device — see
    _mtp_transfer_in.
    """
    return _mtp_transfer_in(chain, local_paths, "copy", progress, on_clash)


def _mtp_transfer_in(chain: list, local_paths: list, how: str,
                     progress=None, on_clash=None) -> str:
    """The engine behind mtp_copy_in / mtp_move_in.  *how* is "copy" or
    "move".

    Batched the same way as _mtp_transfer_out, and for the same reason: one
    file at a time meant the device session was rebuilt between every item.
    The asynchronous rule is unchanged — CopyHere/MoveHere hand the job to the
    shell and return at once, so the thread stays alive and pumps its
    apartment until the items show up on the device (that is the old fix for
    "it looks like it starts and then nothing happens", and it still applies).

    NAME CLASHES ON THE DEVICE (2026-09-23).  The 16 passed to CopyHere is
    FOF_NOCONFIRMATION — "overwrite, do not ask".  On a real folder it works;
    on a PHONE the shell's copy engine ignores it and pops its own
    "Replace or Skip" dialog anyway, ONCE PER FILE.  Copying 24 songs that
    are already there meant 24 dialogs, and the batch sat frozen behind them
    (a file cannot land until its dialog is answered) — which is exactly the
    "I waited and nothing happened" that was reported.

    So a clash is settled HERE, up front, in ONE decision instead of a dialog
    per file:

      * on_clash(existing_names) is asked once and returns "overwrite",
        "skip" or "cancel".  The window supplies it (a single Yes/No/Cancel);
        with no asker the default is "overwrite", which never hangs.
      * "overwrite" DELETES each clashing file on the device first, so the
        shell has nothing left to ask about and the copy runs clean.  If a
        delete will not take within _MTP_CLEAR_SECS we fall through and let
        the shell handle that one file — one dialog, not the whole batch.
      * "skip" does not copy the files that already exist.
      * "cancel" copies nothing.
    """
    sh = _mtp_shell()
    if sh is None:
        return "No COM support available (pywin32 / comtypes missing)."
    folder = _mtp_folder_for(sh, chain)
    if folder is None:
        return "The device folder could not be opened (unplugged?)."

    pairs, missing = [], []
    for p in local_paths:
        name = os.path.basename(os.path.abspath(p).rstrip("\\/"))
        if os.path.exists(p):
            pairs.append((name, os.path.abspath(p)))
        else:
            missing.append(name)

    # Which of the names we are about to write already sit on the device?
    # ONE walk of the device folder for the whole job (see _mtp_index_folder),
    # not one per file.
    existing = _mtp_index_folder(folder, [n for n, _ in pairs]) if pairs else {}
    clashers = [n for n, _ in pairs if n in existing]

    if clashers:
        policy = "overwrite"
        if on_clash:
            try:
                policy = (on_clash(list(clashers)) or "overwrite").lower()
            except Exception:
                policy = "overwrite"
        if policy == "cancel":
            return "Cancelled — nothing was copied."
        if policy == "skip":
            pairs = [(n, f) for n, f in pairs if n not in existing]
        else:                                   # overwrite: clear the way
            for name in clashers:
                item = existing.get(name)
                if item is None:
                    continue
                try:
                    item.InvokeVerb("delete")
                    # Asynchronous like every shell verb here; wait briefly,
                    # then give up gracefully rather than hang the batch.
                    _mtp_wait_gone(folder, name, stall=_MTP_CLEAR_SECS)
                except Exception:
                    pass

    total = len(pairs)
    done, stalled = 0, []
    verb = "copied" if how == "copy" else "moved"

    for start in range(0, len(pairs), _MTP_BATCH):
        batch  = pairs[start:start + _MTP_BATCH]
        probes = {}
        for name, full in batch:
            try:
                if how == "copy":
                    folder.CopyHere(full, 16)
                else:
                    folder.MoveHere(full, 16)
                probes[name] = _mtp_device_probe(folder, name)
            except Exception as exc:
                return f"{name}: {exc}"

        base = done

        def _landed(_name, count, _base=base, _total=total):
            if progress:
                try:
                    progress(_base + count, _total, _name)
                except Exception:
                    pass

        got = _mtp_wait_batch(probes, on_done=_landed)
        done += len(got)
        stalled.extend(n for n, _ in batch if n not in got)

    return _mtp_verdict(done, total, missing, stalled, verb)


def mtp_move_out(chain: list, names: list, dest_dir: str,
                  progress=None, on_clash=None) -> str:
    """Move items off the device into dest_dir.  Returns "" or an error text.

    Same engine as mtp_copy_out — Windows' Shell.Application, the same single
    clash question — but MoveHere instead of CopyHere, so the device loses the
    file once the transfer succeeds instead of keeping a copy.  Whether the
    phone frees the space immediately or only on its next sync is up to its
    own MTP driver; this is exactly what dragging with no key held in
    Explorer would do, not something new invented here.  *progress* and
    *on_clash* keep the same contract as mtp_copy_out.
    """
    return _mtp_transfer_out(chain, names, dest_dir, "move", progress, on_clash)


def mtp_move_in(chain: list, local_paths: list, progress=None,
                on_clash=None) -> str:
    """Move local files/folders ONTO the device — they are removed from this
    computer once the transfer succeeds.  Returns "" or an error.  *progress*,
    if given, is called as progress(done, total, name) after each item.
    *on_clash* is asked once on a name clash — see _mtp_transfer_in."""
    return _mtp_transfer_in(chain, local_paths, "move", progress, on_clash)


def mtp_delete(chain: list, names: list, progress=None) -> str:
    """Delete items on the device.  Returns "" or an error text.

    There was no way to delete anything on a device before — Copy/Move were
    the only two verbs the window offered.  Same reasoning as copy/move:
    item.InvokeVerb("delete") hands the actual removal to Windows' own shell
    delete verb, so its confirmation (and, on devices that support one, its
    recycle-bin behaviour) applies here too, instead of a silent, hand-rolled
    delete written from scratch.  *progress*, if given, is called as
    progress(done, total, name) after each item.
    """
    sh = _mtp_shell()
    if sh is None:
        return "No COM support available (pywin32 / comtypes missing)."
    folder = _mtp_folder_for(sh, chain)
    if folder is None:
        return "The device folder could not be opened (unplugged?)."
    deleted, missing, stalled = 0, [], []
    total = len(names)
    # ONE walk of the device folder for the whole job — see _mtp_index_folder.
    index   = _mtp_index_folder(folder, names)
    missing = [n for n in names if n not in index]
    for i, name in enumerate(names, 1):
        if name not in index:
            continue
        try:
            item = index[name]
            item.InvokeVerb("delete")
            # Asynchronous, like every other shell verb here — see
            # _mtp_wait_gone.  Returning now would tear the apartment down
            # mid-delete and report a success that never happened.
            if _mtp_wait_gone(folder, name):
                deleted += 1
            else:
                stalled.append(name)
        except Exception as exc:
            return f"{name}: {exc}"
        if progress:
            try:
                progress(i, total, name)
            except Exception:
                pass
    return _mtp_verdict(deleted, total, missing, stalled, "deleted")


_MTP_HELP = (
    "No phone or camera was found.\n\n"
    "Windows only shows a phone here when ALL of this is true:\n"
    "   1.  The phone is UNLOCKED  (a locked screen hides the storage).\n"
    "   2.  Its USB mode is set to “File transfer” / “MTP” — not “Charging "
    "only”, and not “USB tethering”.  Pull down the phone's notification "
    "shade after plugging it in and tap the USB notification to change it.\n"
    "   3.  The cable can carry data.  Many charging cables cannot; if the "
    "phone charges but never appears, try another cable first.\n"
    "   4.  You allowed this computer on the phone's “Allow access?” prompt.\n\n"
    "A phone in MTP mode never gets a drive letter, which is why it cannot "
    "appear in the ordinary drive list — it lives only here.\n"
    "If the phone is set to “USB drive / mass storage” instead, it DOES get a "
    "letter and shows up as a Removable drive in the drive menu."
)


class PortableDeviceWindow(tk.Toplevel):
    """Browse a phone / camera / media player and copy files to and from it."""

    def __init__(self, manager: "EditorFrame", side: str = None,
                 device: str = None):
        super().__init__(manager)
        self.manager = manager
        self.side    = side or manager.active_panel
        self.chain   = []            # ["Galaxy S23", "Internal storage", "DCIM"]
        self._busy   = False
        self._xfer   = False     # a transfer is running on a worker thread
        self._rows   = []

        self.configure(bg=C_BG)
        self.geometry("1000x620")
        _setup_toplevel(self, "Portable devices", manager, modal=False)

        self._build()
        self.after(50, lambda: self._load_devices(preselect=device))

    # ── Layout ────────────────────────────────────────────────────────────

    def _build(self):
        head = tk.Frame(self, bg=C_BG)
        head.pack(fill="x", padx=12, pady=(12, 4))
        tk.Label(head, text="📱  Phones, cameras and media players",
                 bg=C_BG, fg=C_ACCENT,
                 font=("Segoe UI", 13, "bold")).pack(anchor="w")
        tk.Label(head,
                 text="These have no drive letter, so they can only be reached "
                      "here.  Double-click a folder to open it.",
                 bg=C_BG, fg=C_FG_DIM, font=("Segoe UI", 9)).pack(anchor="w")

        nav = tk.Frame(self, bg=C_BG)
        nav.pack(fill="x", padx=12, pady=(6, 4))
        tk.Button(nav, text="⬆  Up", bg="lightgrey", fg="black", width=8,
                  command=self.go_up).pack(side="left")
        tk.Button(nav, text="🏠  Devices", bg="lightgrey", fg="black", width=10,
                  command=lambda: self._load_devices()).pack(side="left", padx=4)
        tk.Button(nav, text="🔄  Refresh", bg="lightgrey", fg="black", width=10,
                  command=self.reload).pack(side="left", padx=4)
        tk.Button(nav, text="☑  Mark all", bg="lightgrey", fg="black", width=10,
                  command=self.select_all).pack(side="left", padx=4)
        # Which panel this window trades files with.  It opens on whichever
        # panel was active, but the files often get marked in the OTHER one
        # afterwards — and "select the files in the RIGHT panel" while they are
        # plainly marked in the LEFT is no help at all.  So it is a visible,
        # switchable choice, and _source_panel() below follows the files when
        # only one side actually has any.  (revAO)
        self.var_side = tk.StringVar(value=self.side)
        _side_box = tk.Frame(nav, bg=C_BG)
        _side_box.pack(side="right")
        tk.Label(_side_box, text="Panel:", bg=C_BG, fg=C_FG_DIM,
                 font=("Segoe UI", 9)).pack(side="left", padx=(0, 4))
        for _val, _txt in (("left", "◀ Left"), ("right", "Right ▶")):
            tk.Radiobutton(_side_box, text=_txt, value=_val,
                           variable=self.var_side, bg=C_BG, fg=C_FG,
                           selectcolor=C_BG3, activebackground=C_BG,
                           activeforeground=C_ACCENT,
                           font=("Segoe UI", 9)).pack(side="left")

        self.lbl_path = tk.Label(nav, text="This PC", bg=C_BG, fg=C_FG,
                                 anchor="w", font=("Segoe UI", 9, "bold"))
        self.lbl_path.pack(side="left", fill="x", expand=True, padx=10)

        mid = tk.Frame(self, bg=C_BG)
        mid.pack(fill="both", expand=True, padx=12, pady=(2, 6))
        self.tree = ttk.Treeview(mid, columns=("size", "modified"),
                                 selectmode="extended")
        self.tree.heading("#0",       text="Name")
        self.tree.heading("size",     text="Size")
        self.tree.heading("modified", text="Modified")
        self.tree.column("#0",       width=470, anchor="w")
        self.tree.column("size",     width=120, anchor="e")
        self.tree.column("modified", width=170, anchor="w")
        sb = ttk.Scrollbar(mid, orient="vertical", command=self.tree.yview)
        self.tree.configure(yscrollcommand=sb.set)
        sb.pack(side="right", fill="y")
        self.tree.pack(side="left", fill="both", expand=True)
        self.tree.tag_configure("dir",   foreground=TC_INFO)
        self.tree.tag_configure("muted", foreground=TC_MUTED)
        self.tree.bind("<Double-1>", self._on_activate)
        self.tree.bind("<Return>",   self._on_activate)
        self.tree.bind("<Control-a>", self._on_select_all)
        self.tree.bind("<Control-A>", self._on_select_all)
        self.tree.bind("<Delete>",   lambda e: self.delete_selected())

        # The help text lives in the same window, hidden until it is needed —
        # "my phone is not here" deserves an answer on the spot.
        self.help_box = tk.Text(self, height=11, wrap="word", bg=C_BG3, fg=C_FG,
                                relief="flat", padx=10, pady=8,
                                insertofftime=0, insertontime=9999999)
        self.help_box.insert("1.0", _MTP_HELP)
        self.help_box.configure(state="disabled")

        bar = tk.Frame(self, bg=C_BG)
        bar.pack(fill="x", padx=12, pady=(0, 10))
        # Names read direction-first, from the DEVICE's point of view (this
        # window's point of view): "away" = off the device, "to here" = onto
        # the device — "to panel" / "from panel" on their own read the same
        # both ways round and only the noun after them told you which was
        # which, so "panel" is now just an arrow-marked qualifier instead of
        # carrying the whole meaning.
        tk.Button(bar, text="⬇  Copy away → Panel", bg="lightgreen", fg="black",
                  command=self.copy_to_panel).pack(side="left", padx=(0, 4))
        tk.Button(bar, text="✂⬇  Move away → Panel", bg="#ffcf7a", fg="black",
                  command=self.move_to_panel).pack(side="left", padx=4)
        tk.Button(bar, text="⬆  Copy to here ← Panel", bg="lightblue", fg="black",
                  command=self.copy_from_panel).pack(side="left", padx=4)
        tk.Button(bar, text="✂⬆  Move to here ← Panel", bg="#ffcf7a", fg="black",
                  command=self.move_from_panel).pack(side="left", padx=4)
        tk.Button(bar, text="🗑  Delete", bg="#ff8080", fg="black",
                  command=self.delete_selected).pack(side="left", padx=4)
        tk.Button(bar, text="🗂  Open in Explorer", bg="lightgrey", fg="black",
                  command=self.open_in_explorer).pack(side="left", padx=4)
        tk.Button(bar, text="❔  Why is my phone missing?", bg="lightgrey",
                  fg="black", command=self.toggle_help).pack(side="left", padx=4)
        tk.Button(bar, text="Close", bg="grey", fg="white", width=9,
                  command=self.destroy).pack(side="right")

        self.status = tk.Label(self, text="", bg=C_BG, fg=C_FG_DIM, anchor="w",
                               font=("Segoe UI", 9))
        self.status.pack(fill="x", padx=12, pady=(0, 8))

    # ── Helpers ───────────────────────────────────────────────────────────

    def _set_status(self, text: str):
        try:
            self.status.config(text=text)
        except Exception:
            pass

    # ── Which panel are we trading with? ──────────────────────────────────

    def _panel_for(self, side: str = None):
        """The panel object for *side* (default: the Panel radio)."""
        side = side or self.var_side.get()
        panel = (self.manager.left_panel if side == "left"
                 else self.manager.right_panel)
        return panel, side

    def _source_panel(self):
        """(panel, side, paths) for a "… to here ← Panel" transfer.

        The chosen side wins whenever it has something marked or selected.  If
        it has nothing and the OTHER side does, that one is used instead and
        the radio moves to match — so the window always shows the panel it
        actually took the files from, instead of telling you to go and mark
        files in a panel where they are already marked.  (revAO)
        """
        panel, side = self._panel_for()
        paths = panel.get_all_selected() if hasattr(panel, "get_all_selected") else []
        if paths:
            return panel, side, paths
        other = "right" if side == "left" else "left"
        opanel, _ = self._panel_for(other)
        opaths = (opanel.get_all_selected()
                  if hasattr(opanel, "get_all_selected") else [])
        if opaths:
            self.var_side.set(other)
            return opanel, other, opaths
        return panel, side, []

    def _help_shown(self) -> bool:
        """Is the help panel packed?  winfo_manager() answers even while the
        window itself is not yet viewable — winfo_ismapped() would say "no"
        and the panel would get packed twice."""
        try:
            return bool(self.help_box.winfo_manager())
        except Exception:
            return False

    def toggle_help(self):
        if self._help_shown():
            self.help_box.pack_forget()
        else:
            self.help_box.pack(fill="x", padx=12, pady=(0, 6))

    def _show(self, rows, at_root: bool):
        self.tree.delete(*self.tree.get_children())
        self._rows = rows
        for r in rows:
            if r["is_dir"]:
                size = ""
                icon = "📱" if at_root else "📁"
            else:
                size = f"{_group_digits(max(1, r['size'] // 1024))} KB" if r["size"] else "0 KB"
                icon = "📄"
            self.tree.insert("", "end", text=f"{icon}  {r['name']}",
                             values=(size, r.get("modified", "")),
                             tags=("dir",) if r["is_dir"] else ())
        self.lbl_path.config(text="This PC" if not self.chain
                             else "  ▸  ".join(self.chain))
        if not rows:
            self.tree.insert("", "end",
                             text=("(no device found — press “Why is my phone "
                                   "missing?”)" if at_root else "(empty)"),
                             values=("", ""), tags=("muted",))
            if at_root and not self._help_shown():
                self.toggle_help()

    def _selected_names(self) -> list:
        names = []
        for iid in self.tree.selection():
            idx = self.tree.index(iid)
            if 0 <= idx < len(self._rows):
                names.append(self._rows[idx]["name"])
        return names

    def select_all(self):
        """Select every row in the current listing — there was no way to do
        this other than dragging or shift-clicking through the whole list."""
        self.tree.selection_set(self.tree.get_children())

    def _on_select_all(self, event=None):
        self.select_all()
        return "break"    # stop Tk's own Ctrl+A handling on the Treeview

    # ── Navigation ────────────────────────────────────────────────────────

    def _load_devices(self, preselect: str = None):
        self.chain = []
        self._set_status("Looking for devices…")

        def work():
            devs = mtp_list_devices()
            rows = [{"name": d["name"], "is_dir": True, "size": 0,
                     "modified": ""} for d in devs]
            _ui_call(self, lambda: self._devices_ready(rows, preselect))

        threading.Thread(target=work, daemon=True).start()

    def _devices_ready(self, rows, preselect):
        self._show(rows, at_root=True)
        self._set_status(f"{len(rows)} device(s)." if rows
                         else "No portable device is connected.")
        if preselect and any(r["name"] == preselect for r in rows):
            self.chain = [preselect]
            self.reload()

    def reload(self):
        if not self.chain:
            self._load_devices()
            return
        if self._busy:
            return
        self._busy = True
        chain = list(self.chain)
        self._set_status("Reading " + "  ▸  ".join(chain) + " …")

        def work():
            rows = mtp_list_folder(chain)
            rows.sort(key=lambda r: (not r["is_dir"], r["name"].lower()))
            _ui_call(self, lambda: self._folder_ready(rows))

        threading.Thread(target=work, daemon=True).start()

    def _folder_ready(self, rows):
        self._busy = False
        self._show(rows, at_root=False)
        n_dirs = sum(1 for r in rows if r["is_dir"])
        self._set_status(f"{n_dirs} folder(s), {len(rows) - n_dirs} file(s).")

    def go_up(self):
        if self.chain:
            self.chain.pop()
        if self.chain:
            self.reload()
        else:
            self._load_devices()

    def _on_activate(self, _event=None):
        sel = self.tree.selection()
        if not sel:
            return
        idx = self.tree.index(sel[0])
        if not (0 <= idx < len(self._rows)):
            return
        row = self._rows[idx]
        if row["is_dir"]:
            self.chain.append(row["name"])
            self.reload()
        else:
            self._set_status("Files on a device must be COPIED before they can "
                             "be opened — use “Copy to panel”.")

    # ── Transfers ─────────────────────────────────────────────────────────

    def _progress_cb(self, verb: str):
        """Build a progress(done, total, name) callback for a transfer's
        status line — MTP transfers used to just say "Copying…" once and
        then sit there until the whole batch finished, with nothing to show
        how far it had actually gotten.  Runs on the worker thread, so it
        must hop back to the Tk thread through _ui_call rather than touching
        the status label directly.
        """
        def cb(done, total, name):
            _ui_call(self, lambda: self._set_status(
                f"{verb} {done}/{total} — {name}"))
        return cb

    def _mtp_clash_asker(self, place: str = "on the device"):
        """A callback the transfer worker can use to settle a name clash.

        The worker (off the Tk thread) has found files that are already where
        it is about to write them.  Rather than let Windows pop its own
        "Replace or Skip" dialog once per file — which it does whenever a
        portable device is in the job, whatever flag we pass, whose own "do
        this for all" tick covers only that one file, and which freezes the
        batch behind it — we ask ONCE here and hand the answer back.
        Yes = overwrite, No = skip the existing ones, Cancel = transfer
        nothing.

        *place* names where the clash is, so the same question reads correctly
        in both directions: "on the device" when sending, or the destination
        folder when fetching.
        """
        def ask(existing):
            box = {"v": "overwrite"}
            done = threading.Event()

            def _ask():
                try:
                    n = len(existing)
                    shown = ", ".join(existing[:6]) + (" …" if n > 6 else "")
                    yn = _ask_yes_no_cancel(
                        f"Some files already exist {place}",
                        f"{n} of the file(s) you are transferring are already "
                        f"{place}:\n\n{shown}\n\n"
                        "Yes — overwrite them\n"
                        "No — skip them (transfer only the new ones)\n"
                        "Cancel — transfer nothing",
                        parent=self)
                    box["v"] = ("overwrite" if yn is True
                                else "skip" if yn is False else "cancel")
                finally:
                    done.set()

            _ui_call(self, _ask)
            done.wait()
            return box["v"]
        return ask

    def _xfer_busy(self) -> bool:
        """One transfer at a time.  They are real, blocking work now that the
        program waits for the shell's copy engine instead of firing and
        forgetting, so a second click while one is running would put two
        transfers on the same device at once."""
        if self._xfer:
            messagebox.showinfo(
                "Busy", "A transfer is already running — wait for the status "
                "line at the bottom to finish.", parent=self)
            return True
        return False

    def copy_to_panel(self):
        if self._xfer_busy():
            return
        names = self._selected_names()
        if not names:
            messagebox.showinfo("Copy", "Select what to copy first.", parent=self)
            return
        if not self.chain:
            messagebox.showinfo("Copy", "Open a device first.", parent=self)
            return
        panel, side = self._panel_for()
        if getattr(panel, "is_remote", False):
            messagebox.showinfo(
                "Copy", f"The {side.upper()} panel is FTP-mounted.\n\n"
                "Pick the other one with the Panel switch at the top right.",
                parent=self)
            return
        dest = panel.current_path
        if not _ask_yes_no(
                "Copy from device",
                f"Copy {len(names)} item(s) to the {side.upper()} panel:\n{dest}",
                parent=self):
            return
        chain = list(self.chain)
        self._xfer = True
        self._set_status("Copying…")

        asker = self._mtp_clash_asker(f"in  {dest}")

        def work():
            err = mtp_copy_out(chain, names, dest,
                               progress=self._progress_cb("Copying"),
                               on_clash=asker)
            _ui_call(self, lambda: self._after_copy(err, panel))

        threading.Thread(target=work, daemon=True).start()

    def copy_from_panel(self):
        if self._xfer_busy():
            return
        if not self.chain:
            messagebox.showinfo("Copy", "Open a folder on the device first.",
                                parent=self)
            return
        panel, side, paths = self._source_panel()
        if not paths:
            messagebox.showinfo(
                "Copy",
                "Neither panel has anything marked or selected.\n\n"
                "Mark the files in the file manager first — either panel will "
                "do; the Panel switch at the top right of this window says "
                "which one is used.", parent=self)
            return
        if getattr(panel, "is_remote", False):
            messagebox.showinfo(
                "Copy", f"The {side.upper()} panel is FTP-mounted — download "
                "the files first, then send them to the device.", parent=self)
            return
        if not _ask_yes_no(
                "Copy to device",
                f"Copy {len(paths)} item(s) from the {side.upper()} panel to:\n"
                + "  ▸  ".join(self.chain),
                parent=self):
            return
        chain = list(self.chain)
        self._xfer = True
        self._set_status("Copying…")

        asker = self._mtp_clash_asker()

        def work():
            err = mtp_copy_in(chain, paths,
                              progress=self._progress_cb("Copying"),
                              on_clash=asker)
            _ui_call(self, lambda: self._after_copy(err, None))

        threading.Thread(target=work, daemon=True).start()

    def move_to_panel(self):
        """Same as copy_to_panel, but the device LOSES the files once the
        transfer succeeds — there was no way to do this before; only Copy
        existed, so getting files off a phone always left them behind too."""
        if self._xfer_busy():
            return
        names = self._selected_names()
        if not names:
            messagebox.showinfo("Move", "Select what to move first.", parent=self)
            return
        if not self.chain:
            messagebox.showinfo("Move", "Open a device first.", parent=self)
            return
        panel, side = self._panel_for()
        if getattr(panel, "is_remote", False):
            messagebox.showinfo(
                "Move", f"The {side.upper()} panel is FTP-mounted.\n\n"
                "Pick the other one with the Panel switch at the top right.",
                parent=self)
            return
        dest = panel.current_path
        if not _ask_yes_no(
                "Move from device",
                f"Move {len(names)} item(s) to the {side.upper()} panel:\n{dest}\n\n"
                "The originals are REMOVED from the device once the transfer "
                "succeeds.",
                parent=self):
            return
        chain = list(self.chain)
        self._xfer = True
        self._set_status("Moving…")

        asker = self._mtp_clash_asker(f"in  {dest}")

        def work():
            err = mtp_move_out(chain, names, dest,
                               progress=self._progress_cb("Moving"),
                               on_clash=asker)
            _ui_call(self, lambda: self._after_copy(err, panel, verb="move"))

        threading.Thread(target=work, daemon=True).start()

    def move_from_panel(self):
        """Same as copy_from_panel, but the LOCAL files are removed once the
        transfer to the device succeeds."""
        if self._xfer_busy():
            return
        if not self.chain:
            messagebox.showinfo("Move", "Open a folder on the device first.",
                                parent=self)
            return
        panel, side, paths = self._source_panel()
        if not paths:
            messagebox.showinfo(
                "Move",
                "Neither panel has anything marked or selected.\n\n"
                "Mark the files in the file manager first — either panel will "
                "do; the Panel switch at the top right of this window says "
                "which one is used.", parent=self)
            return
        if getattr(panel, "is_remote", False):
            messagebox.showinfo(
                "Move", f"The {side.upper()} panel is FTP-mounted — download "
                "the files first, then send them to the device.", parent=self)
            return
        if not _ask_yes_no(
                "Move to device",
                f"Move {len(paths)} item(s) from the {side.upper()} panel to:\n"
                + "  ▸  ".join(self.chain) +
                "\n\nThe originals are REMOVED from this computer once the "
                "transfer succeeds.", parent=self):
            return
        chain = list(self.chain)
        self._xfer = True
        self._set_status("Moving…")

        asker = self._mtp_clash_asker()

        def work():
            err = mtp_move_in(chain, paths,
                              progress=self._progress_cb("Moving"),
                              on_clash=asker)
            # The panel just lost files on THIS computer, unlike a plain
            # copy — it needs a refresh, so pass it instead of None.
            _ui_call(self, lambda: self._after_copy(err, panel, verb="move"))

        threading.Thread(target=work, daemon=True).start()

    def delete_selected(self):
        """Delete the selected items on the device — there was no way to do
        this before; Copy/Move were the only two verbs the window offered.
        The shell's own delete verb does the actual removal (see
        mtp_delete), so its own confirmation applies on top of this one."""
        if self._xfer_busy():
            return
        names = self._selected_names()
        if not names:
            messagebox.showinfo("Delete", "Select what to delete first.",
                                parent=self)
            return
        if not self.chain:
            messagebox.showinfo("Delete", "Open a device first.", parent=self)
            return
        if not _ask_yes_no(
                "Delete from device",
                f"Delete {len(names)} item(s) from:\n" +
                "  ▸  ".join(self.chain) + "\n\nThis cannot be undone.",
                parent=self):
            return
        chain = list(self.chain)
        self._xfer = True
        self._set_status("Deleting…")

        def work():
            err = mtp_delete(chain, names,
                             progress=self._progress_cb("Deleting"))
            _ui_call(self, lambda: self._after_delete(err))

        threading.Thread(target=work, daemon=True).start()

    def _after_delete(self, err):
        self._xfer = False
        if err:
            self._set_status("✘  " + err)
            messagebox.showerror("Delete failed", err, parent=self)
            return
        self._set_status("✔  Deleted.")
        self.reload()

    def _after_copy(self, err, panel, verb="copy"):
        self._xfer = False
        if err:
            self._set_status("✘  " + err)
            messagebox.showerror(f"{verb.capitalize()} failed", err, parent=self)
            return
        self._set_status(f"✔  Done — the {verb} finished.")
        if panel is not None:
            try:
                panel.refresh()
            except Exception:
                pass
        self.after(1500, self.reload)

    def open_in_explorer(self):
        """Explorer can browse MTP natively — a useful escape hatch."""
        try:
            if self.chain:
                devs = {d["name"]: d["path"] for d in mtp_list_devices_cached()}
                target = devs.get(self.chain[0], "")
                if target:
                    subprocess.Popen(["explorer.exe", target],
                                     **_no_window_kwargs())
                    return
            subprocess.Popen(["explorer.exe", "shell:MyComputerFolder"],
                             **_no_window_kwargs())
        except Exception as exc:
            messagebox.showerror("Explorer", str(exc), parent=self)


# ══════════════════════════════════════════════════════════════════════════
#  DEL 50 — Relocator  (⤴  throw files where they belong)
# ══════════════════════════════════════════════════════════════════════════
#
# A rule says "these files, from here, belong THERE" and the ⤴ button carries
# it out — through the Task Queue, so it is one click and no waiting.
#
#   LEFT-click  ⤴  → the list of rules, with how many files each one would
#                    move right now, and a ▶ Run beside each.
#   RIGHT-click ⤴  → run every enabled rule, IN ORDER, one at a time (a single
#                    "run N rules?" confirmation unless it is turned off).
#
# THE ORDER MATTERS, because the rules hand work to each other:
#     1.  dist      →  Exe-redo        (every *.exe that got rebuilt)
#     2.  Exe-redo  →  1---Blandat     (only the programs you list)
# Rule 2 has nothing to do until rule 1 has been and gone, so "Run all" starts
# a rule, lets the Task Queue FINISH it, and only then looks at the next one —
# re-scanning it first if (and only if) a rule before it actually moved
# something.  ▲▼ in the popup and in the rules window set that order; the
# numbers 1., 2., 3. … in both lists are it.
#
# Two kinds of rule:
#
#   pattern     Files in a folder whose name matches a wildcard — that is the
#               "every Backup<code>- file goes to my backup folder" rule, and
#               equally "every Bildningspodden*.mp3 in Downloads goes to the
#               podcast folder".  Optionally only files older than N days.
#
#   newer       The other way round: files in X that are NEWER than the copy
#               the destination already has — those get sent over.  The file
#               they replace can be RETIRED first: renamed Backup<code>- and
#               moved to a third folder BEFORE the new one lands, which is the
#               only safe order (and the only one that works on a program that
#               is running — Windows lets a busy .exe be renamed, never
#               overwritten).  That is the build → stage → install move:
#                 dist       →  Exe-Redo      (every *.exe that got rebuilt)
#                 Exe-Redo   →  1---Blandat   (only the programs you list)
#               with the replaced copies piling up in one "delete later" folder.
#
#   superseded  Files in folder X that a NEWER copy in folder Y has replaced —
#               matched by name with any " (3)" suffix taken off, which is
#               what makes the browser's third save of the same program count
#               as the same file.  Those go to folder Z.  ("X is Temp, Y is
#               where the Python files live, Z is where the old ones end up.")
#
# The rules live in Helpfiles/redigerare/relocator.json.

RELOCATOR_KINDS = [
    ("Files whose NAME matches a pattern",        "pattern"),
    ("Files a NEWER copy elsewhere has replaced", "superseded"),
    ("Files NEWER than the copy over there",      "newer"),
]
RELOCATOR_KIND_LABEL = {k: lbl for lbl, k in RELOCATOR_KINDS}

# What "old" means when the rule asks for it, and the slack allowed before one
# file counts as older than another (a copy across a FAT volume can shift a
# timestamp by up to two seconds).
RELOCATOR_MTIME_SLACK = 2.0

# How often "Run all" asks the Task Queue whether the rule it is on is through.
# Cheap (it reads a field on a handful of task objects) but not free, and a
# status line that rewrites itself three times a second reads as a flicker —
# which is why the text is only refreshed every seventh look.
RELOCATOR_POLL_MS = 300


def _reloc_task_finished(task) -> bool:
    """A queue job that will not move another byte, whichever way it ended."""
    return getattr(task, "status", None) in (
        TaskStatus.DONE, TaskStatus.CANCELLED, TaskStatus.ERROR)


def _reloc_task_parked(task) -> bool:
    """Pending, but not going anywhere until somebody answers something.

    Worth telling apart from "still copying": the chain waits for both, but a
    parked job waits for YOU, and a run window that says "3 files · 40s" while
    the queue is holding a question is a window that lies."""
    if getattr(task, "status", None) != TaskStatus.PENDING:
        return False
    return (getattr(task, "conflict_mode", "") == "pending_conflicts"
            or getattr(task, "preflight", "done") == "twins"
            or bool(getattr(task, "wait_reason", ""))
            or bool(getattr(task, "space_warning", "")))


def _load_relocator_rules() -> list:
    return _load_json_list(RELOCATOR_PATH, portable=True)


def _save_relocator_rules(rules: list):
    _save_json_list(RELOCATOR_PATH, rules, portable=True)


def _reloc_norm(p: str) -> str:
    """One comparable spelling of a path — case-folded and absolute."""
    try:
        return os.path.normcase(os.path.abspath(p))
    except Exception:
        return os.path.normcase(p or "")


def _reloc_under(path_n: str, folder_n: str) -> bool:
    """Is *path_n* that folder, or anything inside it?  Both already normed.

    The separator matters: without it  C:\\Work\\Backup2  counts as inside
    C:\\Work\\Backup, which is exactly the kind of quiet over-reach an exclude
    list must not have.
    """
    if not folder_n:
        return False
    if path_n == folder_n:
        return True
    return path_n.startswith(folder_n.rstrip("\\/") + os.sep)


def _relocator_excludes(rule: dict) -> tuple:
    """The rule's "never look in here" list, split into paths and bare names.

    A line with a separator or a drive letter in it is a PATH: that folder and
    everything under it.  A line without one is a NAME, and matches any folder
    called that at any depth — which is how "leave every Backup folder alone"
    stays one line instead of twenty.
    """
    paths, names = set(), set()
    for raw in (rule.get("exclude") or []):
        s = (raw or "").strip().strip('"')
        if not s:
            continue
        if ("\\" in s or "/" in s or (len(s) > 1 and s[1] == ":")):
            paths.add(_reloc_norm(s))
        else:
            names.add(s.lower())
    return paths, names


def _reloc_is_excluded(folder: str, ex_paths, ex_names) -> bool:
    """Is this folder one the rule was told to stay out of?"""
    if not ex_paths and not ex_names:
        return False
    if ex_names:
        if os.path.basename(folder.rstrip("\\/")).lower() in ex_names:
            return True
    if ex_paths:
        n = _reloc_norm(folder)
        for f in ex_paths:
            if _reloc_under(n, f):
                return True
    return False


def _relocator_iter_files(folder: str, subfolders: bool,
                          ex_paths=(), ex_names=()):
    """Every FILE in *folder* (optionally below it), skipping our own trash.

    An excluded folder is PRUNED from the walk, not filtered out of the
    results afterwards: "never look in the backup folder" means do not walk
    into it at all, which on a real backup tree is also the difference between
    a scan that is instant and one that reads ten thousand files to throw them
    all away.
    """
    if _reloc_is_excluded(folder, ex_paths, ex_names):
        return
    try:
        if subfolders:
            for dirpath, dirs, fnames in os.walk(folder):
                dirs[:] = [d for d in dirs
                           if not _reloc_is_excluded(os.path.join(dirpath, d),
                                                     ex_paths, ex_names)]
                for fn in fnames:
                    yield os.path.join(dirpath, fn)
        else:
            with os.scandir(folder) as it:
                for e in it:
                    try:
                        if e.is_file():
                            yield e.path
                    except OSError:
                        continue
    except Exception as exc:
        _log(f"Relocator: could not read {folder}: {exc}")


def _relocator_sources(rule: dict, active_dir: str) -> list:
    """Every folder this rule works on, in order, without repeats.

    One rule can name SEVERAL folders now, so "the same tidy-up for four
    download folders" is one rule instead of four almost-identical ones that
    have to be edited four times.  A rule written before this only has
    "source", and a blank entry still means "whichever folder I am looking at".
    """
    raw = rule.get("sources")
    if not isinstance(raw, list):
        raw = [rule.get("source", "")]
    out, seen = [], set()
    for s in raw:
        s = (s or "").strip().strip('"') or (active_dir or "")
        if not s:
            continue
        key = _reloc_norm(s)
        if key in seen:
            continue
        seen.add(key)
        out.append(s)
    return out


def _relocator_source(rule: dict, active_dir: str) -> str:
    """The FIRST folder a rule works on — for everything that wants just one."""
    srcs = _relocator_sources(rule, active_dir)
    return srcs[0] if srcs else ""


def _relocator_name_matches(name: str, pats: list) -> bool:
    """Does *name* answer to any of the rule's patterns?

    An EXACT name always matches itself, whatever characters are in it.  That
    is not free with fnmatch alone: square brackets are a character class
    there, so a rule naming a real file called  Report[2].exe  matched nothing
    and said nothing about why.  (Round brackets were never the problem —
    "F(re)email.exe" has always matched — but the same surprise is one square
    bracket away, and "my file is named exactly this" is what typing a full
    filename means.)  Wildcards keep working exactly as before; this only ever
    matches MORE, never less.
    """
    n = name.lower()
    for p in pats:
        p = p.lower()
        if n == p or fnmatch.fnmatch(n, p):
            return True
    return False


# Why a rule found nothing.  A bare "nothing" beside a rule is the single most
# confusing thing the Relocator does: the file is right there, the pattern
# names it, and the rule still says nothing — because "newer" quietly skips a
# program the destination has no copy of YET.  Every reason a file is dropped
# is counted here so the popup can say which one it was.
_RELOC_STAT_KEYS = ("seen", "pattern", "age", "at_dest", "no_twin",
                    "not_newer", "no_cmp", "not_older",
                    "missing", "same_as_dest")


def _relocator_scan(rule: dict, active_dir: str, stats: dict = None) -> list:
    """The files this rule would move RIGHT NOW, as full paths.

    Runs off the UI thread (the popup and the run-everything path both call it
    from a worker), so it never raises: an unreadable folder is an empty list.

    Pass a dict as *stats* and it is filled in with why files were dropped —
    see _relocator_reason(), which turns that into one line of plain English.
    """
    if stats is not None:
        stats.clear()
        stats.update({k: 0 for k in _RELOC_STAT_KEYS})
        stats["blocked"] = ""

    def _blocked(why: str):
        if stats is not None:
            stats["blocked"] = why
        return []

    srcs = _relocator_sources(rule, active_dir)
    dest = (rule.get("dest") or "").strip()
    if not srcs:
        return _blocked("no source folder")
    live = [s for s in srcs if os.path.isdir(s)]
    if stats is not None:
        stats["missing"] = len(srcs) - len(live)
    if not live:
        if len(srcs) == 1:
            return _blocked(f"the source folder is not there:  {srcs[0]}")
        return _blocked(f"none of the {len(srcs)} source folders is there")
    if not dest:
        return _blocked("no destination folder")
    try:
        dest_n = _reloc_norm(dest)
    except Exception:
        return _blocked("the folders could not be read")
    # A folder that IS the destination is dropped rather than fatal — with a
    # list of sources, one of them being the destination is a typo in one line,
    # not a broken rule.
    same = [s for s in live if _reloc_norm(s) == dest_n]
    live = [s for s in live if _reloc_norm(s) != dest_n]
    if not live:
        return _blocked("source and destination are the same folder")
    if same and stats is not None:
        stats["same_as_dest"] = len(same)
    ex_paths, ex_names = _relocator_excludes(rule)
    if live and all(_reloc_is_excluded(s, ex_paths, ex_names) for s in live):
        return _blocked("every source folder is on this rule's exclude list")

    kind    = rule.get("kind", "pattern")
    pats    = [p.strip() for p in _re.split(r"[;,]", rule.get("match", "") or "")
               if p.strip()]
    cmp_dir = (rule.get("compare") or "").strip()
    if kind == "superseded" and (not cmp_dir or not os.path.isdir(cmp_dir)):
        return _blocked("the folder to compare against is missing")
    # "newer" compares against the DESTINATION itself — that is the folder
    # whose copy is being replaced.
    include_new = bool(rule.get("include_new"))
    if kind == "newer" and not os.path.isdir(dest):
        # Nothing to be newer THAN yet.  Only worth doing when the rule has
        # been told to send files the other side does not have at all.
        if not include_new:
            return _blocked("the destination folder does not exist yet, and "
                            "“Files the destination does not have at all  ▸  "
                            "Also send those” is off")
    try:
        min_age = float(rule.get("min_age_days") or 0)
    except (TypeError, ValueError):
        min_age = 0.0
    try:
        max_age = float(rule.get("max_age_days") or 0)
    except (TypeError, ValueError):
        max_age = 0.0
    now = _time.time()

    sub = bool(rule.get("subfolders"))

    # The folder the files are delivered to (and, for "newer", the one the
    # replaced copies are retired to) is NEVER walked into.  It used to be
    # filtered out file by file afterwards, which still read the whole
    # destination tree on every run, and the editor refused any rule whose
    # destination sat inside a source.  Pruning it here means that case is
    # simply fine: nothing delivered is ever picked up again.
    auto_skip = {dest_n}
    retire = (rule.get("retire_dir") or "").strip()
    if kind == "newer" and retire:
        auto_skip.add(_reloc_norm(retire))

    def _every_file():
        """All the source folders as one stream, so the filters below stay
        exactly as they were when a rule had only one folder."""
        for folder in live:
            fold_n = _reloc_norm(folder)
            # A source that itself lives inside the destination is left to the
            # "already at the destination" test below, which says so.
            extra = {a for a in auto_skip if not _reloc_under(fold_n, a)}
            for p in _relocator_iter_files(folder, sub,
                                           set(ex_paths) | extra, ex_names):
                yield p

    out = []
    seen_files = set()
    for path in _every_file():
        name = os.path.basename(path)
        if name.startswith(TRASH_PREFIX):
            continue                   # already deleted, just not purged yet
        # Two source folders may overlap (one inside another, or the same
        # folder reached two ways).  Count and move a file ONCE.
        key = _reloc_norm(path)
        if key in seen_files:
            continue
        seen_files.add(key)
        if stats is not None:
            stats["seen"] += 1
        try:
            # "Already at the destination" now covers the destination's own
            # sub-folders too.  It did not before, so a rule recursing into a
            # destination that sits INSIDE its source picked its own delivered
            # files back up one level down.
            if _reloc_under(_reloc_norm(os.path.dirname(path)), dest_n):
                if stats is not None:
                    stats["at_dest"] += 1
                continue               # already living at the destination
        except Exception:
            pass
        if pats and not _relocator_name_matches(name, pats):
            if stats is not None:
                stats["pattern"] += 1
            continue
        try:
            mtime = os.path.getmtime(path)
        except OSError:
            continue
        if min_age > 0 and (now - mtime) < min_age * 86400:
            if stats is not None:
                stats["age"] += 1
            continue
        if max_age > 0 and (now - mtime) > max_age * 86400:
            if stats is not None:
                stats["age"] += 1
            continue        # too old to be interesting (e.g. last week's builds)

        if kind == "superseded":
            # The same file, one "(3)" apart — that is the whole point here.
            twin = os.path.join(cmp_dir, _strip_copy_suffix(name))
            try:
                if not os.path.isfile(twin):
                    if stats is not None:
                        stats["no_cmp"] += 1
                    continue
                if mtime >= os.path.getmtime(twin) - RELOCATOR_MTIME_SLACK:
                    if stats is not None:
                        stats["not_older"] += 1
                    continue           # not older than its replacement
            except OSError:
                continue

        elif kind == "newer":
            there = os.path.join(dest, name)
            try:
                if not os.path.isfile(there):
                    if not include_new:
                        if stats is not None:
                            stats["no_twin"] += 1
                        continue       # nothing over there to be newer than
                elif mtime <= os.path.getmtime(there) + RELOCATOR_MTIME_SLACK:
                    if stats is not None:
                        stats["not_newer"] += 1
                    continue           # the copy over there is as new, or newer
            except OSError:
                continue

        out.append(path)
    return out


def _relocator_reason(stats: dict, rule: dict) -> str:
    """One line saying why a rule came back with nothing.

    Ordered by how surprising the reason is, not by how many files it hit: a
    file that matched the pattern and was still dropped is the thing worth
    saying, even when a hundred others simply did not match."""
    if not stats:
        return ""
    blocked = stats.get("blocked") or ""
    if blocked:
        return blocked
    if not stats.get("seen"):
        if stats.get("missing"):
            return (f"nothing to read — {stats['missing']} of the rule's source "
                    "folder(s) is not there")
        if (rule.get("exclude") or []):
            return ("the source folder is empty — or everything in it is "
                    "under one of this rule's excluded folders")
        return "the source folder is empty"
    if stats.get("no_twin"):
        n = stats["no_twin"]
        return (f"{n} file(s) matched, but the destination has no copy of "
                f"{'them' if n != 1 else 'it'} yet — in the rule, tick "
                f"“Files the destination does not have at all  ▸  Also send those”")
    if stats.get("not_newer"):
        return (f"{stats['not_newer']} file(s) matched, but the copy at the "
                "destination is already as new")
    if stats.get("not_older"):
        return (f"{stats['not_older']} file(s) matched, but none is older than "
                "its replacement")
    if stats.get("no_cmp"):
        return (f"{stats['no_cmp']} file(s) matched, but the compare folder "
                "has nothing of the same name")
    if stats.get("age"):
        return f"{stats['age']} file(s) matched, but fell outside the age limits"
    if stats.get("at_dest"):
        return "everything is already at the destination"
    if stats.get("pattern"):
        return (f"none of the {stats['pattern']} file(s) in the folder answers "
                "to this rule's pattern")
    return ""


def _relocator_describe(rule: dict, active_dir: str = "") -> str:
    """One line saying what the rule does, for the popup and the rule list."""
    srcs = _relocator_sources(rule, active_dir)
    src  = srcs[0] if srcs else "(the active panel)"
    if len(srcs) > 1:
        src += f"        (+ {len(srcs) - 1} more folder"
        src += ")" if len(srcs) == 2 else "s)"
    raw_srcs = rule.get("sources")
    if not isinstance(raw_srcs, list):
        raw_srcs = [rule.get("source", "")]
    if not any((s or "").strip() for s in raw_srcs):
        src += "   ← wherever you are"
    verb = "Move" if rule.get("action", "move") == "move" else "Copy"
    kind = rule.get("kind", "pattern")
    if kind == "superseded":
        what = f"replaced by a newer copy in  {rule.get('compare','?')}"
    elif kind == "newer":
        what = f"{rule.get('match') or '*'}  —  newer than the copy over there"
    else:
        what = (rule.get("match") or "*")
    line = f"{verb}   {what}\nfrom   {src}\nto        {rule.get('dest','?')}"
    retire = (rule.get("retire_dir") or "").strip()
    if kind == "newer" and retire:
        line += f"\nthe replaced copy is retired to   {retire}"
    ex = [e.strip() for e in (rule.get("exclude") or []) if (e or "").strip()]
    if ex:
        shown = "   ·   ".join(ex[:2])
        if len(ex) > 2:
            shown += f"   (+{len(ex) - 2})"
        line += f"\nnever looks in   {shown}"
    return line


class RelocatorRunWindow(tk.Toplevel):
    """“Run all” in flight — the rules, in order, ticked off as they go.

    Nothing here drives the work: the chain lives in EditorFrame and runs just
    as well with this window shut.  It exists because a CHAIN waits — one click
    can now mean half a minute of copying before the last rule so much as
    starts, and without a window that is a program that looks like it did
    nothing at all.

    Non-modal on purpose: the Task Queue may need an answer while this is up,
    and a grab here would be a program holding the door shut against itself.
    """

    def __init__(self, manager: "EditorFrame", found: list):
        super().__init__(manager)
        self.manager = manager
        self.configure(bg=C_BG)
        _setup_toplevel(self, "Relocator — running", manager, modal=False)
        self.resizable(True, True)
        self._rows = {}
        self._row_frames = {}
        self._build(found)
        self._place(manager)

    def _build(self, found: list):
        head = tk.Frame(self, bg=C_BG3)
        head.pack(fill="x")
        tk.Label(head, text="⤴  Running the rules", bg=C_BG3, fg=C_ACCENT,
                 font=("Segoe UI", 12, "bold")).pack(side="left", padx=10, pady=7)
        tk.Label(head, text="one at a time, top to bottom",
                 bg=C_BG3, fg=C_FG_DIM,
                 font=("Segoe UI", 9)).pack(side="left")

        # Bottom first: the packer gives an expanding widget everything that is
        # left, and a status line packed after it comes out one pixel tall.
        self._status = tk.Label(
            self, text="Each rule waits for the one before it to finish.",
            bg=C_BG, fg=C_FG_DIM, anchor="w", font=("Segoe UI", 8))
        self._status.pack(side="bottom", fill="x", padx=12, pady=(0, 8))

        bot = tk.Frame(self, bg=C_BG)
        bot.pack(side="bottom", fill="x", padx=10, pady=(0, 6))
        self._btn_close = tk.Button(bot, text="Close", bg="grey", fg="white",
                                    width=9, activebackground="grey",
                                    command=self.destroy)
        self._btn_close.pack(side="right", padx=3)
        self._auto_var = tk.BooleanVar(
            value=bool(self.manager.settings.get("relocator_autoclose", True)))
        tk.Checkbutton(bot, text="Close this window when done",
                       variable=self._auto_var, bg=C_BG, fg=C_FG_DIM,
                       activebackground=C_BG, activeforeground=C_FG,
                       selectcolor=C_BG2,
                       command=self._save_auto).pack(side="left")
        self._btn_stop = tk.Button(bot, text="⏹  Stop after this rule",
                                   bg="white", fg="black",
                                   activebackground="white",
                                   command=self._stop)
        self._btn_stop.pack(side="right", padx=3)

        # The rows SCROLL: with a couple of dozen rules the window used to grow
        # past the bottom of the desktop, taking the status line and the Close
        # button with it.  Bottom widgets are packed above, so they stay put.
        outer = tk.Frame(self, bg=C_BG)
        outer.pack(fill="both", expand=True, padx=10, pady=(8, 4))
        self._canvas = tk.Canvas(outer, bg=C_BG, highlightthickness=0, height=40)
        # A tk.Scrollbar, not ttk: the themed one is nearly invisible on dark.
        self._vsb = tk.Scrollbar(outer, orient="vertical",
                                 command=self._canvas.yview,
                                 bg=C_BG3, troughcolor=C_BG,
                                 activebackground=C_BG3,
                                 highlightthickness=0, bd=0)
        self._canvas.configure(yscrollcommand=self._vsb.set)
        self._vsb.pack(side="right", fill="y")
        self._canvas.pack(side="left", fill="both", expand=True)
        body = tk.Frame(self._canvas, bg=C_BG)
        self._body = body
        self._body_id = self._canvas.create_window((0, 0), window=body,
                                                   anchor="nw")
        body.bind("<Configure>", lambda e: self._canvas.configure(
            scrollregion=self._canvas.bbox("all")))
        self._canvas.bind("<Configure>", lambda e: self._canvas.itemconfig(
            self._body_id, width=e.width))

        def _wheel(e):
            self._canvas.yview_scroll(-1 * (e.delta // 120), "units")
            return "break"

        self._wheel = _wheel
        self._canvas.bind("<MouseWheel>", _wheel)
        body.bind("<MouseWheel>", _wheel)
        for idx, (rule, files) in enumerate(found):
            row = tk.Frame(body, bg=C_BG2, padx=8, pady=4)
            row.pack(fill="x", pady=2)
            row.bind("<MouseWheel>", _wheel)
            self._row_frames[idx] = row
            tk.Label(row, text=f"{idx + 1}.", bg=C_BG2, fg=C_FG_DIM,
                     font=("Segoe UI", 9), width=3,
                     anchor="w").pack(side="left")
            state = tk.Label(row, text="waiting", bg=C_BG2, fg=C_FG_DIM,
                             font=("Segoe UI", 9), width=20, anchor="e")
            state.pack(side="right")
            tk.Label(row, text=rule.get("name") or "(unnamed rule)", bg=C_BG2,
                     fg=C_FG, font=("Segoe UI", 9, "bold"), anchor="w",
                     justify="left").pack(side="left", fill="x", expand=True)
            self._rows[idx] = state
            for w in row.winfo_children():
                w.bind("<MouseWheel>", _wheel)

    def _place(self, manager):
        self.update_idletasks()
        # Let the list ask for its own height, but never more than the desktop
        # can show with the header, status line and buttons around it.
        try:
            room = max(160, self.winfo_screenheight() - 300)
            self._canvas.configure(
                height=min(self._body.winfo_reqheight(), room))
            self.update_idletasks()
        except Exception:
            pass
        w = max(520, self.winfo_reqwidth())
        h = self.winfo_reqheight()
        try:
            x = manager.winfo_rootx() + 90
            y = manager.winfo_rooty() + 90
            x = max(0, min(x, self.winfo_screenwidth()  - w - 10))
            y = max(0, min(y, self.winfo_screenheight() - h - 40))
            self.geometry(f"{w}x{h}+{x}+{y}")
        except Exception:
            pass

    # ── driven from the chain ─────────────────────────────────────────────
    def set_row(self, idx: int, text: str, colour: str = None):
        lbl = self._rows.get(idx)
        if lbl is None:
            return
        try:
            lbl.configure(text=text, fg=(colour or C_FG))
        except Exception:
            pass
        self._see(idx)

    def _see(self, idx: int):
        """Scroll so the row being updated is on screen."""
        try:
            row = self._row_frames.get(idx)
            if row is None:
                return
            self.update_idletasks()
            total = max(1, self._body.winfo_height())
            top, bot = self._canvas.yview()
            y0 = row.winfo_y() / total
            y1 = (row.winfo_y() + row.winfo_height()) / total
            if y0 < top:
                self._canvas.yview_moveto(max(0.0, y0 - 0.01))
            elif y1 > bot:
                self._canvas.yview_moveto(
                    max(0.0, y1 - (bot - top) + 0.01))
        except Exception:
            pass

    def _save_auto(self):
        self.manager.settings["relocator_autoclose"] = bool(self._auto_var.get())
        try:
            self.manager.save_settings()
        except Exception:
            pass

    def finished(self, moved: int, ran: int, total: int, stopped: bool,
                 clean: bool = True):
        auto = False
        try:
            auto = bool(self._auto_var.get()) and clean and not stopped
        except Exception:
            pass
        try:
            self._btn_stop.configure(state="disabled")
            self._btn_close.configure(bg="lightgreen", fg="black",
                                      activebackground="lightgreen")
            self._status.configure(
                text=(f"Stopped after {ran} of {total} rule(s)  ·  "
                      f"{moved} file move(s)" if stopped else
                      f"Done  ·  {total} rule(s), {moved} file move(s)"),
                fg=("#e8c84a" if stopped else "#55aa55"))
        except Exception:
            pass
        if auto:
            # Long enough to read "Done", short enough to be out of the way.
            # Re-checks the tick-box: it may have been unticked while waiting.
            try:
                self.after(2000, self._auto_close)
            except Exception:
                pass

    def _auto_close(self):
        try:
            if self.winfo_exists() and self._auto_var.get():
                self.destroy()
        except Exception:
            pass

    def present(self):
        try:
            self.deiconify()
            self.lift()
        except Exception:
            pass

    def _stop(self):
        self.manager.relocator_stop_chain()
        try:
            self._btn_stop.configure(state="disabled")
            self._status.configure(
                text="Stopping — the rule that is going will finish first.",
                fg="#e8c84a")
        except Exception:
            pass


class RelocatorPopup(tk.Toplevel):
    """Left-click on ⤴ — the rules, with live counts and a ▶ beside each."""

    def __init__(self, manager: "EditorFrame", anchor=None):
        super().__init__(manager)
        self.manager = manager
        self.configure(bg=C_BG)
        _setup_toplevel(self, "Relocator", manager, modal=False)
        self.resizable(True, True)
        self.rules  = _load_relocator_rules()
        self._rows  = {}          # rule index → (count label, run button, why label)
        self._found = {}          # rule index → [paths]  (filled in by the scan)
        self._why   = {}          # rule index → why it found nothing, in words
        self._build()
        self._place_near(anchor)
        self._rescan()

    # ── layout ────────────────────────────────────────────────────────────
    def _build(self):
        head = tk.Frame(self, bg=C_BG3)
        head.pack(fill="x")
        tk.Label(head, text="⤴  Relocator", bg=C_BG3, fg=C_ACCENT,
                 font=("Segoe UI", 12, "bold")).pack(side="left", padx=10, pady=7)
        tk.Label(head, text="Throw files where they belong  ·  Run all goes "
                            "1, 2, 3 …, one rule at a time",
                 bg=C_BG3, fg=C_FG_DIM, font=("Segoe UI", 9)).pack(side="left")
        # Both doors, side by side: "Edit rules…" reads as "change what is
        # already there", so a NEW rule looked impossible from here once the
        # first one existed.
        tk.Button(head, text="✎  Edit rules…", bg="white", fg="black",
                  activebackground="white",
                  command=self._edit_rules).pack(side="right", padx=(4, 8), pady=5)
        tk.Button(head, text="＋  New rule", bg="lightgreen", fg="black",
                  activebackground="lightgreen",
                  command=self._new_rule).pack(side="right", padx=4, pady=5)

        # The bottom row and the status line are packed BEFORE the list, or the
        # list's expand=True would eat their space and leave them 1 px tall —
        # the packer trap this program has been bitten by before.
        self._status = tk.Label(self, text="", bg=C_BG, fg=C_FG_DIM,
                                anchor="w", font=("Segoe UI", 8))
        self._status.pack(side="bottom", fill="x", padx=12, pady=(0, 8))

        bot = tk.Frame(self, bg=C_BG)
        bot.pack(side="bottom", fill="x", padx=10, pady=(0, 6))
        self._ask_var = tk.BooleanVar(
            value=bool(self.manager.settings.get("relocator_confirm", True)))
        tk.Checkbutton(bot, text="Ask before running everything",
                       variable=self._ask_var, bg=C_BG, fg=C_FG_DIM,
                       activebackground=C_BG, activeforeground=C_FG,
                       selectcolor=C_BG2, command=self._save_ask).pack(side="left")
        tk.Button(bot, text="Close", bg="grey", fg="white", width=9,
                  activebackground="grey",
                  command=self.destroy).pack(side="right", padx=3)
        self._btn_all = tk.Button(bot, text="▶▶  Run all in order",
                                  bg="lightgreen",
                                  fg="black", activebackground="lightgreen",
                                  command=self._run_all)
        self._btn_all.pack(side="right", padx=3)

        self.body = tk.Frame(self, bg=C_BG)
        self.body.pack(fill="both", expand=True, padx=10, pady=(8, 4))
        self._render()

    def _place_near(self, anchor):
        """Open just under the ⤴ button, kept on screen."""
        self.update_idletasks()
        w = max(560, self.winfo_reqwidth())
        h = max(220, self.winfo_reqheight())
        try:
            if anchor is not None and anchor.winfo_exists():
                x = anchor.winfo_rootx() - w + anchor.winfo_width() + 20
                y = anchor.winfo_rooty() + anchor.winfo_height() + 4
            else:
                x = self.manager.winfo_rootx() + 80
                y = self.manager.winfo_rooty() + 80
            x = max(0, min(x, self.winfo_screenwidth()  - w - 10))
            y = max(0, min(y, self.winfo_screenheight() - h - 40))
            self.geometry(f"{w}x{h}+{x}+{y}")
        except Exception:
            pass

    def _render(self):
        for w in self.body.winfo_children():
            w.destroy()
        self._rows.clear()

        if not self.rules:
            tk.Label(self.body,
                     text="No rules yet.\n\n"
                          "A rule says “these files, from here, belong THERE”.\n"
                          "Pick a ready-made one to start from:",
                     bg=C_BG, fg=C_FG_DIM, font=("Segoe UI", 10),
                     justify="left").pack(anchor="w", pady=(6, 10))
            for label, maker in (
                ("⤴  Backup-old files  →  a backup folder", self._starter_backup),
                ("⤴  Files a newer copy has replaced  →  an old-versions folder",
                 self._starter_superseded),
                ("⤴  Files NEWER than the copy over there  →  send them over",
                 self._starter_newer),
                ("＋  Empty rule — fill it in myself", self._new_rule)):
                tk.Button(self.body, text=label, bg=C_BG2, fg=C_FG, anchor="w",
                          activebackground=C_BG3, activeforeground=C_FG,
                          relief="flat", padx=10, pady=6,
                          command=maker).pack(fill="x", pady=3)
            self._btn_all.configure(state="disabled")
            return

        self._btn_all.configure(state="normal")
        for idx, r in enumerate(self.rules):
            self._render_row(idx, r)

    def _render_row(self, idx: int, r: dict):
        enabled = r.get("enabled", True)
        row = tk.Frame(self.body, bg=C_BG2, padx=8, pady=5)
        row.pack(fill="x", pady=2)

        var = tk.BooleanVar(value=enabled)

        def _toggle(i=idx, v=var):
            self.rules[i]["enabled"] = bool(v.get())
            _save_relocator_rules(self.rules)
            self._render()
            self._rescan()

        # fg matters: the tick itself is drawn in the FOREGROUND colour, and the
        # default (black) on a dark indicator is invisible — an enabled rule
        # looked switched off.
        tk.Checkbutton(row, variable=var, bg=C_BG2, activebackground=C_BG2,
                       fg=C_FG, activeforeground=C_FG,
                       selectcolor=C_BG, command=_toggle).pack(side="left")

        left = tk.Frame(row, bg=C_BG2)
        left.pack(side="left", fill="x", expand=True, padx=(4, 0))
        # The number is not decoration: it is the order "Run all" goes in.
        tk.Label(left, text=f"{idx + 1}.  "
                            f"{r.get('name') or '(unnamed rule)'}", bg=C_BG2,
                 fg=(C_FG if enabled else C_FG_DIM),
                 font=("Segoe UI", 9, "bold"), anchor="w").pack(anchor="w")
        tk.Label(left, text=_relocator_describe(
                     r, getattr(self.manager.get_active_panel(),
                                "current_path", "")).replace("\n", "   ·   "),
                 bg=C_BG2, fg=C_FG_DIM, font=("Segoe UI", 8), anchor="w",
                 wraplength=430, justify="left").pack(anchor="w")
        # Filled in by _scan_done when the rule finds nothing.  A bare
        # "nothing" beside a rule whose file is plainly sitting there is the
        # most confusing thing this window does — this says which test the
        # file failed, in words, without opening the rule.
        why = tk.Label(left, text="", bg=C_BG2, fg="#e8c84a",
                       font=("Segoe UI", 8), anchor="w",
                       wraplength=430, justify="left")

        right = tk.Frame(row, bg=C_BG2)
        right.pack(side="right")
        cnt = tk.Label(right, text="counting…", bg=C_BG2, fg=C_FG_DIM,
                       font=("Segoe UI", 9), width=12, anchor="e")
        cnt.pack(side="left", padx=(0, 6))
        btn = tk.Button(right, text="▶  Run", bg="lightblue", fg="black",
                        width=7, state="disabled", activebackground="lightblue",
                        command=lambda i=idx: self._run_one(i))
        btn.pack(side="left")
        tk.Button(right, text="▲", bg=C_BG3, fg=C_FG, width=2,
                  activebackground=C_BG3, activeforeground=C_FG,
                  state=("normal" if idx > 0 else "disabled"),
                  command=lambda i=idx: self._move(i, -1)).pack(side="left",
                                                                padx=(6, 0))
        tk.Button(right, text="▼", bg=C_BG3, fg=C_FG, width=2,
                  activebackground=C_BG3, activeforeground=C_FG,
                  state=("normal" if idx < len(self.rules) - 1 else "disabled"),
                  command=lambda i=idx: self._move(i, 1)).pack(side="left",
                                                               padx=(2, 0))
        self._rows[idx] = (cnt, btn, why)

    def _move(self, idx: int, delta: int):
        """Move a rule up or down — that order IS the running order.

        The counts were taken a moment ago and swapping two rules changes
        nothing on disk, so they are carried across rather than every folder
        being read again."""
        j = idx + delta
        if not (0 <= idx < len(self.rules) and 0 <= j < len(self.rules)):
            return
        self.rules[idx], self.rules[j] = self.rules[j], self.rules[idx]
        _save_relocator_rules(self.rules)
        a, b = self._found.get(idx, []), self._found.get(j, [])
        self._found[idx], self._found[j] = b, a
        # The "why nothing" lines belong to the rules, so they travel with them
        wa, wb = self._why.get(idx, ""), self._why.get(j, "")
        self._why[idx], self._why[j] = wb, wa
        self._render()
        self._scan_done(dict(self._found), dict(self._why))

    # ── scanning ──────────────────────────────────────────────────────────
    def _rescan(self):
        if not self.rules:
            return
        self._status.configure(text="Looking through the folders…")
        active_dir = getattr(self.manager.get_active_panel(), "current_path", "")
        rules = [dict(r) for r in self.rules]

        def _worker():
            found, why = {}, {}
            for i, r in enumerate(rules):
                if not r.get("enabled", True):
                    found[i] = []
                    continue
                try:
                    stats = {}
                    found[i] = _relocator_scan(r, active_dir, stats)
                    if not found[i]:
                        why[i] = _relocator_reason(stats, r)
                except Exception as exc:
                    _log(f"Relocator scan failed for rule {i}: {exc}")
                    found[i] = []
            _ui_call(self, lambda: self._scan_done(found, why))

        threading.Thread(target=_worker, daemon=True).start()

    def _scan_done(self, found: dict, why: dict = None):
        if not self.winfo_exists():
            return
        self._found = found
        if why is not None:
            self._why = why
        why = self._why if why is None else why
        total = 0
        for idx, (cnt, btn, why_lbl) in self._rows.items():
            files = found.get(idx, [])
            total += len(files)
            try:
                reason = ""
                if not self.rules[idx].get("enabled", True):
                    cnt.configure(text="off", fg=C_FG_DIM)
                    btn.configure(state="disabled")
                elif files:
                    cnt.configure(text=f"{len(files)} file"
                                       f"{'s' if len(files) != 1 else ''}",
                                  fg=C_ACCENT)
                    btn.configure(state="normal")
                else:
                    cnt.configure(text="nothing", fg=C_FG_DIM)
                    btn.configure(state="disabled")
                    reason = (why or {}).get(idx, "")
                # The reason line only takes up room when there IS one, so a
                # window full of working rules looks exactly as it did.
                if reason:
                    why_lbl.configure(text="↳  " + reason)
                    if not why_lbl.winfo_ismapped():
                        why_lbl.pack(anchor="w", pady=(2, 0))
                else:
                    why_lbl.configure(text="")
                    why_lbl.pack_forget()
            except Exception as exc:
                _log(f"Relocator row {idx} could not be updated: {exc}")
        self._status.configure(
            text=(f"{total} file(s) waiting to be moved   ·   ▲▼ sets the "
                  "order   ·   a rule can pick up what the rule above it "
                  "delivers, so a “nothing” may not stay one")
            if total else
            "Nothing to move right now   ·   the counts refresh each time you open this")

    # ── actions ───────────────────────────────────────────────────────────
    def _save_ask(self):
        self.manager.settings["relocator_confirm"] = bool(self._ask_var.get())
        try:
            self.manager.save_settings()
        except Exception:
            pass

    def _run_one(self, idx: int):
        rule  = self.rules[idx]
        files = self._found.get(idx, [])
        n = self.manager.run_relocator_rule(rule, files=files)
        if n:
            self.destroy()

    def _run_all(self):
        self.destroy()
        self.manager.run_relocator_all()

    def _edit_rules(self):
        self.destroy()
        self.manager.open_relocator_rules()

    def _new_rule(self):
        """Open the rule list AND a blank rule editor on top of it."""
        self.destroy()
        self.manager.open_relocator_rules(new_rule={})

    # ── ready-made starters ───────────────────────────────────────────────
    def _starter_backup(self):
        here = getattr(self.manager.get_active_panel(), "current_path", "")
        self._prefill({
            "name": "Backup-old files → backup folder",
            "enabled": True, "kind": "pattern",
            "source": here, "subfolders": False,
            "match": "Backup???-*",
            "dest": "", "action": "move", "conflict": "backup_old",
            "strip_suffix": False, "compare": "", "min_age_days": 0,
        })

    def _starter_superseded(self):
        here = getattr(self.manager.get_active_panel(), "current_path", "")
        other = getattr(self.manager.get_inactive_panel(), "current_path", "")
        self._prefill({
            "name": "Superseded files → old-versions folder",
            "enabled": True, "kind": "superseded",
            "source": here, "subfolders": False,
            "match": "", "dest": "", "action": "move",
            "conflict": "backup_old", "strip_suffix": False,
            "compare": other, "min_age_days": 0,
        })

    def _starter_newer(self):
        """The publish move: what is newer here goes over there, and the copy
        it replaces is retired to a third folder."""
        here  = getattr(self.manager.get_active_panel(), "current_path", "")
        other = getattr(self.manager.get_inactive_panel(), "current_path", "")
        self._prefill({
            "name": "Newer here → send it over",
            "enabled": True, "kind": "newer",
            "source": here, "subfolders": False,
            "match": "*.exe", "dest": other, "action": "copy",
            "conflict": "backup_old", "strip_suffix": False,
            "compare": "", "retire_dir": "", "include_new": False,
            "min_age_days": 0, "max_age_days": 0,
        })

    def _prefill(self, prefill: dict):
        self.destroy()
        self.manager.open_relocator_rules(new_rule=prefill)


class RelocatorRulesWindow(tk.Toplevel):
    """Make, edit and delete the Relocator's rules."""

    def __init__(self, manager: "EditorFrame", new_rule: dict = None):
        super().__init__(manager)
        self.manager = manager
        self.configure(bg=C_BG)
        self.geometry("880x520")
        _setup_toplevel(self, "Relocator rules", manager, modal=False)
        self.rules = _load_relocator_rules()
        self._build()
        self._render()
        if new_rule is not None:
            RelocatorRuleEditor(self, self.manager, rule=new_rule)

    def _build(self):
        head = tk.Frame(self, bg=C_BG3)
        head.pack(fill="x")
        tk.Label(head, text="⤴  Relocator rules", bg=C_BG3, fg=C_ACCENT,
                 font=("Segoe UI", 12, "bold")).pack(side="left", padx=10, pady=7)
        tk.Label(head, text="“these files, from here, belong THERE”  ·  "
                            "▲▼ sets the order they run in",
                 bg=C_BG3, fg=C_FG_DIM, font=("Segoe UI", 9)).pack(side="left")

        bar = tk.Frame(self, bg=C_BG)
        bar.pack(fill="x", padx=10, pady=(8, 2))
        tk.Button(bar, text="＋  New rule", bg="lightgreen", fg="black",
                  activebackground="lightgreen",
                  command=self._new).pack(side="left")
        tk.Button(bar, text="Close", bg="grey", fg="white", width=9,
                  activebackground="grey",
                  command=self.destroy).pack(side="right")

        mid = tk.Frame(self, bg=C_BG)
        mid.pack(fill="both", expand=True, padx=10, pady=4)
        canvas = tk.Canvas(mid, bg=C_BG, highlightthickness=0)
        sb = ttk.Scrollbar(mid, orient="vertical", command=canvas.yview)
        canvas.configure(yscrollcommand=sb.set)
        sb.pack(side="right", fill="y")
        canvas.pack(side="left", fill="both", expand=True)
        self._inner = tk.Frame(canvas, bg=C_BG)
        self._inner_id = canvas.create_window((0, 0), window=self._inner,
                                              anchor="nw")
        self._inner.bind("<Configure>",
            lambda e: canvas.configure(scrollregion=canvas.bbox("all")))
        canvas.bind("<Configure>",
            lambda e: canvas.itemconfig(self._inner_id, width=e.width))
        canvas.bind("<MouseWheel>",
            lambda e: canvas.yview_scroll(-1 * (e.delta // 120), "units"))

    def _render(self):
        for w in self._inner.winfo_children():
            w.destroy()
        if not self.rules:
            tk.Label(self._inner,
                     text="No rules yet.  Click  “＋ New rule”.\n\n"
                          "Leave the SOURCE folder blank and the rule works on "
                          "whichever folder the active panel is showing.",
                     bg=C_BG, fg=C_FG_DIM, font=("Segoe UI", 10),
                     justify="left").pack(anchor="w", pady=20)
            return
        for idx, r in enumerate(self.rules):
            self._render_row(idx, r)

    def _render_row(self, idx: int, r: dict):
        enabled = r.get("enabled", True)
        row = tk.Frame(self._inner, bg=C_BG2, padx=8, pady=6)
        row.pack(fill="x", pady=3)

        var = tk.BooleanVar(value=enabled)

        def _toggle(i=idx, v=var):
            self.rules[i]["enabled"] = bool(v.get())
            _save_relocator_rules(self.rules)
            self._render()

        # fg matters: the tick itself is drawn in the FOREGROUND colour, and the
        # default (black) on a dark indicator is invisible — an enabled rule
        # looked switched off.
        tk.Checkbutton(row, variable=var, bg=C_BG2, activebackground=C_BG2,
                       fg=C_FG, activeforeground=C_FG,
                       selectcolor=C_BG, command=_toggle).pack(side="left")

        left = tk.Frame(row, bg=C_BG2)
        left.pack(side="left", fill="x", expand=True, padx=(4, 0))
        # 1., 2., 3. … — the number IS the order "Run all" works through them.
        tk.Label(left, text=f"{idx + 1}.  "
                            f"{r.get('name') or '(unnamed rule)'}", bg=C_BG2,
                 fg=(C_FG if enabled else C_FG_DIM),
                 font=("Segoe UI", 9, "bold"), anchor="w").pack(anchor="w")
        tk.Label(left, text=_relocator_describe(r), bg=C_BG2, fg=C_FG_DIM,
                 font=("Segoe UI", 8), anchor="w", justify="left",
                 wraplength=560).pack(anchor="w")
        extra = []
        if r.get("subfolders"):
            extra.append("sub-folders too")
        if r.get("strip_suffix"):
            extra.append("drops the “(2)” on arrival")
        try:
            if float(r.get("min_age_days") or 0) > 0:
                extra.append(f"only older than {r['min_age_days']} day(s)")
        except (TypeError, ValueError):
            pass
        try:
            if float(r.get("max_age_days") or 0) > 0:
                extra.append(f"only from the last {r['max_age_days']} day(s)")
        except (TypeError, ValueError):
            pass
        extra.append("on clash: " + _CONFLICT_LABEL.get(
            r.get("conflict", "backup_old"), r.get("conflict", "")))
        tk.Label(left, text="   ·   ".join(extra), bg=C_BG2, fg=C_FG_DIM,
                 font=("Segoe UI", 8), anchor="w").pack(anchor="w")

        btns = tk.Frame(row, bg=C_BG2)
        btns.pack(side="right")
        tk.Button(btns, text="▲", bg=C_BG3, fg=C_FG, width=2,
                  activebackground=C_BG3, activeforeground=C_FG,
                  state=("normal" if idx > 0 else "disabled"),
                  command=lambda i=idx: self._move(i, -1)).pack(side="left",
                                                                padx=2)
        tk.Button(btns, text="▼", bg=C_BG3, fg=C_FG, width=2,
                  activebackground=C_BG3, activeforeground=C_FG,
                  state=("normal" if idx < len(self.rules) - 1 else "disabled"),
                  command=lambda i=idx: self._move(i, 1)).pack(side="left",
                                                               padx=(2, 10))
        tk.Button(btns, text="✎ Edit", bg="white", fg="black", width=7,
                  activebackground="white",
                  command=lambda i=idx: self._edit(i)).pack(side="left", padx=2)
        tk.Button(btns, text="⧉", bg="white", fg="black", width=3,
                  activebackground="white",
                  command=lambda i=idx: self._duplicate(i)).pack(side="left", padx=2)
        tk.Button(btns, text="🗑", bg="grey", fg="white", width=3,
                  activebackground="grey",
                  command=lambda i=idx: self._delete(i)).pack(side="left", padx=2)

    def _move(self, idx: int, delta: int):
        """Move a rule up or down the list — that order IS the running order,
        and it is what relocator.json remembers."""
        j = idx + delta
        if not (0 <= idx < len(self.rules) and 0 <= j < len(self.rules)):
            return
        self.rules[idx], self.rules[j] = self.rules[j], self.rules[idx]
        _save_relocator_rules(self.rules)
        self._render()

    def _new(self):
        RelocatorRuleEditor(self, self.manager, rule=None)

    def _edit(self, idx: int):
        if 0 <= idx < len(self.rules):
            RelocatorRuleEditor(self, self.manager, rule=self.rules[idx],
                                edit_idx=idx)

    def _duplicate(self, idx: int):
        if 0 <= idx < len(self.rules):
            copy_r = dict(self.rules[idx])
            copy_r["name"] = (copy_r.get("name", "") or "rule") + " (copy)"
            self.rules.insert(idx + 1, copy_r)
            _save_relocator_rules(self.rules)
            self._render()

    def _delete(self, idx: int):
        if 0 <= idx < len(self.rules):
            if _ask_yes_no("Delete rule", "Delete this rule?", parent=self):
                del self.rules[idx]
                _save_relocator_rules(self.rules)
                self._render()

    def reload(self):
        self.rules = _load_relocator_rules()
        self._render()


class RelocatorRuleEditor(tk.Toplevel):
    """One Relocator rule, field by field."""

    def __init__(self, parent: "RelocatorRulesWindow", manager: "EditorFrame",
                 rule: dict = None, edit_idx: int = None):
        super().__init__(parent)
        self.parent   = parent
        self.manager  = manager
        self.edit_idx = edit_idx
        r = dict(rule or {})
        self.configure(bg=C_BG)
        # Vertically resizable since revAW — the fields scroll, so dragging the
        # window taller is a real way to see more of them at once.
        self.resizable(False, True)
        _setup_toplevel(self, "Relocator rule", parent, modal=True)

        self.v_name   = tk.StringVar(value=r.get("name", ""))
        self.v_kind   = tk.StringVar(value=r.get("kind", "pattern"))
        # revAW — a rule can name SEVERAL source folders and any number of
        # folders to stay out of.  An older rule has a single "source"; either
        # way the editor works on a list, and _collect writes both keys back.
        _srcs = r.get("sources")
        if not isinstance(_srcs, list):
            _srcs = [r.get("source", "")]
        self._src_init  = list(_srcs) or [""]
        self._excl_init = [e for e in (r.get("exclude") or []) if str(e).strip()]
        self.v_sub    = tk.BooleanVar(value=bool(r.get("subfolders", False)))
        self.v_match  = tk.StringVar(value=r.get("match", ""))
        self.v_cmp    = tk.StringVar(value=r.get("compare", ""))
        self.v_retire = tk.StringVar(value=r.get("retire_dir", ""))
        self.v_newonly = tk.BooleanVar(value=bool(r.get("include_new", False)))
        self.v_dest   = tk.StringVar(value=r.get("dest", ""))
        self.v_action = tk.StringVar(value=("Copy" if r.get("action") == "copy"
                                            else "Move"))
        self.v_conf   = tk.StringVar(value=_CONFLICT_LABEL.get(
            r.get("conflict", "backup_old"), "Backup-rename old"))
        self.v_strip  = tk.BooleanVar(value=bool(r.get("strip_suffix", False)))
        self.v_age    = tk.StringVar(value=str(r.get("min_age_days", 0) or 0))
        self.v_maxage = tk.StringVar(value=str(r.get("max_age_days", 0) or 0))
        self.v_enable = tk.BooleanVar(value=bool(r.get("enabled", True)))

        # revAW — the editor can now outgrow the desktop (several source
        # folders, several excluded ones, and "newer" already asked for 920px
        # of a 1080px screen), so the fields SCROLL and the buttons live in a
        # fixed footer.  The footer is packed FIRST on purpose: pack starves
        # whoever is last in the packing ORDER, and a Save button that exists
        # but is never drawn is precisely the fault revAU had to fix in
        # Settings.  Same trap, so the same shape of answer.
        # pady is a plain number on a WIDGET — a (0, 12) tuple is legal on
        # pack() and a TclError here.
        self._footer = tk.Frame(self, bg=C_BG, padx=16)
        self._footer.pack(side="bottom", fill="x", pady=(0, 12))

        outer = tk.Frame(self, bg=C_BG)
        outer.pack(side="top", fill="both", expand=True)
        self._canvas = tk.Canvas(outer, bg=C_BG, highlightthickness=0)
        # A tk.Scrollbar, not ttk: on this dark background the themed one is
        # very nearly invisible.
        self._vsb = tk.Scrollbar(outer, orient="vertical",
                                 command=self._canvas.yview,
                                 bg=C_BG3, troughcolor=C_BG,
                                 activebackground=C_BG3,
                                 highlightthickness=0, bd=0)
        self._canvas.configure(yscrollcommand=self._vsb.set)
        # Scrollbar first, or the expanding canvas leaves it 1 px wide.
        self._vsb.pack(side="right", fill="y")
        self._canvas.pack(side="left", fill="both", expand=True)

        body = tk.Frame(self._canvas, bg=C_BG, padx=16, pady=12)
        self._body_frame = body
        self._body_id = self._canvas.create_window((0, 0), window=body,
                                                   anchor="nw")
        body.bind("<Configure>", lambda e: self._canvas.configure(
            scrollregion=self._canvas.bbox("all")))
        self._canvas.bind("<Configure>", lambda e: self._canvas.itemconfig(
            self._body_id, width=e.width))

        def _wheel(e):
            self._canvas.yview_scroll(-1 * (e.delta // 120), "units")
            return "break"

        self._wheel = _wheel
        self._canvas.bind("<MouseWheel>", _wheel)

        def label(txt, note=""):
            tk.Label(body, text=txt, bg=C_BG, fg=C_FG, anchor="w",
                     font=("Segoe UI", 9, "bold")).pack(fill="x", pady=(8, 0))
            if note:
                tk.Label(body, text=note, bg=C_BG, fg=C_FG_DIM, anchor="w",
                         font=("Segoe UI", 8), justify="left",
                         wraplength=560).pack(fill="x")

        def entry(var, width=64):
            e = tk.Entry(body, textvariable=var, width=width, bg=C_BG2, fg=C_FG,
                         insertbackground=C_FG,
                         insertofftime=0, insertontime=9999999)
            e.pack(fill="x", pady=(2, 0))
            return e

        def folder_row(var, note, parent=None):
            row = tk.Frame(parent or body, bg=C_BG)
            row.pack(fill="x", pady=(2, 0))
            e = tk.Entry(row, textvariable=var, bg=C_BG2, fg=C_FG,
                         insertbackground=C_FG,
                         insertofftime=0, insertontime=9999999)
            e.pack(side="left", fill="x", expand=True)
            tk.Button(row, text="…", width=3, bg="white", fg="black",
                      activebackground="white",
                      command=lambda v=var: self._browse(v)).pack(side="left", padx=(4, 0))
            tk.Button(row, text="◧ Left", width=6, bg=C_BG3, fg=C_FG,
                      activebackground=C_BG3, activeforeground=C_FG,
                      command=lambda v=var: v.set(
                          self.manager.left_panel.current_path)).pack(side="left", padx=2)
            tk.Button(row, text="◨ Right", width=7, bg=C_BG3, fg=C_FG,
                      activebackground=C_BG3, activeforeground=C_FG,
                      command=lambda v=var: v.set(
                          self.manager.right_panel.current_path)).pack(side="left")
            if note:
                tk.Label(parent or body, text=note, bg=C_BG, fg=C_FG_DIM,
                         anchor="w", font=("Segoe UI", 8), justify="left",
                         wraplength=560).pack(fill="x")
            return row

        def folder_list(parent, initial, add_text, empty_text,
                        keep_one: bool, panels: bool = True):
            """A growing list of folder rows, each with its own ✕.

            Returns a dict with a "get" callable — the rows come and go, so
            handing back the widgets would hand back something that stops
            existing the moment a row is removed.

            The rows are rebuilt from the list of StringVars rather than
            re-gridded in place.  With a handful of folders that is far easier
            to get right (every ✕ keeps pointing at its own row) and it only
            ever runs on a click, never on a timer — nothing here redraws by
            itself.
            """
            state = {"vars": [tk.StringVar(value=str(v))
                              for v in (initial or [])]}
            if keep_one and not state["vars"]:
                state["vars"].append(tk.StringVar(value=""))
            holder = tk.Frame(parent, bg=C_BG)
            holder.pack(fill="x")

            def redraw():
                for w in holder.winfo_children():
                    w.destroy()
                if not state["vars"]:
                    tk.Label(holder, text=empty_text, bg=C_BG, fg=C_FG_DIM,
                             anchor="w", font=("Segoe UI", 8),
                             justify="left", wraplength=560).pack(fill="x")
                for i, var in enumerate(state["vars"]):
                    row = tk.Frame(holder, bg=C_BG)
                    row.pack(fill="x", pady=1)
                    tk.Entry(row, textvariable=var, bg=C_BG2, fg=C_FG,
                             insertbackground=C_FG,
                             insertofftime=0, insertontime=9999999
                             ).pack(side="left", fill="x", expand=True)
                    tk.Button(row, text="…", width=3, bg="white", fg="black",
                              activebackground="white",
                              command=lambda v=var: self._browse(v)
                              ).pack(side="left", padx=(4, 0))
                    if panels:
                        tk.Button(row, text="◧", width=2, bg=C_BG3, fg=C_FG,
                                  activebackground=C_BG3, activeforeground=C_FG,
                                  command=lambda v=var: v.set(
                                      self.manager.left_panel.current_path)
                                  ).pack(side="left", padx=2)
                        tk.Button(row, text="◨", width=2, bg=C_BG3, fg=C_FG,
                                  activebackground=C_BG3, activeforeground=C_FG,
                                  command=lambda v=var: v.set(
                                      self.manager.right_panel.current_path)
                                  ).pack(side="left")
                    # The last row of a "must have one" list keeps its ✕ but
                    # only CLEARS it — a source list with no rows at all has no
                    # box to type the folder into, which is a dead end.
                    tk.Button(row, text="✕", width=2, bg=C_BG3, fg=C_FG_DIM,
                              activebackground=C_BG3, activeforeground=C_FG,
                              command=lambda n=i: _drop(n)
                              ).pack(side="left", padx=(4, 0))

            def _drop(n):
                if keep_one and len(state["vars"]) == 1:
                    state["vars"][0].set("")
                    return
                try:
                    state["vars"].pop(n)
                except IndexError:
                    return
                redraw()
                self._fit_height()

            def _add():
                state["vars"].append(tk.StringVar(value=""))
                redraw()
                self._fit_height()

            redraw()
            btn = tk.Frame(parent, bg=C_BG)
            btn.pack(fill="x", pady=(2, 0))
            tk.Button(btn, text=add_text, bg=C_BG3, fg=C_FG,
                      activebackground=C_BG3, activeforeground=C_FG,
                      command=_add).pack(side="left")
            return {"get": lambda: [v.get().strip()
                                    for v in state["vars"] if v.get().strip()]}

        label("Name")
        e_name = entry(self.v_name)

        label("What it picks up")
        kind_row = tk.Frame(body, bg=C_BG)
        kind_row.pack(fill="x", pady=(2, 0))
        for lbl, val in RELOCATOR_KINDS:
            tk.Radiobutton(kind_row, text=lbl, variable=self.v_kind, value=val,
                           bg=C_BG, fg=C_FG, selectcolor=C_BG2,
                           activebackground=C_BG, activeforeground=C_FG,
                           command=self._sync_kind).pack(anchor="w")

        label("From these folders",
              "Leave the only line blank and the rule works on whichever "
              "folder the ACTIVE panel is showing when you press ⤴.\n"
              "Add more and one rule covers them all, in the order listed — "
              "no need for four near-identical rules.  A file that turns up in "
              "two of them is moved once.")
        self._src_list = folder_list(
            body, self._src_init,
            "＋  another folder",
            "", keep_one=True)

        tk.Checkbutton(body, text="Look in sub-folders too", variable=self.v_sub,
                       bg=C_BG, fg=C_FG_DIM, activebackground=C_BG,
                       activeforeground=C_FG, selectcolor=C_BG2,
                       command=lambda: self._fit_height()).pack(anchor="w")

        label("…but never look in these",
              "Mostly for use with “Look in sub-folders too”.  The "
              "destination folder is skipped AUTOMATICALLY, so there is no "
              "need to list it here even when it lives INSIDE the folder you "
              "are tidying.\n"
              "A full path excludes that folder and everything under it.  A "
              "bare name (no \\ and no drive letter) excludes EVERY folder "
              "called that, at any depth — one line instead of twenty.")
        self._excl_list = folder_list(
            body, self._excl_init,
            "＋  a folder to skip",
            "Nothing is skipped — every sub-folder is looked at.",
            keep_one=False)

        self._lbl_match = tk.Label(body, text="Name pattern(s)", bg=C_BG, fg=C_FG,
                                   anchor="w", font=("Segoe UI", 9, "bold"))
        self._lbl_match.pack(fill="x", pady=(8, 0))
        self._note_match = tk.Label(
            body,
            text="Wildcards, several separated by ; or ,   —   e.g.  "
                 "Backup???-*   ·   Bildningspodden*.mp3   ·   *.tmp\n"
                 "Blank means every file in the folder.",
            bg=C_BG, fg=C_FG_DIM, anchor="w", font=("Segoe UI", 8),
            justify="left", wraplength=560)
        self._note_match.pack(fill="x")
        self._e_match = entry(self.v_match)

        # Everything only SOME kinds use lives in this one slot, so it always
        # appears in the same place and _sync_kind() only has to pack or
        # forget whole blocks.
        self._opt = tk.Frame(body, bg=C_BG)
        self._opt.pack(fill="x")

        # (a) "superseded" — the folder holding the newer copies
        self._cmp_box = tk.Frame(self._opt, bg=C_BG)
        tk.Label(self._cmp_box, text="…that a newer copy in THIS folder "
                                     "has replaced",
                 bg=C_BG, fg=C_FG, anchor="w",
                 font=("Segoe UI", 9, "bold")).pack(fill="x", pady=(8, 0))
        tk.Label(self._cmp_box,
                 text="Matched by name with any “ (3)” taken off, so the "
                      "browser's third save of the same program counts as the "
                      "same file.",
                 bg=C_BG, fg=C_FG_DIM, anchor="w", font=("Segoe UI", 8),
                 justify="left", wraplength=560).pack(fill="x")
        folder_row(self.v_cmp, "", parent=self._cmp_box)

        self._lbl_dest = tk.Label(body, text="To this folder", bg=C_BG, fg=C_FG,
                                  anchor="w", font=("Segoe UI", 9, "bold"))
        self._lbl_dest.pack(fill="x", pady=(8, 0))
        self._note_dest = tk.Label(body, text="Made if it is not there yet.",
                                   bg=C_BG, fg=C_FG_DIM, anchor="w",
                                   font=("Segoe UI", 8), justify="left",
                                   wraplength=560)
        self._note_dest.pack(fill="x")
        self._dest_row = folder_row(self.v_dest, "")

        # (b) "newer" — where the copy being replaced is retired to
        self._ret_box = tk.Frame(body, bg=C_BG)
        tk.Label(self._ret_box,
                 text="Retire the copy it replaces to THIS folder",
                 bg=C_BG, fg=C_FG, anchor="w",
                 font=("Segoe UI", 9, "bold")).pack(fill="x", pady=(8, 0))
        tk.Label(self._ret_box,
                 text="The file already over there is renamed Backup<code>- and "
                      "MOVED here BEFORE the new one lands — the only safe "
                      "order, and the only one that works on a program that is "
                      "running (Windows lets a busy .exe be renamed, never "
                      "overwritten).  Leave it blank to let the clash policy "
                      "below deal with the old copy instead.",
                 bg=C_BG, fg=C_FG_DIM, anchor="w", font=("Segoe UI", 8),
                 justify="left", wraplength=560).pack(fill="x")
        folder_row(self.v_retire, "", parent=self._ret_box)

        # This tick decides WHICH FILES ARE PICKED, so it does not belong under
        # a heading about where the replaced copy is retired to — that is where
        # it used to live, and it is why "F(re)email.exe matches nothing" looked
        # like a pattern problem: the first build of a program has no copy at
        # the destination to be newer than, so the rule skipped it silently.
        self._new_box = tk.Frame(body, bg=C_BG)
        tk.Label(self._new_box,
                 text="Files the destination does not have at all",
                 bg=C_BG, fg=C_FG, anchor="w",
                 font=("Segoe UI", 9, "bold")).pack(fill="x", pady=(8, 0))
        tk.Checkbutton(self._new_box,
                       text="Also send those",
                       variable=self.v_newonly, bg=C_BG, fg=C_FG,
                       activebackground=C_BG, activeforeground=C_FG,
                       selectcolor=C_BG2).pack(anchor="w")
        tk.Label(self._new_box,
                 text="Off: only files that already have an older copy over "
                      "there travel — so a program you built for the FIRST "
                      "time is skipped, however exactly its name is spelled.\n"
                      "On: a name the destination has never seen is sent too.  "
                      "That is what you want for a rule that keeps a folder of "
                      "programs up to date; leave it off when the destination "
                      "is deliberately a subset.",
                 bg=C_BG, fg=C_FG_DIM, anchor="w", font=("Segoe UI", 8),
                 justify="left", wraplength=560).pack(fill="x")

        label("Age", "Both are in days, and 0 means “any age”.  The second one "
                     "is what keeps a rule like  *.exe  from picking up every "
                     "build you ever made.")
        age_row = tk.Frame(body, bg=C_BG)
        age_row.pack(fill="x", pady=(2, 0))
        tk.Label(age_row, text="older than", bg=C_BG, fg=C_FG_DIM).pack(side="left")
        tk.Entry(age_row, textvariable=self.v_age, width=6, bg=C_BG2, fg=C_FG,
                 insertbackground=C_FG,
                 insertofftime=0, insertontime=9999999).pack(side="left", padx=(4, 12))
        tk.Label(age_row, text="and changed within the last",
                 bg=C_BG, fg=C_FG_DIM).pack(side="left")
        tk.Entry(age_row, textvariable=self.v_maxage, width=6, bg=C_BG2, fg=C_FG,
                 insertbackground=C_FG,
                 insertofftime=0, insertontime=9999999).pack(side="left", padx=(4, 0))
        tk.Label(age_row, text="days", bg=C_BG, fg=C_FG_DIM).pack(side="left",
                                                                  padx=(4, 0))

        opts = tk.Frame(body, bg=C_BG)
        opts.pack(fill="x", pady=(10, 0))
        tk.Label(opts, text="Then:", bg=C_BG, fg=C_FG,
                 font=("Segoe UI", 9, "bold")).pack(side="left")
        ttk.Combobox(opts, textvariable=self.v_action, width=6, state="readonly",
                     values=["Move", "Copy"]).pack(side="left", padx=6)
        tk.Label(opts, text="  on a name clash:", bg=C_BG, fg=C_FG_DIM).pack(side="left")
        ttk.Combobox(opts, textvariable=self.v_conf, width=18, state="readonly",
                     values=[lbl for lbl, mode in _CONFLICT_CHOICES
                             if mode != "ask"]).pack(side="left", padx=6)

        tk.Checkbutton(body,
                       text="Drop the “(2)” from the name on arrival "
                            "(Notes (3).py lands as Notes.py)",
                       variable=self.v_strip, bg=C_BG, fg=C_FG_DIM,
                       activebackground=C_BG, activeforeground=C_FG,
                       selectcolor=C_BG2).pack(anchor="w", pady=(8, 0))
        tk.Checkbutton(body, text="Rule is on", variable=self.v_enable,
                       bg=C_BG, fg=C_FG_DIM, activebackground=C_BG,
                       activeforeground=C_FG, selectcolor=C_BG2).pack(anchor="w")

        # In the FIXED footer, not in the scrolling body: the answer to
        # "🔎 Test it" is the one line you must be able to read without
        # hunting for it, and Save must never scroll away.
        self._test_lbl = tk.Label(self._footer, text="", bg=C_BG, fg=C_ACCENT,
                                  anchor="w", font=("Segoe UI", 9),
                                  justify="left", wraplength=560)
        self._test_lbl.pack(fill="x", pady=(10, 0))

        btns = tk.Frame(self._footer, bg=C_BG)
        btns.pack(fill="x", pady=(10, 0))
        tk.Button(btns, text="Cancel", bg="grey", fg="white", width=10,
                  activebackground="grey",
                  command=self.destroy).pack(side="right", padx=3)
        tk.Button(btns, text="Save", bg="lightgreen", fg="black", width=10,
                  activebackground="lightgreen",
                  command=self._save).pack(side="right", padx=3)
        tk.Button(btns, text="🔎  Test it", bg="lightblue", fg="black", width=11,
                  activebackground="lightblue",
                  command=self._test).pack(side="right", padx=3)

        self._sync_kind()
        self._fit_height()
        e_name.focus_set()

    # ── helpers ───────────────────────────────────────────────────────────
    def _wheel_everywhere(self, w=None):
        """Give the wheel to the fields too, not just the canvas background.

        Bound widget by widget rather than with bind_all, which would take the
        wheel away from the rest of the program.  Re-run after every add or
        remove, because those rows are built fresh and know nothing yet.
        """
        w = self._body_frame if w is None else w
        try:
            w.bind("<MouseWheel>", self._wheel)
        except Exception:
            pass
        for c in w.winfo_children():
            self._wheel_everywhere(c)

    def _fit_height(self):
        """As tall as the fields want, never taller than the desktop.

        Called after anything that changes the height — a folder row added or
        dropped, a different kind chosen — so the window keeps up instead of
        staying at whatever size it happened to open at.
        """
        if not getattr(self, "_body_frame", None):
            return
        try:
            self.update_idletasks()
            self._canvas.configure(scrollregion=self._canvas.bbox("all"))
            want = (self._body_frame.winfo_reqheight()
                    + self._footer.winfo_reqheight() + 4)
            room = max(360, self.winfo_screenheight() - 140)
            wide = max(self._body_frame.winfo_reqwidth()
                       + self._vsb.winfo_reqwidth(), self.winfo_reqwidth())
            self.geometry(f"{wide}x{min(want, room)}")
            self._wheel_everywhere()
        except Exception:
            pass

    def _browse(self, var: tk.StringVar):
        start = var.get() or getattr(self.manager.get_active_panel(),
                                     "current_path", "")
        path = filedialog.askdirectory(parent=self, initialdir=start or None,
                                       title="Choose a folder")
        if path:
            var.set(os.path.normpath(path))

    def _sync_kind(self):
        """Show only the fields the chosen kind actually uses."""
        kind = self.v_kind.get()
        for w in (self._cmp_box, self._ret_box, self._new_box):
            try:
                w.pack_forget()
            except Exception:
                pass
        if kind == "superseded":
            self._cmp_box.pack(fill="x")
            self._lbl_dest.configure(text="To this folder")
            self._note_dest.configure(text="Made if it is not there yet.")
            self._note_match.configure(
                text="Optional here — leave it blank to compare EVERY file in "
                     "the folder.  Wildcards, several separated by ; or ,")
        elif kind == "newer":
            # right under the destination it belongs to — pack order follows
            # the pack() calls, not the order the widgets were created in
            self._ret_box.pack(fill="x", after=self._dest_row)
            self._new_box.pack(fill="x", after=self._ret_box)
            self._lbl_dest.configure(
                text="Send them to THIS folder  (the one they are newer than)")
            self._note_dest.configure(
                text="Each file is compared with the one of the same name "
                     "here; only the newer ones travel.")
            self._note_match.configure(
                text="Which files to look at.  Wildcards, several separated by "
                     "; or ,   —   this is the easy place to add or drop a "
                     "program:\n"
                     "*.exe   ·   WhyBrowse.exe; File_manager.exe; Meditor.exe"
                     "\nBlank means every file in the folder.")
        else:
            self._lbl_dest.configure(text="To this folder")
            self._note_dest.configure(text="Made if it is not there yet.")
            self._note_match.configure(
                text="Wildcards, several separated by ; or ,   —   e.g.  "
                     "Backup???-*   ·   Bildningspodden*.mp3   ·   *.tmp\n"
                     "Blank means every file in the folder.")
        # Whole blocks appear and disappear here, so the window has to be
        # re-measured — otherwise picking "newer" leaves the fields it just
        # added below the bottom edge.
        self._fit_height()

    def _collect(self) -> dict:
        def _days(var):
            try:
                return float((var.get() or "0").replace(",", "."))
            except ValueError:
                return 0.0
        age = _days(self.v_age)
        srcs = self._src_list["get"]()
        return {
            "name":     self.v_name.get().strip() or "(unnamed rule)",
            "enabled":  bool(self.v_enable.get()),
            "kind":     self.v_kind.get(),
            # "source" is still written — a single folder is what every older
            # part of the program reads, and it keeps a rule saved here
            # readable by a File_manager from before revAW.
            "source":   (srcs[0] if srcs else ""),
            "sources":  srcs,
            "exclude":  self._excl_list["get"](),
            "subfolders": bool(self.v_sub.get()),
            "match":    self.v_match.get().strip(),
            "compare":  self.v_cmp.get().strip(),
            "retire_dir": self.v_retire.get().strip(),
            "include_new": bool(self.v_newonly.get()),
            "dest":     self.v_dest.get().strip(),
            "action":   "copy" if self.v_action.get() == "Copy" else "move",
            "conflict": dict(_CONFLICT_CHOICES).get(self.v_conf.get(),
                                                    "backup_old"),
            "strip_suffix": bool(self.v_strip.get()),
            "min_age_days": age,
            "max_age_days": _days(self.v_maxage),
        }

    def _test(self):
        rule = self._collect()
        active = getattr(self.manager.get_active_panel(), "current_path", "")
        self._test_lbl.configure(text="Looking…", fg=C_FG_DIM)

        def _worker():
            try:
                files = _relocator_scan(rule, active)
            except Exception as exc:
                files = []
                _log(f"Relocator test failed: {exc}")
            _ui_call(self, lambda: self._test_done(files))

        threading.Thread(target=_worker, daemon=True).start()

    def _test_done(self, files: list):
        if not self.winfo_exists():
            return
        if not files:
            self._test_lbl.configure(
                text="Nothing matches right now.", fg=C_FG_DIM)
            return
        names = ", ".join(os.path.basename(f) for f in files[:4])
        more  = f"  … and {len(files) - 4} more" if len(files) > 4 else ""
        self._test_lbl.configure(
            text=f"{len(files)} file(s):  {names}{more}", fg=C_ACCENT)

    def _save(self):
        rule = self._collect()
        if not rule["dest"]:
            messagebox.showwarning("Relocator rule",
                                   "The rule needs a destination folder.",
                                   parent=self)
            return
        # ── The destination can never be a source ───────────────────────
        #
        # Two different mistakes, and only one of them is a loop:
        #
        #   dest IS a source            — nothing could ever move; the run
        #                                 drops that folder and may end up with
        #                                 no sources at all.
        #   dest INSIDE a source        — NOT a mistake any more: _relocator_scan
        #                                 prunes the destination from the walk,
        #                                 so nothing delivered is re-collected.
        dest_n = _reloc_norm(rule["dest"])
        srcs = [s for s in (rule.get("sources") or []) if (s or "").strip()]
        same = [s for s in srcs if _reloc_norm(s) == dest_n]
        if same:
            messagebox.showwarning(
                "Relocator rule",
                "The destination is also a source folder:\n\n"
                f"    {same[0]}\n\n"
                "Nothing could ever move. Pick another destination, or take "
                "that folder out of the source list.",
                parent=self)
            return
        # dest INSIDE a source with "include sub-folders" on used to be refused
        # here.  It is fine now: the scan never walks into the destination.
        if rule["kind"] == "superseded" and not rule["compare"]:
            messagebox.showwarning(
                "Relocator rule",
                "This kind of rule needs the folder holding the NEWER copies.",
                parent=self)
            return
        rules = _load_relocator_rules()
        if self.edit_idx is not None and 0 <= self.edit_idx < len(rules):
            rules[self.edit_idx] = rule
        else:
            rules.append(rule)
        _save_relocator_rules(rules)
        try:
            self.parent.reload()
        except Exception:
            pass
        self.destroy()


class TwinRulesWindow(tk.Toplevel):
    """The remembered “always do this with the (2) copies” answers."""

    def __init__(self, manager: "EditorFrame"):
        super().__init__(manager)
        self.manager = manager
        self.configure(bg=C_BG)
        self.geometry("820x380")
        _setup_toplevel(self, "“(2) suffix” answers", manager, modal=False)
        head = tk.Frame(self, bg=C_BG3)
        head.pack(fill="x")
        tk.Label(head, text="“(2) suffix” answers", bg=C_BG3, fg=C_ACCENT,
                 font=("Segoe UI", 12, "bold")).pack(side="left", padx=10, pady=7)
        tk.Label(head, text="folder pairs where you ticked “always do this”",
                 bg=C_BG3, fg=C_FG_DIM, font=("Segoe UI", 9)).pack(side="left")
        # Close first, list second — pack() gives the expanding widget whatever
        # is left, so a button packed after it can end up with no room at all.
        bot = tk.Frame(self, bg=C_BG)
        bot.pack(side="bottom", fill="x", padx=10, pady=(0, 10))
        tk.Button(bot, text="Close", bg="grey", fg="white", width=9,
                  activebackground="grey",
                  command=self.destroy).pack(side="right")
        self._inner = tk.Frame(self, bg=C_BG)
        self._inner.pack(fill="both", expand=True, padx=10, pady=8)
        self._render()

    def _render(self):
        for w in self._inner.winfo_children():
            w.destroy()
        rules = _load_twin_rules()
        if not rules:
            tk.Label(self._inner,
                     text="Nothing remembered.\n\n"
                          "When a file arrives whose name differs from one "
                          "already there only by a “(2)”, the question that "
                          "pops up has an “Always do this” tick — that is what "
                          "writes a line here.",
                     bg=C_BG, fg=C_FG_DIM, font=("Segoe UI", 10),
                     justify="left", wraplength=740).pack(anchor="w", pady=16)
            return
        labels = {"backup_old": "Backup old, drop the (2)",
                  "overwrite":  "Replace old, drop the (2)",
                  "keep":       "Keep the (2) name"}
        for idx, r in enumerate(rules):
            row = tk.Frame(self._inner, bg=C_BG2, padx=8, pady=6)
            row.pack(fill="x", pady=3)
            left = tk.Frame(row, bg=C_BG2)
            left.pack(side="left", fill="x", expand=True)
            tk.Label(left, text=f"{r.get('src','(any)')}   →   {r.get('dst','(any)')}",
                     bg=C_BG2, fg=C_FG, font=("Segoe UI", 9, "bold"),
                     anchor="w", wraplength=600, justify="left").pack(anchor="w")
            tk.Label(left, text=labels.get(r.get("policy", ""), r.get("policy", "")),
                     bg=C_BG2, fg=C_FG_DIM, font=("Segoe UI", 8),
                     anchor="w").pack(anchor="w")
            tk.Button(row, text="🗑", bg="grey", fg="white", width=3,
                      activebackground="grey",
                      command=lambda i=idx: self._delete(i)).pack(side="right")

    def _delete(self, idx: int):
        rules = _load_twin_rules()
        if 0 <= idx < len(rules):
            del rules[idx]
            _save_twin_rules(rules)
            self._render()



# ══════════════════════════════════════════════════════════════════════════
#  DEL 53 — ISO / IMG image writer
# ══════════════════════════════════════════════════════════════════════════
#
# ASKED FOR: "Kan file manager skapa IMG/Iso-filer?  Det vore bra."
#
# Written from the spec rather than pulled in as a dependency, because there
# was nothing here to lean on: pycdlib is not installed, 7-Zip can READ an ISO
# but never write one, and neither oscdimg nor mkisofs is on the machine.  A
# file manager that can open images but not make them is half a tool.
#
# What it produces is a plain data image - the same bytes whether it is called
# .iso or .img, which is all "IMG" means for a data disc:
#
#   * 2048-byte sectors, the System Area left as 16 zero sectors
#   * a Primary Volume Descriptor with ISO 9660 (level 2) short names
#   * a Supplementary Volume Descriptor with JOLIET names - UCS-2, up to 64
#     characters, which is what keeps "Faktura Hakan 2017.rtf" intact
#   * L- and M-path tables for both, and directory records for both
#   * no El Torito boot record: this makes DATA images, not bootable ones
#
# Verified end to end, not assumed: an image built from a tree with Swedish
# characters, long names, four levels of nesting, an empty file and a 2 MB
# binary was extracted with 7-Zip and every file compared by SHA-256, and
# Windows itself mounted it (label TESTDISC, CDFS, every name intact).
#
# Limits, stated rather than discovered later: one extent per file, so a
# single file must be under 4 GB - anything larger is left out and reported;
# names are squeezed for the ISO tree only, the Joliet tree keeps them.
#
# THE ONE THAT COST AN HOUR: an EMPTY file takes no sectors at all.  Reserving
# one for it makes the volume size one sector larger than the bytes actually
# written, and every reader then reports "unexpected end of archive" on an
# otherwise perfect image.

SECTOR = 2048
MAX_EXTENT = 0xFFFFFFFF - SECTOR      # one-extent limit, ~4 GiB


# ── little helpers for the both-endian fields the format insists on ────────
def _both16(n: int) -> bytes:
    return struct.pack("<H", n) + struct.pack(">H", n)


def _both32(n: int) -> bytes:
    return struct.pack("<I", n) + struct.pack(">I", n)


def _sectors(n: int) -> int:
    return (n + SECTOR - 1) // SECTOR


def _dt_long(t: float) -> bytes:
    """The 17-byte 'digits' timestamp used in the volume descriptors."""
    lt = _time.localtime(t)
    off = -(_time.altzone if lt.tm_isdst else _time.timezone) // 900
    return ("%04d%02d%02d%02d%02d%02d00" % (lt.tm_year, lt.tm_mon, lt.tm_mday,
                                            lt.tm_hour, lt.tm_min,
                                            lt.tm_sec)).encode() + \
        struct.pack("b", off)


def _dt_short(t: float) -> bytes:
    """The 7-byte timestamp used in a directory record."""
    lt = _time.localtime(t)
    off = -(_time.altzone if lt.tm_isdst else _time.timezone) // 900
    return struct.pack("BBBBBBb", max(0, lt.tm_year - 1900), lt.tm_mon,
                       lt.tm_mday, lt.tm_hour, lt.tm_min, lt.tm_sec, off)


_DCHARS = set("ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_")


def _iso_name(name: str, is_dir: bool) -> str:
    """An ISO 9660 level-2 name: A-Z 0-9 _ only, 31 characters at most.

    Only the ISO tree is squeezed like this.  Every reader Windows ships with
    uses the Joliet tree instead, where the real name survives intact."""
    up = name.upper()
    if is_dir:
        out = "".join(c if c in _DCHARS else "_" for c in up)[:31]
        return out or "_"
    base, dot, ext = up.rpartition(".")
    if not dot:
        base, ext = up, ""
    base = "".join(c if c in _DCHARS else "_" for c in base)
    ext = "".join(c if c in _DCHARS else "_" for c in ext)[:3]
    base = base[:30 - len(ext)] or "_"
    return f"{base}.{ext};1" if ext else f"{base}.;1"


def _joliet_name(name: str, is_dir: bool) -> bytes:
    """UCS-2 big-endian, 64 characters at most (the Joliet ceiling)."""
    n = name[:64]
    if not is_dir:
        n = n[:64]
    return n.encode("utf-16-be")


class _Node:
    __slots__ = ("name", "path", "is_dir", "children", "size", "mtime",
                 "extent", "iso_name", "jol_name", "dir_len_iso",
                 "dir_len_jol", "number", "parent")

    def __init__(self, name, path, is_dir, parent=None):
        self.name = name
        self.path = path
        self.is_dir = is_dir
        self.parent = parent
        self.children: list = []
        self.size = 0
        self.mtime = _time.time()
        self.extent = 0
        self.number = 1
        self.iso_name = ""
        self.jol_name = b""
        self.dir_len_iso = 0
        self.dir_len_jol = 0


def _dir_record(name_bytes: bytes, extent: int, size: int, mtime: float,
                is_dir: bool, flags_extra: int = 0) -> bytes:
    """One directory record.  Padded to an even length, as the spec requires."""
    ln = 33 + len(name_bytes)
    pad = ln % 2
    rec = bytearray()
    rec.append(ln + pad)
    rec.append(0)                                   # extended attr length
    rec += _both32(extent)
    rec += _both32(size)
    rec += _dt_short(mtime)
    rec.append((0x02 if is_dir else 0x00) | flags_extra)
    rec.append(0)                                   # file unit size
    rec.append(0)                                   # interleave gap
    rec += _both16(1)                               # volume sequence number
    rec.append(len(name_bytes))
    rec += name_bytes
    if pad:
        rec.append(0)
    return bytes(rec)


class IsoBuilder:
    """Collect a tree, then write it.  Progress is reported per file."""

    def __init__(self, volume_label: str = "DATA"):
        self.label = "".join(c for c in volume_label.upper()
                             if c in _DCHARS or c == " ")[:32] or "DATA"
        self.root = _Node("", "", True)
        self.warnings: list = []

    # ── building the tree ────────────────────────────────────────────────
    def add(self, src_path: str, arc_name: str = None):
        """Add a file or a whole folder at the image's top level."""
        src_path = os.path.abspath(src_path)
        name = arc_name or os.path.basename(src_path.rstrip("\\/"))
        if os.path.isdir(src_path):
            self._add_dir(src_path, name, self.root)
        else:
            self._add_file(src_path, name, self.root)

    def _add_dir(self, path, name, parent):
        node = _Node(name, path, True, parent)
        try:
            node.mtime = os.path.getmtime(path)
        except OSError:
            pass
        parent.children.append(node)
        try:
            entries = sorted(os.listdir(path), key=str.upper)
        except OSError as exc:
            self.warnings.append(f"{path}: {exc}")
            return
        for e in entries:
            p = os.path.join(path, e)
            try:
                if os.path.isdir(p) and not os.path.islink(p):
                    self._add_dir(p, e, node)
                elif os.path.isfile(p):
                    self._add_file(p, e, node)
            except OSError as exc:
                self.warnings.append(f"{p}: {exc}")

    def _add_file(self, path, name, parent):
        node = _Node(name, path, False, parent)
        try:
            st = os.stat(path)
            node.size = st.st_size
            node.mtime = st.st_mtime
        except OSError as exc:
            self.warnings.append(f"{path}: {exc}")
            return
        if node.size > MAX_EXTENT:
            self.warnings.append(
                f"{path}: {node.size / 2**30:.1f} GB is too big for one ISO "
                f"extent (4 GB limit) — left out")
            return
        parent.children.append(node)

    # ── counting what is there ───────────────────────────────────────────
    def totals(self):
        files = data = dirs = 0
        stack = [self.root]
        while stack:
            n = stack.pop()
            for c in n.children:
                if c.is_dir:
                    dirs += 1
                    stack.append(c)
                else:
                    files += 1
                    data += c.size
        return files, dirs, data

    # ── the write itself ─────────────────────────────────────────────────
    def write(self, out_path: str, progress=None, is_cancelled=None) -> bool:
        """Write the image.  progress(done_bytes, total_bytes, name) is called
        per file; is_cancelled() stops and removes the half-written file."""
        dirs_iso = self._layout()
        total_files, _n_dirs, total_bytes = self.totals()
        done = 0
        try:
            with open(out_path, "wb") as fh:
                fh.write(b"\0" * (16 * SECTOR))          # system area
                fh.write(self._pvd())
                fh.write(self._svd())
                fh.write(self._terminator())
                # path tables and directory extents, in the order _layout laid
                # them out — the offsets in the descriptors depend on it.
                fh.write(self._pad(self._path_table(False, False)))
                fh.write(self._pad(self._path_table(True, False)))
                fh.write(self._pad(self._path_table(False, True)))
                fh.write(self._pad(self._path_table(True, True)))
                for node in dirs_iso:
                    fh.write(self._pad(self._dir_extent(node, joliet=False)))
                for node in dirs_iso:
                    fh.write(self._pad(self._dir_extent(node, joliet=True)))
                for node in self._files():
                    if is_cancelled and is_cancelled():
                        raise KeyboardInterrupt
                    if progress:
                        progress(done, total_bytes, node.name)
                    written = 0
                    with open(node.path, "rb") as src:
                        while True:
                            buf = src.read(1 << 20)
                            if not buf:
                                break
                            fh.write(buf)
                            written += len(buf)
                            done += len(buf)
                            if progress:
                                progress(done, total_bytes, node.name)
                            if is_cancelled and is_cancelled():
                                raise KeyboardInterrupt
                    if written != node.size:
                        # The file changed under us; keep the extent the size
                        # the descriptors promise or the image is corrupt.
                        if written < node.size:
                            fh.write(b"\0" * (node.size - written))
                        self.warnings.append(
                            f"{node.path}: changed size while being written")
                    pad = (-node.size) % SECTOR
                    if pad:
                        fh.write(b"\0" * pad)
            return True
        except KeyboardInterrupt:
            try:
                os.remove(out_path)
            except OSError:
                pass
            return False

    # ── internals ────────────────────────────────────────────────────────
    def _pad(self, data: bytes) -> bytes:
        pad = (-len(data)) % SECTOR
        return data + b"\0" * pad if pad else data

    def _dirs(self) -> list:
        """Every directory, breadth-first — the order the path table needs."""
        out = [self.root]
        i = 0
        while i < len(out):
            for c in out[i].children:
                if c.is_dir:
                    out.append(c)
            i += 1
        return out

    def _files(self) -> list:
        out = []
        for d in self._dirs():
            for c in d.children:
                if not c.is_dir:
                    out.append(c)
        return out

    def _layout(self):
        """Work out every extent number.  Everything downstream reads these."""
        dirs = self._dirs()
        for i, d in enumerate(dirs):
            d.number = i + 1
            for c in d.children:
                c.iso_name = _iso_name(c.name, c.is_dir)
                c.jol_name = _joliet_name(c.name, c.is_dir)
            d.iso_name = _iso_name(d.name, True) if d.parent else ""
            d.jol_name = _joliet_name(d.name, True) if d.parent else b""

        # names must be unique within a directory once squeezed to ISO form
        for d in dirs:
            seen = {}
            for c in d.children:
                key = c.iso_name.upper()
                if key in seen:
                    seen[key] += 1
                    stem, semi, _ = c.iso_name.partition(";")
                    base, dot, ext = stem.rpartition(".")
                    tag = f"~{seen[key]}"
                    if dot:
                        base = base[:max(1, 30 - len(ext) - len(tag))] + tag
                        c.iso_name = f"{base}.{ext}" + (";1" if semi else "")
                    else:
                        c.iso_name = (stem[:31 - len(tag)] + tag) + (";1" if semi else "")
                else:
                    seen[key] = 0

        # sizes of the directory extents
        for d in dirs:
            for joliet in (False, True):
                size = len(_dir_record(b"\0", 0, 0, d.mtime, True)) + \
                    len(_dir_record(b"\x01", 0, 0, d.mtime, True))
                for c in sorted(d.children,
                                key=lambda x: (not x.is_dir, x.name.upper())):
                    nb = c.jol_name if joliet else c.iso_name.encode("ascii")
                    size += len(_dir_record(nb, 0, 0, c.mtime, c.is_dir))
                if joliet:
                    d.dir_len_jol = size
                else:
                    d.dir_len_iso = size

        pt_l = len(self._path_table_bytes(False, False))
        pt_j = len(self._path_table_bytes(False, True))
        self._pt_size_iso = pt_l
        self._pt_size_jol = pt_j

        lba = 16 + 3                                   # descriptors
        self._pt_iso_l, lba = lba, lba + _sectors(pt_l)
        self._pt_iso_m, lba = lba, lba + _sectors(pt_l)
        self._pt_jol_l, lba = lba, lba + _sectors(pt_j)
        self._pt_jol_m, lba = lba, lba + _sectors(pt_j)
        for d in dirs:
            d.extent = lba
            lba += _sectors(d.dir_len_iso)
        self._jol_extent = {}
        for d in dirs:
            self._jol_extent[id(d)] = lba
            lba += _sectors(d.dir_len_jol)
        for f in self._files():
            f.extent = lba
            # An EMPTY file takes no sectors at all.  Reserving one for it (the
            # obvious-looking "or 1") makes the volume size one sector larger
            # than the bytes actually written, and every reader then reports
            # "unexpected end of archive" on an otherwise perfect image.
            lba += _sectors(f.size)
        self._total_sectors = lba
        return dirs

    def _path_table_bytes(self, big: bool, joliet: bool) -> bytes:
        out = bytearray()
        for d in self._dirs():
            name = (d.jol_name if joliet else d.iso_name.encode("ascii")) \
                if d.parent else b"\0"
            ext = (self._jol_extent[id(d)] if joliet else d.extent) \
                if hasattr(self, "_jol_extent") or not joliet else 0
            parent_no = d.parent.number if d.parent else 1
            out.append(len(name))
            out.append(0)
            out += struct.pack(">I" if big else "<I", ext)
            out += struct.pack(">H" if big else "<H", parent_no)
            out += name
            if len(name) % 2:
                out.append(0)
        return bytes(out)

    def _path_table(self, big: bool, joliet: bool) -> bytes:
        return self._path_table_bytes(big, joliet)

    def _dir_extent(self, node: _Node, joliet: bool) -> bytes:
        ext = self._jol_extent[id(node)] if joliet else node.extent
        size = node.dir_len_jol if joliet else node.dir_len_iso
        parent = node.parent or node
        pext = (self._jol_extent[id(parent)] if joliet else parent.extent)
        psize = parent.dir_len_jol if joliet else parent.dir_len_iso
        out = bytearray()
        out += _dir_record(b"\0", ext, size, node.mtime, True)
        out += _dir_record(b"\x01", pext, psize, parent.mtime, True)
        for c in sorted(node.children,
                        key=lambda x: (not x.is_dir, x.name.upper())):
            nb = c.jol_name if joliet else c.iso_name.encode("ascii")
            if c.is_dir:
                cext = self._jol_extent[id(c)] if joliet else c.extent
                csize = c.dir_len_jol if joliet else c.dir_len_iso
            else:
                cext, csize = c.extent, c.size
            out += _dir_record(nb, cext, csize, c.mtime, c.is_dir)
        return bytes(out)

    def _vol_descriptor(self, kind: int, joliet: bool) -> bytes:
        d = bytearray(b"\0" * SECTOR)
        d[0] = kind
        d[1:6] = b"CD001"
        d[6] = 1
        enc = (lambda s, n: s.encode("utf-16-be")[:n].ljust(n, b"\0")) if joliet \
            else (lambda s, n: s.encode("ascii", "replace")[:n].ljust(n, b" "))
        d[8:40] = enc("", 32)                              # system identifier
        d[40:72] = enc(self.label, 32)                     # volume identifier
        d[80:88] = _both32(self._total_sectors)
        if joliet:
            d[88:120] = b"%/E".ljust(32, b"\0")            # Joliet escape
        d[120:124] = _both16(1)                            # volume set size
        d[124:128] = _both16(1)                            # sequence number
        d[128:132] = _both16(SECTOR)
        pt_size = self._pt_size_jol if joliet else self._pt_size_iso
        d[132:140] = _both32(pt_size)
        d[140:144] = struct.pack("<I", self._pt_jol_l if joliet else self._pt_iso_l)
        d[144:148] = struct.pack("<I", 0)                  # optional L table
        d[148:152] = struct.pack(">I", self._pt_jol_m if joliet else self._pt_iso_m)
        d[152:156] = struct.pack(">I", 0)                  # optional M table
        root = self.root
        rext = self._jol_extent[id(root)] if joliet else root.extent
        rsize = root.dir_len_jol if joliet else root.dir_len_iso
        d[156:190] = _dir_record(b"\0", rext, rsize, root.mtime, True)
        for a, b, txt in ((190, 318, ""), (318, 446, "FILE MANAGER"),
                          (446, 574, ""), (574, 702, ""), (702, 739, ""),
                          (739, 776, ""), (776, 813, "")):
            d[a:b] = enc(txt, b - a)
        now = _time.time()
        d[813:830] = _dt_long(now)                         # creation
        d[830:847] = _dt_long(now)                         # modification
        d[847:864] = b"0" * 16 + b"\0"                     # expiration: none
        d[864:881] = _dt_long(now)                         # effective
        d[881] = 1                                         # file structure ver
        return bytes(d)

    def _pvd(self) -> bytes:
        return self._vol_descriptor(1, joliet=False)

    def _svd(self) -> bytes:
        return self._vol_descriptor(2, joliet=True)

    def _terminator(self) -> bytes:
        d = bytearray(b"\0" * SECTOR)
        d[0] = 0xFF
        d[1:6] = b"CD001"
        d[6] = 1
        return bytes(d)

# ══════════════════════════════════════════════════════════════════════════
#  DEL 52 — Connect to a PC  /  Share this PC  (one account, no typing)
# ══════════════════════════════════════════════════════════════════════════
#
# Two halves of the same idea (asked for 2026-11-21: "både dela ut och komma in"):
#
#   SHARE OUT  (NET ▾ → "📤 Share this PC's drives …", run on the PC whose drives
#   others should reach, e.g. FILM).  One Administrator step (a Windows question,
#   answered Yes once) makes ONE hidden local account ("pcshare") with a random
#   password, shares the ticked fixed drives as Drive_<letter> for that account
#   (the system drive read-only), turns on the Private network profile, the
#   File-and-Printer-Sharing + Network-Discovery firewall groups and the sharing
#   services - and writes  Helpfiles\redigerare\Share_out\PC_connect.json  (computer
#   name, IP addresses, account, password, share list).  Run again any time: the
#   same account + password are kept, only missing things are repaired.
#
#   GET IN  (NET ▾ → "🔌 Connect to a PC …", or just drop PC_connect*.json into
#   Helpfiles\redigerare\ - it is picked up at the next start).  The sign-in goes
#   into Windows (cmdkey, so Explorer stops asking too) and into net_logins.json
#   (so it comes back by itself after a Windows reinstall), every share becomes a
#   network favourite with its own drive letter, and the drives are connected.
#   At every start the saved favourites of such PCs are reconnected if their
#   letter is not there.
#
# The connection file holds the password (base64 is NOT encryption): copy it only
# by USB between your own PCs.
# ToDo: a "Revoke" button (remove the account + the shares again) is not built.

PC_CONNECT_DONE = HELP_DIR / "pc_connect_done.json"   # {file name: sha1} already imported
PC_SHARE_OUT    = HELP_DIR / "Share_out"              # where "Share this PC" writes its file
PC_ACCOUNT_DEFAULT = "pcshare"


def _pcc_read(path) -> dict:
    """Read + check a PC_connect.json.  Raises ValueError with a plain message."""
    try:
        data = json.loads(Path(path).read_text(encoding="utf-8-sig"))
    except Exception as exc:
        raise ValueError(f"Could not read the file: {exc}")
    if not isinstance(data, dict):
        raise ValueError("This is not a connection file.")
    comp = str(data.get("computer", "")).strip()
    user = str(data.get("user", "")).strip()
    try:
        pw = base64.b64decode(str(data.get("password_b64", ""))).decode("utf-8")
    except Exception:
        pw = ""
    shares = [s for s in (data.get("shares") or [])
              if isinstance(s, dict) and s.get("share")]
    if not (comp and user and pw and shares):
        raise ValueError("This connection file is incomplete: it needs the computer, "
                         "the user, the password and at least one share.")
    ips = [str(i).strip() for i in (data.get("ips") or []) if str(i).strip()]
    return {"computer": comp, "ips": ips, "user": user, "password": pw,
            "shares": shares}


def _pcc_mapped_shares(hosts) -> dict:
    """Drive letters that already point at a share of one of *hosts* (the PC's name
    or an IP address): {share name in lower case: 'Z:'}.  So a drive that was
    mapped before - by hand, or by the old PC_Drives.bat - keeps its letter."""
    out = {}
    try:
        text = _net_run_sys("net.exe", ["use"], 15).stdout
    except Exception:
        return out
    want = {str(h).strip().lower() for h in hosts if str(h).strip()}
    for m in _re.finditer(r"(?im)\b([A-Z]:)\s+\\\\([^\s\\]+)\\(\S+)", text):
        if m.group(2).lower() in want:
            out.setdefault(m.group(3).lower(), m.group(1).upper())
    return out


def _pcc_import(path, keep: bool = True) -> tuple:
    """GET IN: sign in, save the sign-in, make favourites, connect the drives.
    Talks to the network - call it from a thread.  Returns (ok, message)."""
    info = _pcc_read(path)                       # may raise ValueError
    comp, user, pw = info["computer"], info["user"], info["password"]

    names = [comp] + [i for i in info["ips"] if i.lower() != comp.lower()]
    reachable = [n for n in names if _net_port_open(n, 445, 2.0)]
    if not reachable:
        return False, (f"{comp} does not answer on the network.\n\nIs it switched on, "
                       "and on the same network as this PC?")

    # 1. Sign in (proves the login works).  'NAME\user' first, then the bare name.
    first = reachable[0]
    cands = [user] if ("\\" in user or "@" in user) else [f"{comp}\\{user}", user]
    already = _pcc_mapped_shares(names)          # letters PC_Drives.bat (or you) already gave
    used, last = "", ""
    for u in cands:
        ok, text = _net_sign_in(first, u, pw, remember=True)
        if ok:
            used = u
            break
        last = text
    if not used:
        return False, (f"{comp} refused the saved login.\n\n{last}\n\nRun "
                       "'Share this PC's drives' on that PC again and bring the new "
                       "connection file here.")

    # 2. The same sign-in for the computer name AND every IP address (Windows
    #    matches by the name you type), saved so it comes back after a reinstall.
    logins = _net_logins_load()
    for n in names:
        logins[_net_host_key(n)] = {"host": n, "user": used,
                                    "_pw": _net_encode_pw(pw)}
        if n != first:
            _net_apply_login(n, used, pw, session=False)
    _net_logins_save(logins)

    # 3. Favourites: one per share, each with its own free drive letter.
    host = comp if comp in reachable else first
    favs = _net_load_favorites()
    known = {f.get("path", "").lower().rstrip("\\"): f for f in favs}
    taken = {l.rstrip(":").upper() for l in _get_mapped_letters()}
    taken |= {f.get("letter", "").rstrip(":").upper() for f in favs}
    free = [c for c in "ZYXWVUTSRQPONMLKJIHGFED" if c not in taken]
    mine, added = [], 0
    for s in info["shares"]:
        unc = f"\\\\{host}\\{s['share']}"
        fav = known.get(unc.lower())
        if fav is None:
            label = str(s.get("label", "")).strip()
            drive = str(s.get("drive", "")).strip()
            keep_letter = already.get(str(s["share"]).lower(), "")
            if keep_letter:                      # same share, same letter as before
                free = [c for c in free if f"{c}:" != keep_letter]
            fav = {"name": " ".join(x for x in (comp, drive, label) if x),
                   "letter": keep_letter or (f"{free.pop(0)}:" if free else ""),
                   "path": unc, "user": "", "_pw": ""}
            favs.append(fav)
            added += 1
        mine.append(fav)
    _net_save_favorites(favs)

    # 4. Connect them now (one after the other; the IPC$ session is already open).
    lines, good = [], 0
    for fav in mine:
        letter, unc = fav.get("letter", ""), fav.get("path", "")
        if not letter:
            lines.append(f"   {unc}   (no free drive letter - open it from Network locations)")
            continue
        try:
            _net_run_sys("net.exe", ["use", letter, "/delete", "/y"], 15)
            r = _net_run_sys("net.exe", ["use", letter, unc, "/persistent:yes"], 45)
            if r.returncode == 0:
                good += 1
                lines.append(f"   {letter}   {unc}")
            else:
                out = (r.stdout + r.stderr).strip().splitlines()
                lines.append(f"   {letter}   {unc}   FAILED: {out[0] if out else ''}")
        except Exception as exc:
            lines.append(f"   {letter}   {unc}   FAILED: {exc}")
    _log(f"Connect to a PC: {comp}: {good}/{len(mine)} drives connected, {added} new favourite(s)")

    if keep:                                    # keep a copy next to the other settings
        try:
            dst = HELP_DIR / f"PC_connect_{comp}.json"
            if Path(path).resolve() != dst.resolve():
                shutil.copy2(path, dst)
            done = {}
            if PC_CONNECT_DONE.exists():
                done = json.loads(PC_CONNECT_DONE.read_text(encoding="utf-8"))
            done[dst.name] = hashlib.sha1(dst.read_bytes()).hexdigest()
            PC_CONNECT_DONE.write_text(json.dumps(done, indent=2), encoding="utf-8")
        except Exception as exc:
            _log(f"Could not keep the connection file: {exc}")

    head = (f"Signed in to {comp} as {used}.\n{good} of {len(mine)} drive(s) connected"
            f"{f', {added} new favourite(s) saved' if added else ''}:\n\n")
    tail = ("\n\nThe sign-in is saved: the drives come back by themselves at every "
            "start of File manager, also after Windows is reinstalled.")
    return good > 0, head + "\n".join(lines) + tail


def _pcc_reconnect_known():
    """At start: favourites that belong to a PC with a saved sign-in are connected
    again when their drive letter is not there (a fresh Windows has none)."""
    try:
        logins = _net_logins_load()
        if not logins:
            return
        used = {l.rstrip(":").upper() for l in _get_mapped_letters()}
        for fav in _net_load_favorites():
            letter = fav.get("letter", "").strip()
            host = _net_host_key(_net_host_of_unc(fav.get("path", "")))
            if letter and host in logins and letter.rstrip(":").upper() not in used:
                if _net_port_open(logins[host].get("host", host), 445, 1.5):
                    _net_restore_login(logins[host].get("host", host))
                    _net_connect_favorite(fav)
    except Exception as exc:
        _log(f"Reconnecting saved network drives failed: {exc}")


def _pcc_autoimport():
    """At start: every PC_connect*.json dropped into Helpfiles\\redigerare is imported
    once (this PC's own file is skipped), then the saved drives are reconnected."""
    try:
        try:
            done = json.loads(PC_CONNECT_DONE.read_text(encoding="utf-8")) \
                if PC_CONNECT_DONE.exists() else {}
        except Exception:
            done = {}
        me = socket.gethostname().upper()
        # Helpfiles\redigerare, and also the folder this program sits in (where the
        # old PC_connect.json lay): it is copied into Helpfiles after the import.
        found, seen = [], set()
        for folder in (HELP_DIR, Path(_own_dir())):
            try:
                for f in sorted(folder.glob("PC_connect*.json")):
                    if str(f.resolve()).lower() not in seen:
                        seen.add(str(f.resolve()).lower())
                        found.append(f)
            except Exception:
                pass
        for f in found:
            try:
                digest = hashlib.sha1(f.read_bytes()).hexdigest()
                if done.get(f.name) == digest:
                    continue
                info = _pcc_read(f)
                if info["computer"].upper() == me:
                    continue
                ok, text = _pcc_import(f, keep=True)
                _log(f"Auto-import of {f.name}: {'OK' if ok else 'failed'}")
                if ok:      # remember the ORIGINAL name too, or it is redone every start
                    try:
                        done = json.loads(PC_CONNECT_DONE.read_text(encoding="utf-8"))
                    except Exception:
                        done = {}
                    done[f.name] = digest
                    PC_CONNECT_DONE.write_text(json.dumps(done, indent=2),
                                               encoding="utf-8")
            except Exception as exc:
                _log(f"Auto-import of {f.name} failed: {exc}")
    except Exception as exc:
        _log(f"Auto-import of connection files failed: {exc}")
    try:                                    # DEL 52b: files other PCs put on the server
        _pcr_fetch_all()
    except Exception as exc:
        _log(f"Fetching connection files from the server failed: {exc}")
    _pcc_reconnect_known()


def _pcc_local_drives() -> list:
    """Fixed local drives: [{'letter','label','size_gb','system'}].  Google Drive's
    virtual drives are left out - they must never be shared."""
    out = []
    try:
        bits = ctypes.windll.kernel32.GetLogicalDrives()
    except Exception:
        return out
    sysd = os.environ.get("SystemDrive", "C:").upper()
    for i, ch in enumerate(_string.ascii_uppercase):
        if not bits & (1 << i):
            continue
        root = f"{ch}:\\"
        try:
            if ctypes.windll.kernel32.GetDriveTypeW(root) != 3:      # 3 = fixed disk
                continue
            buf = ctypes.create_unicode_buffer(261)
            ctypes.windll.kernel32.GetVolumeInformationW(root, buf, 260, None,
                                                         None, None, None, 0)
            label = buf.value
        except Exception:
            label = ""
        low = label.lower()
        # Google Drive's virtual drives are labelled "name@gmail.com - Goo…" (cut off)
        if "google" in low or " - goo" in low or "@" in low:
            continue
        try:
            size_gb = round(shutil.disk_usage(root).total / 1e9)
        except Exception:
            size_gb = 0
        out.append({"letter": ch, "label": label, "size_gb": size_gb,
                    "system": f"{ch}:" == sysd})
    return out


# The PowerShell that runs ELEVATED.  Placeholders are replaced by Python; the
# password only lives in this temporary file, which deletes itself at the end.
_PCC_PS_TEMPLATE = r"""
$ErrorActionPreference = 'Stop'
$ProgressPreference = 'SilentlyContinue'
$account = '@@ACCOUNT@@'
$pwtext  = '@@PASSWORD@@'
$outFile = '@@OUT@@'
$fullControl = @@FULL@@
$script:steps  = @()
$script:shares = @()
$script:accOk  = $false

function Step([string]$title, [scriptblock]$sb) {
    try { & $sb; $script:steps += ,@{ title = $title; ok = $true; msg = '' } }
    catch { $script:steps += ,@{ title = $title; ok = $false; msg = [string]$_.Exception.Message } }
}

Step 'Network profile set to Private' {
    Get-NetConnectionProfile | Where-Object { $_.NetworkCategory -ne 'Private' } | Set-NetConnectionProfile -NetworkCategory Private
}
Step 'Firewall: File and Printer Sharing + Network Discovery on' {
    Enable-NetFirewallRule -Group '@FirewallAPI.dll,-28502'
    Enable-NetFirewallRule -Group '@FirewallAPI.dll,-32752'
}
Step 'Sharing services start automatically' {
    foreach ($n in 'LanmanServer','LanmanWorkstation','fdPHost','FDResPub','SSDPSRV') {
        try { Set-Service -Name $n -StartupType Automatic; if ((Get-Service $n).Status -ne 'Running') { Start-Service $n } } catch { }
    }
    if ((Get-Service LanmanServer).Status -ne 'Running') { throw 'The Server service would not start' }
}
Step ('Account ' + $account + ' ready (hidden from the sign-in screen)') {
    $pw = ConvertTo-SecureString $pwtext -AsPlainText -Force
    $u = Get-LocalUser -Name $account -ErrorAction SilentlyContinue
    if ($u) { Set-LocalUser -Name $account -Password $pw -PasswordNeverExpires $true; Enable-LocalUser -Name $account }
    else { New-LocalUser -Name $account -Password $pw -PasswordNeverExpires -UserMayNotChangePassword -AccountNeverExpires -Description 'Network access to shared drives' | Out-Null }
    Add-LocalGroupMember -SID 'S-1-5-32-545' -Member $account -ErrorAction SilentlyContinue
    $k = 'HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon\SpecialAccounts\UserList'
    if (-not (Test-Path $k)) { New-Item $k -Force | Out-Null }
    New-ItemProperty -Path $k -Name $account -Value 0 -PropertyType DWord -Force | Out-Null
    $script:accOk = $true
}
if ($script:accOk) {
    if ($fullControl) {
        Step 'Full control: the account may change/delete ANY file on the shared drives' {
            Add-LocalGroupMember -SID 'S-1-5-32-544' -Member $account -ErrorAction SilentlyContinue
            $pk = 'HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System'
            New-ItemProperty -Path $pk -Name 'LocalAccountTokenFilterPolicy' -Value 1 -PropertyType DWord -Force | Out-Null
        }
    } else {
        Step 'Limited rights: the account is NOT an Administrator' {
            Remove-LocalGroupMember -SID 'S-1-5-32-544' -Member $account -ErrorAction SilentlyContinue
        }
    }
}
if ($script:accOk) {
    foreach ($d in @(@@DRIVES@@)) {
        $p = $d.Split('|'); $L = $p[0]; $mode = $p[1]; $name = 'Drive_' + $L
        Step ('Share ' + $name) {
            if (Get-SmbShare -Name $name -ErrorAction SilentlyContinue) { Remove-SmbShare -Name $name -Force }
            if ($mode -eq 'read') { New-SmbShare -Name $name -Path ($L + ':\') -ReadAccess $account -Description 'Shared by File manager' | Out-Null }
            else { New-SmbShare -Name $name -Path ($L + ':\') -FullAccess $account -Description 'Shared by File manager' | Out-Null }
            $script:shares += ,@{ share = $name; drive = ($L + ':'); mode = $mode }
        }
    }
}
$res = @{ steps = $script:steps; shares = $script:shares; listening = $false }
try { $c = New-Object Net.Sockets.TcpClient; $c.Connect('127.0.0.1', 445); $res.listening = $true; $c.Close() } catch { }
$json = ConvertTo-Json -InputObject $res -Depth 6
[IO.File]::WriteAllText($outFile, $json, (New-Object Text.UTF8Encoding($false)))
Remove-Item -LiteralPath $PSCommandPath -Force -ErrorAction SilentlyContinue
"""


def _pcc_new_password(n: int = 16) -> str:
    import secrets
    alphabet = _string.ascii_letters + _string.digits
    while True:
        pw = "".join(secrets.choice(alphabet) for _ in range(n))
        if (any(c.islower() for c in pw) and any(c.isupper() for c in pw)
                and any(c.isdigit() for c in pw)):
            return pw


def _pcc_share_run(drives: list, account: str, full_control: bool = True) -> tuple:
    """SHARE OUT: run the elevated PowerShell and write PC_connect.json.
    *full_control*: the account becomes an Administrator on this PC and every
    drive (the system drive too) is shared with full access - needed to change or
    delete files owned by other accounts (2026-11-21: "kunde inte radera en stor
    fil på FILMs C:").  Off = plain user, system drive read-only.
    Talks to Windows - call it from a thread.  Returns (ok, text, file_path)."""
    comp = socket.gethostname().upper()
    PC_SHARE_OUT.mkdir(parents=True, exist_ok=True)
    conn = PC_SHARE_OUT / "PC_connect.json"
    password = ""
    try:
        old = json.loads(conn.read_text(encoding="utf-8-sig"))
        if old.get("user") == account and old.get("password_b64"):
            password = base64.b64decode(old["password_b64"]).decode("utf-8")
    except Exception:
        pass
    password = password or _pcc_new_password()

    tmpdir = Path(tempfile.mkdtemp(prefix="fm_share_"))
    script, result = tmpdir / "share_this_pc.ps1", tmpdir / "result.json"
    items = ",".join(
        f"'{d['letter']}|{'read' if (d['system'] and not full_control) else 'full'}'"
        for d in drives)
    body = (_PCC_PS_TEMPLATE.replace("@@ACCOUNT@@", account)
            .replace("@@FULL@@", "$true" if full_control else "$false")
            .replace("@@PASSWORD@@", password)
            .replace("@@OUT@@", str(result).replace("'", "''"))
            .replace("@@DRIVES@@", items))
    script.write_text(body, encoding="utf-8-sig")
    ps = os.path.join(_NET_SYS32, "WindowsPowerShell", "v1.0", "powershell.exe")
    arg = f'-NoProfile -ExecutionPolicy Bypass -File "{script}"'
    cmd = ("Start-Process -FilePath '" + ps.replace("'", "''") + "' -ArgumentList '"
           + arg.replace("'", "''") + "' -Verb RunAs -Wait -WindowStyle Hidden")
    try:
        r = subprocess.run([ps, "-NoProfile", "-NonInteractive", "-ExecutionPolicy",
                            "Bypass", "-Command", cmd],
                           capture_output=True, text=True, errors="replace",
                           stdin=subprocess.DEVNULL, timeout=900,
                           **_no_window_kwargs())
        launched = (r.returncode == 0)
    except Exception as exc:
        launched = False
        _log(f"Share this PC: could not start PowerShell: {exc}")
    try:
        if not launched or not result.exists():
            return False, ("Windows did not give Administrator rights (the question "
                           "was answered No, or could not be shown).\n\nNothing was "
                           "changed."), ""
        res = json.loads(result.read_text(encoding="utf-8-sig"))
    except Exception as exc:
        return False, f"The setup did not report back: {exc}", ""
    finally:
        shutil.rmtree(tmpdir, ignore_errors=True)       # the password was in there

    steps = res.get("steps") or []
    if isinstance(steps, dict):
        steps = [steps]
    shares = res.get("shares") or []
    if isinstance(shares, dict):
        shares = [shares]
    lines = []
    for s in steps:
        mark = "OK    " if s.get("ok") else "FAILED"
        extra = "" if s.get("ok") else f"   ({str(s.get('msg', ''))[:140]})"
        lines.append(f"  {mark}  {s.get('title', '')}{extra}")
    if not shares:
        return False, ("Nothing could be shared.\n\n" + "\n".join(lines)), ""

    by_letter = {d["letter"]: d for d in drives}
    out_shares = []
    for sh in shares:
        d = by_letter.get(str(sh.get("drive", ""))[:1], {})
        out_shares.append({"share": sh.get("share"), "drive": sh.get("drive"),
                           "label": d.get("label", ""), "size_gb": d.get("size_gb", 0),
                           "mode": "read only" if sh.get("mode") == "read" else "full access"})
    try:
        ips = [i["ip"] for i in _net_get_local_interfaces() if i.get("ip")]
    except Exception:
        ips = []
    info = {"computer": comp, "ips": ips, "user": account,
            "password_b64": base64.b64encode(password.encode("utf-8")).decode("ascii"),
            "shares": out_shares, "made": _time.strftime("%Y-%m-%d %H:%M"),
            "note": "PRIVATE: holds the password of the network account. Copy only "
                    "by USB between your own PCs."}
    try:
        conn.write_text(json.dumps(info, indent=2), encoding="utf-8")
    except Exception as exc:
        return False, f"Shared, but the connection file could not be written: {exc}", ""
    listening = "yes" if res.get("listening") else "NO - check a third-party firewall"
    text = ("\n".join(lines) + f"\n\nFile sharing is listening here: {listening}\n"
            f"This PC answers to: {comp}  {'  '.join(ips)}\n\n"
            "Connection file written:\n" + str(conn) +
            "\n\nNEXT: copy that file by USB to the other PC.  There, in File manager: "
            "NET ▾ → 🔌 Connect to a PC …  (or drop it into Helpfiles\\redigerare and "
            "restart).\n\nTip: give this PC a fixed IP address in the router.")
    ok = any(s.get("ok") for s in steps if "Account" in str(s.get("title", "")))
    return ok, text, str(conn)


# ══════════════════════════════════════════════════════════════════════════
#  DEL 52b — a SERVER for the connection files (no USB, no copying)
# ══════════════════════════════════════════════════════════════════════════
#
# "Share this PC" uploads its PC_connect.json to the small PC-connect relay on
# your own Webdock server; File manager on every other PC fetches it at start
# (and on "Fetch now") and signs in by itself.  The file is ENCRYPTED here first,
# with a SECRET that never leaves your PCs - the server only keeps unreadable text
# and only answers to the KEY.  The setting is ONE small file:
#       Helpfiles\redigerare\pc_relay.json   {"url": "https://host/pcconnect/", "key": "...", "secret": "..."}
# Other people use their own server (the relay + installer are in the PcConnectRelay
# folder) and put their own three values in that file, or paste the code the
# "Server for connection files" window shows.
# ToDo: no way yet to delete a PC's file from the server in the window (the relay
# has DELETE /file/<name>).

PC_RELAY_CONFIG = HELP_DIR / "pc_relay.json"
PCR_CODE_PREFIX = "ISSUSYNC1:"          # same pairing-code idea as Lars's phone apps


def _pcr_load() -> dict:
    """The saved server settings, or {} when none (or incomplete)."""
    try:
        d = json.loads(PC_RELAY_CONFIG.read_text(encoding="utf-8-sig"))
        if (isinstance(d, dict) and str(d.get("url", "")).startswith(("http://", "https://"))
                and len(str(d.get("key", ""))) >= 16 and len(str(d.get("secret", ""))) >= 16):
            d["url"] = d["url"].rstrip("/") + "/"
            return d
    except Exception:
        pass
    return {}


def _pcr_save(cfg: dict):
    PC_RELAY_CONFIG.write_text(json.dumps(
        {"url": cfg["url"], "key": cfg["key"], "secret": cfg["secret"]}, indent=2),
        encoding="utf-8")


def _pcr_code_make(cfg: dict) -> str:
    raw = json.dumps({"a": "pcconnect", "u": cfg["url"], "k": cfg["key"],
                      "s": cfg["secret"]}, separators=(",", ":")).encode("utf-8")
    return PCR_CODE_PREFIX + base64.urlsafe_b64encode(raw).decode("ascii").rstrip("=")


def _pcr_code_parse(text: str) -> dict:
    """The settings inside a pasted code.  Raises ValueError with a plain message."""
    t = "".join(str(text).split())
    i = t.find(PCR_CODE_PREFIX)
    if i < 0:
        raise ValueError("This is not a code (it should start with ISSUSYNC1:).")
    body = t[i + len(PCR_CODE_PREFIX):]
    body = _re.match(r"[A-Za-z0-9_\-]*", body).group(0)
    d = None
    for cut in range(0, 41):                  # words typed after the code are cut off
        part = body[:len(body) - cut]
        try:
            d = json.loads(base64.urlsafe_b64decode(part + "=" * (-len(part) % 4)))
            if isinstance(d, dict):
                break
        except Exception:
            pass
        d = None
    if d is None:
        raise ValueError("The code is damaged - copy it again.")
    if d.get("a") != "pcconnect":
        raise ValueError("This code is for another program.")
    cfg = {"url": str(d.get("u", "")), "key": str(d.get("k", "")), "secret": str(d.get("s", ""))}
    if not cfg["url"].startswith(("http://", "https://")) or len(cfg["key"]) < 16 \
            or len(cfg["secret"]) < 16:
        raise ValueError("The code does not hold a full address, key and secret.")
    return cfg


def _pcr_keys(secret: str, salt: bytes) -> tuple:
    k = hashlib.pbkdf2_hmac("sha256", secret.encode("utf-8"), salt, 100000, 64)
    return k[:32], k[32:]


def _pcr_stream(enc_key: bytes, nonce: bytes, n: int) -> bytes:
    import hmac as _hmac
    out, c = bytearray(), 0
    while len(out) < n:
        out += _hmac.new(enc_key, nonce + c.to_bytes(8, "big"), hashlib.sha256).digest()
        c += 1
    return bytes(out[:n])


def _pcr_encrypt(secret: str, plain: bytes) -> str:
    """Encrypt-then-MAC (HMAC-SHA256 as the keystream and as the check) -> JSON text."""
    import hmac as _hmac
    import secrets as _secrets
    salt, nonce = _secrets.token_bytes(16), _secrets.token_bytes(16)
    ek, mk = _pcr_keys(secret, salt)
    ct = bytes(a ^ b for a, b in zip(plain, _pcr_stream(ek, nonce, len(plain))))
    tag = _hmac.new(mk, b"pcc1" + salt + nonce + ct, hashlib.sha256).digest()
    b = lambda x: base64.b64encode(x).decode("ascii")
    return json.dumps({"v": 1, "s": b(salt), "n": b(nonce), "c": b(ct), "t": b(tag)})


def _pcr_decrypt(secret: str, text: str) -> bytes:
    import hmac as _hmac
    try:
        d = json.loads(text)
        salt, nonce = base64.b64decode(d["s"]), base64.b64decode(d["n"])
        ct, tag = base64.b64decode(d["c"]), base64.b64decode(d["t"])
    except Exception:
        raise ValueError("The file on the server is not in the expected form.")
    ek, mk = _pcr_keys(secret, salt)
    good = _hmac.new(mk, b"pcc1" + salt + nonce + ct, hashlib.sha256).digest()
    if not _hmac.compare_digest(good, tag):
        raise ValueError("The file could not be opened: this PC has another secret "
                         "than the PC that uploaded it.")
    return bytes(a ^ b for a, b in zip(ct, _pcr_stream(ek, nonce, len(ct))))


def _pcr_request(cfg: dict, method: str, path: str, body: bytes = None,
                 timeout: float = 15.0) -> tuple:
    """One call to the relay -> (status, bytes).  Raises OSError on a network problem."""
    import urllib.request
    import urllib.error
    req = urllib.request.Request(cfg["url"] + path.lstrip("/"), data=body, method=method,
                                 headers={"X-Pc-Key": cfg["key"],
                                          "User-Agent": "File_manager"})
    if body is not None:
        req.add_header("Content-Type", "text/plain")
    try:
        with urllib.request.urlopen(req, timeout=timeout) as r:
            return r.status, r.read()
    except urllib.error.HTTPError as exc:
        return exc.code, exc.read()
    except urllib.error.URLError as exc:
        raise OSError(str(exc.reason))
    except OSError:
        raise
    except Exception as exc:                      # a bad address, a broken answer ...
        raise OSError(str(exc))


def _pcr_name(computer: str) -> str:
    return _re.sub(r"[^A-Za-z0-9_-]", "_", computer)[:32] or "PC"


def _pcr_why(status: int) -> str:
    return {401: "the server did not accept the key", 429: "too many wrong keys - wait an hour",
            413: "the file is too big", 404: "not found on the server",
            507: "the server holds too many files"}.get(status, f"the server answered {status}")


def _pcr_upload(conn_path) -> tuple:
    """Put one connection file on the server, encrypted.  Returns (ok, message)."""
    cfg = _pcr_load()
    if not cfg:
        return False, "no server is set up (the Server… button)"
    try:
        data = Path(conn_path).read_bytes()
        comp = _pcc_read(conn_path)["computer"]
        status, _ = _pcr_request(cfg, "PUT", "file/" + _pcr_name(comp),
                                 _pcr_encrypt(cfg["secret"], data).encode("utf-8"))
    except (OSError, ValueError) as exc:
        return False, f"could not reach the server: {exc}"
    if status != 200:
        return False, _pcr_why(status)
    return True, f"the connection file of {comp} is on the server now"


def _pcr_fetch_all() -> list:
    """Fetch + import every other PC's connection file that is new or changed.
    Talks to the network - call it from a thread.  Returns [(name, ok, message)]."""
    cfg = _pcr_load()
    if not cfg:
        return []
    results = []
    try:
        status, raw = _pcr_request(cfg, "GET", "list")
        if status != 200:
            return [("server", False, _pcr_why(status))]
        names = [f["name"] for f in json.loads(raw.decode("utf-8")).get("files", [])]
    except (OSError, ValueError) as exc:
        _log(f"PC connect server: {exc}")
        return [("server", False, f"could not reach the server: {exc}")]
    try:
        done = json.loads(PC_CONNECT_DONE.read_text(encoding="utf-8")) \
            if PC_CONNECT_DONE.exists() else {}
    except Exception:
        done = {}
    me = _pcr_name(socket.gethostname().upper())
    for name in names:
        if name.upper() == me.upper():
            continue
        try:
            status, raw = _pcr_request(cfg, "GET", "file/" + name)
            if status != 200:
                results.append((name, False, _pcr_why(status)))
                continue
            plain = _pcr_decrypt(cfg["secret"], raw.decode("utf-8"))
            digest = hashlib.sha1(plain).hexdigest()
            if done.get("server:" + name) == digest:
                continue                                    # nothing new
            tmpdir = Path(tempfile.mkdtemp(prefix="fm_pcc_"))
            try:
                tmp = tmpdir / f"PC_connect_{name}.json"
                tmp.write_bytes(plain)
                ok, text = _pcc_import(tmp, keep=True)
            finally:
                shutil.rmtree(tmpdir, ignore_errors=True)       # holds the password
            if ok:
                try:
                    done = json.loads(PC_CONNECT_DONE.read_text(encoding="utf-8"))
                except Exception:
                    pass
                done["server:" + name] = digest
                PC_CONNECT_DONE.write_text(json.dumps(done, indent=2), encoding="utf-8")
            _log(f"PC connect server: {name}: {'OK' if ok else 'failed'}")
            results.append((name, ok, text))
        except Exception as exc:
            _log(f"PC connect server: {name} failed: {exc}")
            results.append((name, False, str(exc)))
    return results


class PcRelayDialog(tk.Toplevel):
    """The server settings: address, key, secret - or paste a code."""

    def __init__(self, parent):
        super().__init__(parent)
        self._busy = False
        self.configure(bg=C_BG)
        self.geometry("620x470")
        self.resizable(False, False)
        _setup_toplevel(self, "Server for connection files", parent, modal=True)
        cfg = _pcr_load()
        tk.Label(self, text="🌐  Server for connection files", bg=C_BG, fg=C_ACCENT,
                 font=("Segoe UI", 13, "bold")).pack(anchor="w", padx=14, pady=(12, 2))
        tk.Label(self, text=("Instead of carrying PC_connect.json between your PCs, File "
                             "manager can keep it - encrypted - on your own server.  "
                             "\"Share this PC\" uploads it, every other File manager "
                             "fetches it by itself at start.\nThe server only ever sees "
                             "unreadable text; the secret stays on your PCs."),
                 bg=C_BG, fg=C_FG_DIM, justify="left", wraplength=590,
                 font=("Segoe UI", 9)).pack(anchor="w", padx=14)

        grid = tk.Frame(self, bg=C_BG)
        grid.pack(fill="x", padx=14, pady=(10, 4))
        self._v = {}
        for i, (key, label, hide) in enumerate((("url", "Server address", False),
                                                ("key", "Key (the server checks it)", True),
                                                ("secret", "Secret (encrypts the file)", True))):
            tk.Label(grid, text=label, bg=C_BG, fg=C_FG, anchor="w", width=26,
                     font=("Segoe UI", 9)).grid(row=i, column=0, sticky="w", pady=3)
            var = tk.StringVar(value=str(cfg.get(key, "")))
            self._v[key] = var
            tk.Entry(grid, textvariable=var, width=48, bg=C_BG2, fg=C_FG,
                     show="•" if hide else "", insertbackground=C_FG, insertofftime=0,
                     insertontime=9999999).grid(row=i, column=1, sticky="w", pady=3)

        row = tk.Frame(self, bg=C_BG)
        row.pack(fill="x", padx=14, pady=(6, 0))
        tk.Button(row, text="Paste code", width=12, command=self._paste).pack(side="left", padx=(0, 6))
        tk.Button(row, text="Copy code", width=12, command=self._copy).pack(side="left", padx=6)
        tk.Label(row, text="(the code holds the key and the secret - send it only to your own PCs)",
                 bg=C_BG, fg=C_FG_DIM, font=("Segoe UI", 8)).pack(side="left", padx=8)

        self.msg = tk.Label(self, text="", bg=C_BG, fg=C_FG_DIM, anchor="nw", justify="left",
                            wraplength=590, height=8, font=("Segoe UI", 9))
        self.msg.pack(fill="x", padx=14, pady=(10, 0))

        bar = tk.Frame(self, bg=C_BG)
        bar.pack(side="bottom", fill="x", padx=14, pady=10)
        tk.Button(bar, text="Close", bg="grey", fg="white", width=9,
                  command=self.destroy).pack(side="right", padx=3)
        tk.Button(bar, text="Save", bg="lightgreen", fg="black", width=9,
                  command=self._save).pack(side="right", padx=3)
        tk.Button(bar, text="Fetch now", width=11, command=self._fetch).pack(side="left", padx=3)
        tk.Button(bar, text="Test", width=9, command=self._test).pack(side="left", padx=3)

    def _cfg(self):
        c = {k: v.get().strip() for k, v in self._v.items()}
        if not c["url"].startswith(("http://", "https://")):
            raise ValueError("The address must start with https://")
        if len(c["key"]) < 16 or len(c["secret"]) < 16:
            raise ValueError("The key and the secret must be at least 16 characters.")
        c["url"] = c["url"].rstrip("/") + "/"
        return c

    def _say(self, text, bad=False):
        self.msg.config(text=text, fg=TC_BAD if bad else C_FG_DIM)

    def _paste(self):
        try:
            c = _pcr_code_parse(self.clipboard_get())
        except tk.TclError:
            self._say("The clipboard is empty.", True)
            return
        except ValueError as exc:
            self._say(str(exc), True)
            return
        for k in ("url", "key", "secret"):
            self._v[k].set(c[k])
        self._say("The code was read.  Press Save.")

    def _copy(self):
        try:
            code = _pcr_code_make(self._cfg())
        except ValueError as exc:
            self._say(str(exc), True)
            return
        if not _to_clipboard(code):
            self.clipboard_clear()
            self.clipboard_append(code)
        self._say("The code is on the clipboard.  Paste it in this window on the other PC.")

    def _save(self):
        try:
            c = self._cfg()
            _pcr_save(c)
        except (ValueError, OSError) as exc:
            self._say(str(exc), True)
            return
        self._say(f"Saved in {PC_RELAY_CONFIG}")

    def _run(self, job):
        if self._busy:
            return
        try:
            c = self._cfg()
            _pcr_save(c)                # the work reads the saved file
        except (ValueError, OSError) as exc:
            self._say(str(exc), True)
            return
        self._busy = True
        self._say("Working …")

        def work():
            try:
                text, bad = job(c)
            except Exception as exc:
                text, bad = f"Unexpected problem: {exc}", True

            def done():
                self._busy = False
                self._say(text, bad)
            _ui_call(self, done)
        threading.Thread(target=work, daemon=True).start()

    def _test(self):
        def job(c):
            try:
                s1, _ = _pcr_request(c, "GET", "health")
                s2, raw = _pcr_request(c, "GET", "list")
            except OSError as exc:
                return f"Could not reach the server: {exc}", True
            if s1 != 200:
                return f"The address does not answer like the relay (status {s1}).", True
            if s2 != 200:
                return f"The server is there, but {_pcr_why(s2)}.", True
            names = [f["name"] for f in json.loads(raw.decode("utf-8")).get("files", [])]
            return ("The server answers and the key is accepted.\nConnection files on it: "
                    + (", ".join(names) if names else "none yet")), False
        self._run(job)

    def _fetch(self):
        def job(c):
            res = _pcr_fetch_all()
            if not res:
                return "Nothing new on the server.", False
            return "\n\n".join(f"{n}: {'OK' if ok else 'FAILED'}\n{t}" for n, ok, t in res)[:900], \
                not all(ok for _, ok, _ in res)
        self._run(job)


class SharePCDialog(tk.Toplevel):
    """SHARE OUT: tick the drives, press the button, say Yes to the Windows question."""

    def __init__(self, parent):
        super().__init__(parent)
        self._busy = False
        self._drives = _pcc_local_drives()
        self._vars = []
        self.configure(bg=C_BG)
        self.geometry("600x560")
        self.resizable(False, False)
        _setup_toplevel(self, "Share this PC's drives", parent, modal=True)

        tk.Label(self, text="📤  Share this PC's drives", bg=C_BG, fg=C_ACCENT,
                 font=("Segoe UI", 13, "bold")).pack(anchor="w", padx=14, pady=(12, 2))
        tk.Label(self, text=("Other PCs of yours can then open these drives with ONE "
                             "saved login - nothing to type each time.\nA hidden network "
                             "account is made on this PC; Windows asks for Administrator "
                             "rights once."),
                 bg=C_BG, fg=C_FG_DIM, justify="left",
                 font=("Segoe UI", 9)).pack(anchor="w", padx=14)

        box = tk.Frame(self, bg=C_BG)
        box.pack(fill="x", padx=14, pady=(10, 4))
        if not self._drives:
            tk.Label(box, text="No fixed drives found.", bg=C_BG, fg=TC_BAD).pack(anchor="w")
        for d in self._drives:
            v = tk.BooleanVar(value=True)
            self._vars.append(v)
            note = "system drive" if d["system"] else ""
            tk.Checkbutton(box, variable=v, anchor="w", bg=C_BG, fg=C_FG,
                           selectcolor=C_BG2, activebackground=C_BG,
                           activeforeground=C_FG,
                           text=f"{d['letter']}:   {d['label'] or '(no label)':<22} "
                                f"{d['size_gb']:>6} GB    {note}").pack(fill="x", anchor="w")

        self.var_full = tk.BooleanVar(value=True)
        tk.Checkbutton(self, variable=self.var_full, anchor="w", justify="left",
                       bg=C_BG, fg=C_FG, selectcolor=C_BG2, activebackground=C_BG,
                       activeforeground=C_FG, wraplength=560,
                       text=("Full control: the account may change and delete ANY file "
                             "on these drives, also the system drive (it becomes an "
                             "Administrator on this PC).  Untick for a plain user - "
                             "then the system drive is read-only and files owned by "
                             "other accounts cannot be changed.")
                       ).pack(fill="x", padx=14, pady=(8, 0))

        row = tk.Frame(self, bg=C_BG)
        row.pack(fill="x", padx=14, pady=(10, 2))
        tk.Label(row, text="Network account name:", bg=C_BG, fg=C_FG,
                 font=("Segoe UI", 9)).pack(side="left")
        self.var_acc = tk.StringVar(value=PC_ACCOUNT_DEFAULT)
        tk.Entry(row, textvariable=self.var_acc, width=18, bg=C_BG2, fg=C_FG,
                 insertbackground=C_FG, insertofftime=0,
                 insertontime=9999999).pack(side="left", padx=8)
        tk.Label(self, text="(the password is made for you and kept in the connection file)",
                 bg=C_BG, fg=C_FG_DIM, font=("Segoe UI", 8)).pack(anchor="w", padx=14)

        self.msg = tk.Label(self, text="", bg=C_BG, fg=TC_BAD, anchor="nw",
                            justify="left", wraplength=570, height=4,
                            font=("Segoe UI", 9))
        self.msg.pack(fill="x", padx=14, pady=(8, 0))

        bar = tk.Frame(self, bg=C_BG)
        bar.pack(side="bottom", fill="x", padx=14, pady=10)
        tk.Button(bar, text="Cancel", bg="grey", fg="white", width=9,
                  command=self.destroy).pack(side="right", padx=3)
        self.btn = tk.Button(bar, text="Share …", bg="lightgreen", fg="black",
                             width=12, command=self._go)
        self.btn.pack(side="right", padx=3)
        tk.Button(bar, text="Server …", width=10,
                  command=lambda: PcRelayDialog(self)).pack(side="left", padx=3)
        tk.Label(bar, text=("server set up" if _pcr_load() else "no server (USB copy)"),
                 bg=C_BG, fg=C_FG_DIM, font=("Segoe UI", 8)).pack(side="left", padx=4)

    def _go(self):
        if self._busy:
            return
        account = self.var_acc.get().strip()
        if not _re.fullmatch(r"[A-Za-z0-9_-]{1,20}", account):
            self.msg.config(text="The account name may only hold letters, digits, "
                                 "_ and - (up to 20).", fg=TC_BAD)
            return
        chosen = [d for d, v in zip(self._drives, self._vars) if v.get()]
        if not chosen:
            self.msg.config(text="Tick at least one drive.", fg=TC_BAD)
            return
        names = ", ".join(f"{d['letter']}:" for d in chosen)
        full = bool(self.var_full.get())
        if not _ask_yes_no("Share this PC",
                           f"Share {names} on the network for the account "
                           f"'{account}'"
                           f"{' with FULL control (it becomes an Administrator here)' if full else ''}"
                           "?\n\nWindows will ask for Administrator rights - answer Yes.",
                           parent=self):
            return
        self._busy = True
        self.btn.config(state="disabled")
        self.msg.config(text="Working … answer the Windows question with Yes.",
                        fg=C_FG_DIM)

        def work():
            try:
                res = _pcc_share_run(chosen, account, full)
                if res[0] and res[2]:                  # put it on the server too
                    up_ok, up_msg = _pcr_upload(res[2])
                    res = (res[0], res[1] + "\n\nServer: " + up_msg
                           + ("" if up_ok or not _pcr_load() else
                              "\n(the file is still on this PC; carry it by USB instead)"),
                           res[2])
            except Exception as exc:
                res = (False, f"Unexpected problem: {exc}", "")
            _ui_call(self, lambda: self._finished(*res))

        threading.Thread(target=work, daemon=True).start()

    def _finished(self, ok: bool, text: str, path: str):
        self._busy = False
        if not ok:
            self.btn.config(state="normal")
            self.msg.config(text=text[:600], fg=TC_BAD)
            return
        show = _ask_yes_no("Share this PC - done",
                           text + "\n\nShow the connection file in a folder?",
                           parent=self)
        if show and path:
            try:
                subprocess.Popen([os.path.join(os.environ.get("SystemRoot", r"C:\Windows"),
                                               "explorer.exe"), "/select,", path])
            except Exception:
                pass
        self.destroy()


# ══════════════════════════════════════════════════════════════════════════
#  DEL 90 — Entry point (standalone)
# ══════════════════════════════════════════════════════════════════════════

def _is_shutdown_noise(exc_type, exc_value) -> bool:
    """True for the harmless errors a background thread raises during close.

    When the window is destroyed while a worker thread is still finishing, its
    final `after()` call has no event loop left to schedule on.  That is not a
    fault worth showing the user — it is logged and otherwise ignored.
    """
    if exc_type is RuntimeError:
        text = str(exc_value).lower()
        return ("main thread is not in main loop" in text
                or "application has been destroyed" in text)
    return exc_type is tk.TclError and "application has been destroyed" in str(exc_value)


def _crash_report(exc_type, exc_value, exc_tb, context: str = "main"):
    """Write a diagnostic crash dump and show it to the user."""
    if _is_shutdown_noise(exc_type, exc_value):
        _log(f"Ignored shutdown race in {context}: {exc_type.__name__}: {exc_value}")
        return
    try:
        lines = [
            "=" * 74,
            f"CRASH  {datetime.now():%Y-%m-%d %H:%M:%S}   (context: {context})",
            "=" * 74,
            f"Program   : File_manager.py",
            f"App root  : {APP_ROOT}",
            f"Python    : {sys.version}",
            f"Platform  : {platform.platform()}",
            f"Executable: {sys.executable}",
            f"Frozen    : {bool(getattr(sys, 'frozen', False))}",
            f"tkinterdnd2: {'yes' if _HAS_DND else 'no'}",
            "-" * 74,
            "".join(traceback.format_exception(exc_type, exc_value, exc_tb)),
        ]
        dump = "\n".join(lines)
        with open(CRASH_PATH, "a", encoding="utf-8") as fh:
            fh.write(dump + "\n")
    except Exception:
        dump = f"{exc_type.__name__}: {exc_value}"

    # Never let the reporter itself take the program down.
    # Preferred: a NON-modal dialog so the main window stays usable — you can
    # keep working and open the log folder straight from a button, without
    # having to remember the path.  Falls back to a plain messagebox, then
    # stderr, if the GUI is already too far gone to build a Toplevel.
    try:
        _show_crash_dialog(exc_type, exc_value)
    except Exception:
        try:
            messagebox.showerror(
                "File Manager — unexpected error",
                f"{exc_type.__name__}: {exc_value}\n\n"
                f"A diagnostic report was written to:\n{CRASH_PATH}",
            )
        except Exception:
            print(dump, file=sys.stderr)


def _open_log_folder():
    """Open the log folder in Explorer, selecting the crash log if possible."""
    try:
        if CRASH_PATH.exists():
            subprocess.Popen(["explorer", "/select,", str(CRASH_PATH)])
        else:
            os.startfile(str(LOG_DIR))   # type: ignore[attr-defined]
    except Exception:
        try:
            os.startfile(str(LOG_DIR))   # type: ignore[attr-defined]
        except Exception:
            pass


def _show_crash_dialog(exc_type, exc_value):
    """Non-modal error dialog: the main window stays fully usable behind it."""
    root = tk._default_root
    if root is None:
        raise RuntimeError("no Tk root to attach the crash dialog to")

    C_BG   = "#1e1e2a"
    C_FG   = "#e0e0f0"
    C_DIM  = "#a0a0b8"
    C_BTN  = "#2a2a3d"

    top = tk.Toplevel(root)
    top.title("File Manager — unexpected error")
    top.configure(bg=C_BG)
    top.resizable(False, False)
    # Deliberately NO grab_set(): this dialog must NOT block the main window,
    # so you can still browse to the log folder / keep working while it is open.
    top.attributes("-topmost", True)

    tk.Label(top, text="⚠  An unexpected error occurred",
             bg=C_BG, fg="#ff8080",
             font=("Segoe UI", 12, "bold")).pack(padx=24, pady=(18, 4))
    tk.Label(top, text=f"{exc_type.__name__}: {exc_value}",
             bg=C_BG, fg=C_FG, font=("Segoe UI", 9),
             wraplength=440, justify="left").pack(padx=24, pady=(0, 8))
    tk.Label(top, text=f"A diagnostic report was written to:\n{CRASH_PATH}",
             bg=C_BG, fg=C_DIM, font=("Segoe UI", 8),
             wraplength=440, justify="left").pack(padx=24, pady=(0, 12))

    btns = tk.Frame(top, bg=C_BG)
    btns.pack(padx=24, pady=(0, 18))
    # NOTE: button base colours spelled out so they are easy to re-theme.
    tk.Button(btns, text="Open log folder", command=_open_log_folder,
              bg=C_BTN, fg=C_FG, activebackground="#3a3a52",
              activeforeground=C_FG, relief="flat", bd=0,
              padx=14, pady=5, cursor="hand2").pack(side="left", padx=(0, 10))
    tk.Button(btns, text="Close", command=top.destroy,
              bg=C_BTN, fg=C_FG, activebackground="#3a3a52",
              activeforeground=C_FG, relief="flat", bd=0,
              padx=18, pady=5, cursor="hand2").pack(side="left")

    top.bind("<Escape>", lambda e: top.destroy())
    top.update_idletasks()
    # Centre over the main window
    try:
        x = root.winfo_rootx() + (root.winfo_width()  - top.winfo_width())  // 2
        y = root.winfo_rooty() + (root.winfo_height() - top.winfo_height()) // 3
        top.geometry(f"+{max(x, 0)}+{max(y, 0)}")
    except Exception:
        pass
    top.focus_force()


def _install_crash_handlers(root: tk.Tk):
    """Catch exceptions from threads, callbacks and the interpreter itself."""
    sys.excepthook = lambda t, v, tb: _crash_report(t, v, tb, "interpreter")

    # A Python-level handler cannot see a HARD death — a Tcl panic, a stack
    # overflow from runaway recursion, or an access violation kill the process
    # with nothing written anywhere, which is exactly the "it just disappeared"
    # case with an empty log.  faulthandler writes the native traceback of every
    # thread straight to a file descriptor, so even those leave evidence.
    try:
        import faulthandler
        global _FAULT_FH
        _FAULT_FH = open(FAULT_PATH, "a", buffering=1, encoding="utf-8",
                         errors="replace")
        _FAULT_FH.write(
            f"\n===== session started {datetime.now():%Y-%m-%d %H:%M:%S} =====\n")
        faulthandler.enable(file=_FAULT_FH, all_threads=True)
    except Exception as exc:
        _log(f"faulthandler not available: {exc}")

    # tkinter reports callback exceptions via root.report_callback_exception(
    # exc, val, tb) — three positional args, NO self.  Setting a 4-arg method
    # (self, exc, val, tb) as an *instance* attribute made the call arrive one
    # argument short ("missing 'tb'"), which turned every minor callback error
    # into a hard crash.  Use a 3-arg function on the instance, and a matching
    # self-taking wrapper on the class so both call styles are correct.
    def _tk_report(exc, val, tb):
        _crash_report(exc, val, tb, "tk-callback")
    root.report_callback_exception = _tk_report
    tk.Tk.report_callback_exception = lambda self, exc, val, tb: _tk_report(exc, val, tb)

    try:    # Python 3.8+ — background thread failures
        threading.excepthook = lambda a: _crash_report(
            a.exc_type, a.exc_value, a.exc_traceback, f"thread:{a.thread.name}")
    except Exception:
        pass


def _restore_geometry(root: tk.Tk, app: "EditorFrame"):
    """Restore the window size / position saved on the previous exit."""
    geo = app.settings.get("window_geometry", "")
    try:
        if geo:
            root.geometry(geo)
            # Guard against a saved position that is now off-screen (e.g. the
            # second monitor is gone) — nudge it back onto the primary screen.
            root.update_idletasks()
            if (root.winfo_x() < -50 or root.winfo_y() < -50
                    or root.winfo_x() > root.winfo_screenwidth() - 100
                    or root.winfo_y() > root.winfo_screenheight() - 100):
                root.geometry("1200x800+80+60")
        else:
            root.geometry("1200x800")
    except Exception:
        root.geometry("1200x800")

    if app.settings.get("window_maximized"):
        try:
            root.state("zoomed")
        except Exception:
            pass


# ═══════════════════════════════════════════════════════════════════════
#  COMMAND LINE + SINGLE INSTANCE
# ═══════════════════════════════════════════════════════════════════════
#
#   File_manager.py <folder>    show that folder in the active panel
#   File_manager.py <file>      show its folder, cursor on the file
#
# This is what lets my OTHER programs say "open this folder" and have it land
# here instead of in Explorer — 36 of them call os.startfile() on a folder.
# Without a hand-over each of those calls would start a SECOND File Manager,
# so a running copy has to take the path instead.
#
# The lock is a BOUND SOCKET, not a lock file: a lock file survives a crash
# and then locks you out of your own program for ever.  A socket dies with
# the process, whatever killed it.
_FM_PORT = 50598                       # ExeForge uses 50597; keep them apart


def _fm_cli_paths() -> list:
    """Paths handed to us on the command line.  A leading "-" is a flag."""
    out = []
    for a in sys.argv[1:]:
        a = (a or "").strip().strip('"')
        if a and not a.startswith("-") and os.path.exists(a):
            out.append(os.path.abspath(a))
    return out


def _fm_hand_over(paths: list) -> bool:
    """Give the paths to a copy that is already running.  True if it took them."""
    try:
        with socket.create_connection(("127.0.0.1", _FM_PORT), timeout=1.5) as s:
            s.sendall(("\n".join(paths) + "\n").encode("utf-8"))
            return True
    except OSError:
        return False


def _fm_claim_instance():
    """Bind the port, or return None when another copy already holds it."""
    try:
        srv = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        # No SO_REUSEADDR on purpose: it would let a second copy bind too,
        # which is the one thing this must not allow.
        srv.bind(("127.0.0.1", _FM_PORT))
        srv.listen(4)
        return srv
    except OSError:
        return None


def _fm_serve(srv, app):
    """Background: take paths from later launches and queue them.

    The queue is drained by the MAIN thread (_drain_cli_paths).  after() must
    never be called from here — a worker's after() only fires while mainloop
    happens to be running and is a classic way to lose the last one."""
    while True:
        try:
            conn, _ = srv.accept()
        except OSError:
            return
        try:
            with conn:
                conn.settimeout(2.0)
                data = b""
                while len(data) < 65536:
                    chunk = conn.recv(4096)
                    if not chunk:
                        break
                    data += chunk
            for line in data.decode("utf-8", "replace").splitlines():
                line = line.strip()
                if line:
                    app._cli_queue.append(line)
        except Exception:
            pass


def _fm_share_only():
    """File_manager.py --share : ONLY the "Share this PC's drives" window (DEL 52),
    for the PC whose drives others should reach (FILM).  Needs nothing but Python -
    no main window, no other program, no .bat."""
    root = tk.Tk()
    root.title("File Manager - Share this PC")
    # Not withdrawn: a dialog that belongs to a withdrawn window is never shown.
    root.geometry("1x1+0+0")
    root.attributes("-alpha", 0.0)
    root.report_callback_exception = lambda e, v, tb: _crash_report(e, v, tb, "share")
    dlg = SharePCDialog(root)
    dlg.bind("<Destroy>", lambda e: root.after(50, root.destroy)
             if e.widget is dlg else None)
    _set_window_icon(dlg)
    root.mainloop()


if __name__ == "__main__":
    if any(a.lower() in ("--share", "--share-this-pc") for a in sys.argv[1:]):
        _fm_share_only()
        sys.exit(0)
    _cli_paths = _fm_cli_paths()
    if _cli_paths and _fm_hand_over(_cli_paths):
        sys.exit(0)                    # a running copy took it — do not open a 2nd

    # Must be set BEFORE tk.Tk() for correct taskbar grouping on Windows
    try:
        ctypes.windll.shell32.SetCurrentProcessExplicitAppUserModelID(
            "LarsIssu.FileManager.1")
    except Exception:
        pass

    if _HAS_DND:
        root = _TkinterDnD.Tk()
        # A click is a click: tkdnd's own 3-pixel drag threshold turned the
        # tiniest hand tremor into a real drag-and-drop.
        _set_dnd_drag_threshold(root)
    else:
        root = tk.Tk()
    # The build stamp (the file's own modified time) is added to the title by
    # EditorFrame._apply_window_title, only when "show_build_in_title" is on.
    root.title("File Manager")

    _install_crash_handlers(root)

    app = EditorFrame(root)
    app.pack(fill="both", expand=True)
    app._apply_window_title()

    _restore_geometry(root, app)

    # Hold the port for the rest of the session and listen for later launches.
    # If the bind fails we simply run without the hand-over — a second window
    # is far better than refusing to start.
    _fm_srv = _fm_claim_instance()
    if _fm_srv is not None:
        # Created HERE, before the listener can touch it: a path that arrived
        # in the first fraction of a second would otherwise be dropped by the
        # thread's own except-clause and never seen again.
        app._cli_queue = []
        threading.Thread(target=_fm_serve, args=(_fm_srv, app),
                         daemon=True).start()
        root.after(300, app._drain_cli_paths)
    for _p in _cli_paths:
        root.after(400, lambda p=_p: app.show_cli_path(p))

    root.after(0, lambda: _set_window_icon(root))  # after(0) = first event loop tick

    def _on_close():
        # ── The queue gets a say ───────────────────────────────
        # A transfer in progress is not something to lose to a stray click on
        # the X.  The bytes are stopped FIRST — the copy stands down at the
        # next block boundary, which is the "suitable place" — and only then is
        # the question asked; "keep working" puts it back exactly where it was.
        if getattr(app, "_fm_closing", False):
            return                       # already on the way out (the wait
                                         # below pumps the event loop, and a
                                         # second X must not re-enter here)
        mgr = getattr(app, "task_queue_mgr", None)
        try:
            waiting = mgr.pending_count() if mgr is not None else 0
        except Exception:
            waiting = 0
        if waiting:
            was_paused = bool(mgr._paused)
            mgr._paused = True
            try:
                mgr._update_ui()
            except Exception:
                pass
            cur = (mgr._current_task or mgr._current_fast
                   or mgr._current_bus or mgr._current_reloc)
            desc = cur.description if cur is not None else ""
            try:
                left = sum(max(0, t.size_bytes) for t in mgr.unfinished())
            except Exception:
                left = 0
            choice = _ask_close_while_busy(root, waiting, desc, left)
            if choice == "keep":
                mgr._paused = was_paused
                try:
                    mgr._update_ui()
                except Exception:
                    pass
                return
            app._fm_closing = True
            # Written down BEFORE anything is cancelled, so the job that was
            # mid-transfer is saved as unfinished rather than as cancelled.
            try:
                mgr.save_state_now(freeze=True)
            except Exception as exc:
                _log(f"Could not save the task queue: {exc}")
            try:
                mgr.shutdown_stop(root, wait_s=5.0)
            except Exception as exc:
                _log(f"Queue shutdown: {exc}")
            if choice == "drop":
                try:
                    mgr.discard_state()
                except Exception as exc:
                    _log(f"Could not drop the task queue: {exc}")
        app._fm_closing = True
        try:
            # Remember window size + position (but store the restored geometry,
            # not the maximized one, so un-maximizing gives a sane size back)
            try:
                maximized = root.state() == "zoomed"
                app.settings["window_maximized"] = maximized
                if maximized:
                    root.state("normal")
                    root.update_idletasks()
                app.settings["window_geometry"] = root.geometry()
            except Exception:
                pass
            app.shutdown()
            app.save_settings()
        finally:
            root.destroy()

    root.protocol("WM_DELETE_WINDOW", _on_close)
    # ToDo (2026-11-03): put every saved network sign-in back into Windows in the
    # background, so a reinstalled / reset Windows finds the computers again.
    threading.Thread(target=_net_restore_all_logins, daemon=True).start()
    # ToDo (2026-11-21, DEL 52): connection files dropped into Helpfiles\redigerare
    # are imported once, and saved network drives come back after a reinstall.
    threading.Thread(target=lambda: (_time.sleep(2.0), _pcc_autoimport()),
                     daemon=True).start()
    root.mainloop()
