Skip to content

A fast file manager for Windows and macOS that never freezes: tabs, dual panes, archives as folders, Quick Look-style previews. A File Explorer and Finder alternative written in Rust.

54.8 KB
Raw Blame
//! What the dock needs to know about the screen, and how it learns that it changed: the primary monitor (its rectangle, work area
//! and DPI), the band the application desktop toolbar reserves at the bottom of it, and one hidden window that hears about every
//! change.
//!
//! [`DockSystem`] owns that hidden window on a thread of its own (a zero-size, never shown pop-up: the toolbar needs an owner, and
//! the messages that tell of display, DPI, work-area, theme and clock changes are broadcast to top-level windows, which a
//! message-only window would not get). It sends [`SystemEvent`]s to a callback on that thread; the app turns them into a re-read of
//! [`primary_monitor`] and a re-placement of the islands. Dropping it takes the reserved band back.

use std::sync::atomic::{AtomicBool, AtomicIsize, Ordering};
use std::sync::{Arc, Mutex};
use std::time::Duration;

use super::band::{AppBarCalls, Applied, Band, MAX_REGISTER_TRIES, TrayId, announcement_is_restart};
use super::layout::{DockEdge, Rect, placement_area_on_edge};
use crate::shellhost::ShellMode;
use crate::shellhost::watch::{Cause, ModeWatch, Seen, SystemLook};

/// The primary monitor as the dock sees it, device px.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct MonitorInfo {
    /// The monitor handle (an `HMONITOR`).
    pub handle: isize,
    /// The whole monitor.
    pub rect: Rect,
    /// What is left of it after the Windows taskbar and other desktop toolbars (ours included, once it has reserved its band).
    pub work: Rect,
    /// Effective DPI of the monitor (96 = 100 %).
    pub dpi: u32,
}

impl MonitorInfo {
    /// Device px per logical px.
    pub fn scale(&self) -> f32 {
        self.dpi as f32 / 96.0
    }
}

/// Makes the calling thread per-monitor DPI aware (v2) for as long as it lives, so that rectangles come back in device px whatever
/// the process was started as. GPUI's own process already is; this makes the functions here correct from any caller.
struct Aware(windows::Win32::UI::HiDpi::DPI_AWARENESS_CONTEXT);

impl Aware {
    fn enter() -> Aware {
        use windows::Win32::UI::HiDpi::{DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE_V2, SetThreadDpiAwarenessContext};
        Aware(unsafe { SetThreadDpiAwarenessContext(DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE_V2) })
    }
}

impl Drop for Aware {
    fn drop(&mut self) {
        use windows::Win32::UI::HiDpi::SetThreadDpiAwarenessContext;
        unsafe {
            SetThreadDpiAwarenessContext(self.0);
        }
    }
}

/// The calling thread per-monitor DPI aware until the returned guard is dropped (for the other files of this module).
pub(super) fn aware_thread() -> impl Drop {
    Aware::enter()
}

fn rect_of(r: windows::Win32::Foundation::RECT) -> Rect {
    Rect::new(r.left, r.top, r.right, r.bottom)
}

/// The primary monitor now. `None` only when Windows has no monitor to give (a session without a display).
pub fn primary_monitor() -> Option<MonitorInfo> {
    use windows::Win32::Foundation::POINT;
    use windows::Win32::Graphics::Gdi::{GetMonitorInfoW, MONITOR_DEFAULTTOPRIMARY, MONITORINFO, MonitorFromPoint};
    use windows::Win32::UI::HiDpi::{GetDpiForMonitor, MDT_EFFECTIVE_DPI};
    let _aware = Aware::enter();
    unsafe {
        // the primary monitor's top left corner is the origin of the virtual screen
        let hmon = MonitorFromPoint(POINT { x: 0, y: 0 }, MONITOR_DEFAULTTOPRIMARY);
        if hmon.is_invalid() {
            return None;
        }
        let mut mi = MONITORINFO { cbSize: size_of::<MONITORINFO>() as u32, ..Default::default() };
        if !GetMonitorInfoW(hmon, &mut mi).as_bool() {
            return None;
        }
        let (mut dx, mut dy) = (0u32, 0u32);
        let dpi = if GetDpiForMonitor(hmon, MDT_EFFECTIVE_DPI, &mut dx, &mut dy).is_ok() && dx > 0 { dx } else { 96 };
        Some(MonitorInfo { handle: hmon.0 as isize, rect: rect_of(mi.rcMonitor), work: rect_of(mi.rcWork), dpi })
    }
}

/// What changed on the system, for the dock to react to.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum SystemEvent {
    /// The display configuration, the primary monitor's DPI or its work area changed (also: the Windows taskbar moved, hid itself or
    /// came back, another desktop toolbar came or went, our own band was set). Read [`primary_monitor`] again and re-place the islands.
    /// Coalesced: a burst of messages gives one event.
    LayoutChanged,
    /// The light / dark theme or the accent colour changed. Read [`crate::accent`] again.
    ThemeChanged,
    /// A full-screen application came to the front on the primary monitor (`true`) or left it (`false`).
    Fullscreen(bool),
    /// The system time or time zone changed, or the machine woke up: show the clock again.
    TimeChanged,
    /// The shell window came, went or is another one (Explorer closed, restarted or replaced), and the mode is now this. Sent from the
    /// watch in [`crate::shellhost::watch`]; the receiver compares the mode with the one it knows to see whether the MODE changed.
    ShellChanged(ShellMode),
}

#[derive(Default)]
struct Shared {
    /// The thickness the app wants reserved (`None`: no band), device px.
    want: Option<i32>,
    edge: DockEdge,
    /// The band the system granted.
    band: Option<Rect>,
}

/// The hidden window, the toolbar registration and the change watch. See the module docs.
pub struct DockSystem {
    hwnd: isize,
    shared: Arc<Mutex<Shared>>,
    fullscreen: Arc<AtomicBool>,
    thread: Option<std::thread::JoinHandle<()>>,
    /// Signalled when the window thread has ended (so that dropping never waits for ever on a thread stuck in the shell).
    ended: std::sync::mpsc::Receiver<()>,
}

/// How long dropping waits for the window thread to take the band back and end.
const END_WAIT: Duration = Duration::from_secs(3);

/// The band the host took out of the work area ITSELF, with no shell to ask (see `shellhost/workarea.rs`). The islands float inside it
/// just like inside a granted band, so [`DockSystem::placement_area`] puts it back the same way. `None`: there is none.
static OWN_BAND: Mutex<Option<Rect>> = Mutex::new(None);

fn own_band() -> Option<Rect> {
    *OWN_BAND.lock().unwrap_or_else(|p| p.into_inner())
}

/// Tells the placement about a band the host took itself (or that it gave it back).
pub fn set_own_band(band: Option<Rect>) {
    let changed = {
        let mut g = OWN_BAND.lock().unwrap_or_else(|p| p.into_inner());
        let changed = *g != band;
        *g = band;
        changed
    };
    // the islands are placed from it, so they are placed again when it changed. (The work area's own change says so too, but a work
    // area that an earlier host left as wanted is adopted without any change, and the islands stayed above their band.)
    if changed {
        wake_system();
    }
}

// ---------------------------------------------------------------- the bottom edge while the taskbar hide is in force
//
// With `shell_hide_taskbar` on, the host hides Explorer's taskbar and TAKES THE BOTTOM EDGE: it sets the work area itself (the monitor
// less the dock's band) instead of leaving the hidden taskbar's strip in it (`rf_shellguard::tbwork`, `rf_win::taskbar_hide`). The dock
// has two parts in that: its placement works from the monitor's bottom edge, and its own desktop-toolbar registration with Explorer
// is GIVEN BACK and stays given back (a second band on top of the host's own). Both are one call here, [`take_edge`], and one back,
// [`give_back_edge`]; the registration is registered again when the edge is given back.

/// The dock's band while the host owns the bottom edge: the bottom strip of the primary monitor (empty when the dock reserves none).
static EDGE: Mutex<Option<Rect>> = Mutex::new(None);
/// The registration with Explorer is not to be held (the host owns the edge).
static APPBAR_SUPPRESSED: AtomicBool = AtomicBool::new(false);
/// Our registration with Explorer is held right now (kept by the system thread after every look).
static APPBAR_HELD: AtomicBool = AtomicBool::new(false);
/// The host has docks on the other monitors (or is about to): the 2 s tick then also looks at every monitor's rectangle, work area and
/// scale, so that a change of a monitor that is not the primary one (its scale, its resolution, its place) reaches the host too. Off, the
/// tick looks at the primary monitor only, as it always did.
static WATCH_ALL: AtomicBool = AtomicBool::new(false);

/// Switches the look at every monitor on or off (the host: a dock on every monitor is wanted).
pub fn watch_all_monitors(on: bool) {
    WATCH_ALL.store(on, Ordering::Relaxed);
}

/// The system window (0: there is none), so that the host's thread can wake it.
static SYSTEM_WINDOW: AtomicIsize = AtomicIsize::new(0);

fn edge_band() -> Option<Rect> {
    *EDGE.lock().unwrap_or_else(|p| p.into_inner())
}

fn wake_system() {
    use windows::Win32::Foundation::{HWND, LPARAM, WPARAM};
    use windows::Win32::UI::WindowsAndMessaging::PostMessageW;
    let h = SYSTEM_WINDOW.load(Ordering::SeqCst);
    if h != 0 {
        // SAFETY: posting to a window of this process; if it is gone the post fails and nothing happens.
        unsafe {
            let _ = PostMessageW(Some(HWND(h as *mut _)), WM_RESERVE, WPARAM(0), LPARAM(0));
        }
    }
}

/// The host owns the bottom edge now: the dock's band is `band` (the bottom strip of the primary monitor), the islands are placed from
/// the monitor's bottom edge, and the registration with Explorer is given back and stays given back. Does NOT wait: [`appbar_held`]
/// turns false when the system thread has removed the registration. Telling it again only moves the strip.
pub fn take_edge(band: Rect) {
    *EDGE.lock().unwrap_or_else(|p| p.into_inner()) = Some(band);
    APPBAR_SUPPRESSED.store(true, Ordering::SeqCst);
    wake_system();
}

/// The host gives the edge back (the taskbar is shown again): the placement works from the work area again and the band is registered
/// with Explorer again. Does not wait. Safe when the edge was never taken.
pub fn give_back_edge() {
    let was = APPBAR_SUPPRESSED.swap(false, Ordering::SeqCst);
    let had = EDGE.lock().unwrap_or_else(|p| p.into_inner()).take().is_some();
    if was || had {
        wake_system();
    }
}

/// Whether the dock holds a desktop-toolbar registration with Explorer. False also when there is no dock system in this process.
pub fn appbar_held() -> bool {
    APPBAR_HELD.load(Ordering::SeqCst)
}

/// The window that holds our toolbar registration right now (0: none). Read by the panic hook, which can run on any thread.
static BAR_WINDOW: std::sync::atomic::AtomicIsize = std::sync::atomic::AtomicIsize::new(0);

// ---------------------------------------------------------------- the bands of the docks on the other monitors
//
// While Explorer's taskbar hides itself (`rf_shellguard::tbctl`, `explorer_keeps_bands`) the dock on every other monitor keeps a band
// of its own registered with Explorer, like the home dock's: Explorer then computes that monitor's work area itself and keeps it
// through every recomputation. A registration belongs to a window, so each of these bands has a hidden window of its own on the
// system thread; they tell the system window when Explorer moves them.

/// The bands wanted on the other monitors (device name, thickness in device px). Empty: none.
static OTHER_WANT: Mutex<Vec<(String, i32)>> = Mutex::new(Vec::new());
/// The windows that hold a registration for another monitor's band right now, for the panic hook.
static OTHER_BAR_WINDOWS: Mutex<Vec<isize>> = Mutex::new(Vec::new());

/// The docks on the other monitors keep these bands registered with Explorer (an empty list: none; the registrations are given
/// back). Does not wait: the system thread registers, moves and removes them. Costs a lock and a comparison when nothing changed.
pub fn set_other_bands(bands: Vec<(String, i32)>) {
    let changed = {
        let mut g = OTHER_WANT.lock().unwrap_or_else(|p| p.into_inner());
        let changed = *g != bands;
        *g = bands;
        changed
    };
    if changed {
        wake_system();
    }
}

fn other_want() -> Vec<(String, i32)> {
    OTHER_WANT.lock().unwrap_or_else(|p| p.into_inner()).clone()
}

/// One other monitor's band: its hidden window and its registration.
struct OtherBar {
    monitor: String,
    hwnd: isize,
    band: Band,
}

/// Which of the held bands go (their monitor is no longer wanted or no longer there) and which monitors need a new one. Pure, so that
/// the bookkeeping is a test: `held` and `present` are device names, `want` is the wish.
fn other_bands_plan(held: &[String], want: &[(String, i32)], present: &[String]) -> (Vec<String>, Vec<String>) {
    let wanted = |m: &String| want.iter().any(|(w, _)| w == m) && present.contains(m);
    let go: Vec<String> = held.iter().filter(|m| !wanted(m)).cloned().collect();
    let mut come: Vec<String> = Vec::new();
    for (m, _) in want {
        if present.contains(m) && !held.contains(m) && !come.contains(m) {
            come.push(m.clone());
        }
    }
    (go, come)
}

const WM_RESERVE: u32 = windows::Win32::UI::WindowsAndMessaging::WM_APP + 2;
/// The message the system sends the toolbar's window about toolbars (`uCallbackMessage`).
const WM_BAR: u32 = windows::Win32::UI::WindowsAndMessaging::WM_APP + 1;
const TIMER_POLL: usize = 1;
const TIMER_DEBOUNCE: usize = 2;
/// One shot: the toolbar registration is tried again after Explorer refused it right after its announcement.
const TIMER_RETRY: usize = 3;
const RETRY_MS: u32 = 1000;
const POLL_MS: u32 = 500;
const DEBOUNCE_MS: u32 = 150;

struct Ctx {
    on_event: Box<dyn Fn(SystemEvent) + Send>,
    shared: Arc<Mutex<Shared>>,
    fullscreen: Arc<AtomicBool>,
    /// The toolbar registration and the band last granted (see `band.rs`).
    band: Band,
    /// Failed registrations since the last announcement or success.
    register_tries: u8,
    /// Whether the shell window is still the one the host saw (see `shellhost/watch.rs`).
    shell: ModeWatch,
    started: std::time::Instant,
    last_monitor: Option<MonitorInfo>,
    /// Every monitor as the last 2 s tick saw it (only kept while [`watch_all_monitors`] is on).
    last_all: Vec<MonitorInfo>,
    ticks: u32,
    layout_pending: bool,
    /// Explorer's taskbar window as it was when it took our registration (see [`announcement_is_restart`]).
    tray_at_registration: Option<TrayId>,
    /// The edge state the app was last told about, so that taking or giving back the edge is announced once.
    edge_seen: (bool, Option<Rect>, Option<Rect>),
    /// The bands of the docks on the other monitors that are registered with Explorer (see [`set_other_bands`]).
    others: Vec<OtherBar>,
}

impl Ctx {
    fn emit(&self, e: SystemEvent) {
        (self.on_event)(e);
    }

    fn shared(&self) -> std::sync::MutexGuard<'_, Shared> {
        self.shared.lock().unwrap_or_else(|p| p.into_inner())
    }
}

impl DockSystem {
    /// Starts the hidden window and its thread. `on_event` runs on that thread (not the UI thread): hand the event over to the UI
    /// thread and return. It must not drop the `DockSystem`.
    pub fn start(on_event: impl Fn(SystemEvent) + Send + 'static) -> anyhow::Result<DockSystem> {
        let shared = Arc::new(Mutex::new(Shared::default()));
        let fullscreen = Arc::new(AtomicBool::new(false));
        let (tx, rx) = std::sync::mpsc::channel::<Result<isize, String>>();
        let (s2, f2) = (shared.clone(), fullscreen.clone());
        let (end_tx, ended) = std::sync::mpsc::channel::<()>();
        install_panic_cleanup();
        let thread = std::thread::Builder::new().name("rf-dock-system".into()).spawn(move || {
            let ctx = Box::new(Ctx {
                on_event: Box::new(on_event),
                shared: s2,
                fullscreen: f2,
                band: Band::new(),
                register_tries: 0,
                shell: ModeWatch::new(&SystemLook),
                started: std::time::Instant::now(),
                last_monitor: None,
                last_all: Vec::new(),
                ticks: 0,
                layout_pending: false,
                tray_at_registration: None,
                edge_seen: (false, None, None),
                others: Vec::new(),
            });
            run(ctx, tx);
            let _ = end_tx.send(());
        })?;
        match rx.recv_timeout(Duration::from_secs(5)) {
            Ok(Ok(hwnd)) => Ok(DockSystem { hwnd, shared, fullscreen, thread: Some(thread), ended }),
            Ok(Err(e)) => Err(anyhow::anyhow!(e)),
            Err(e) => Err(anyhow::anyhow!("the dock's system window did not start: {e}")),
        }
    }

    /// Asks the system to keep `thickness_px` (device px, see [`super::layout::reserved_thickness`]) free above the bottom of the
    /// primary monitor: maximised windows then stop above the band. Registers the toolbar the first time and moves it afterwards.
    /// Asynchronous: a [`SystemEvent::LayoutChanged`] follows when the work area has changed.
    pub fn reserve(&self, thickness_px: i32) {
        self.reserve_on(Some(thickness_px), DockEdge::Bottom);
    }

    /// Keep the selected edge free, or release the band when the thickness is absent.
    pub fn reserve_on(&self, thickness_px: Option<i32>, edge: DockEdge) {
        {
            let mut shared = self.shared.lock().unwrap_or_else(|p| p.into_inner());
            shared.want = thickness_px.map(|t| t.max(1));
            shared.edge = edge;
        }
        self.post_reserve();
    }

    /// Gives the band back (the toolbar is unregistered). The dock then only floats.
    pub fn release(&self) {
        self.shared.lock().unwrap_or_else(|p| p.into_inner()).want = None;
        self.post_reserve();
    }

    fn post_reserve(&self) {
        use windows::Win32::Foundation::{HWND, LPARAM, WPARAM};
        use windows::Win32::UI::WindowsAndMessaging::PostMessageW;
        unsafe {
            let _ = PostMessageW(Some(HWND(self.hwnd as *mut _)), WM_RESERVE, WPARAM(0), LPARAM(0));
        }
    }

    /// The band the system granted, if any.
    pub fn band(&self) -> Option<Rect> {
        self.shared.lock().unwrap_or_else(|p| p.into_inner()).band
    }

    /// The area to place the islands in: the primary monitor's work area with this toolbar's band put back (see
    /// [`placement_area`]). `None` without a monitor.
    pub fn placement_area(&self) -> Option<(MonitorInfo, Rect)> {
        let m = primary_monitor()?;
        let shared = self.shared.lock().unwrap_or_else(|p| p.into_inner());
        let band = edge_band().or(shared.band).or(own_band());
        // The active band may still belong to the previous edge during a change.
        let edge = band.map_or(shared.edge, |b| if b.width() < b.height() { DockEdge::Right } else { DockEdge::Bottom });
        Some((m, placement_area_on_edge(m.work, band, m.rect, edge)))
    }

    /// The last known state of the full-screen check (kept up to date by the watch).
    pub fn fullscreen(&self) -> bool {
        self.fullscreen.load(Ordering::Relaxed)
    }
}

impl Drop for DockSystem {
    fn drop(&mut self) {
        use windows::Win32::Foundation::{HWND, LPARAM, WPARAM};
        use windows::Win32::UI::WindowsAndMessaging::{PostMessageW, WM_CLOSE};
        unsafe {
            let _ = PostMessageW(Some(HWND(self.hwnd as *mut _)), WM_CLOSE, WPARAM(0), LPARAM(0));
        }
        if let Some(t) = self.thread.take()
            && t.thread().id() != std::thread::current().id()
        {
            // The window thread makes synchronous calls to Explorer (the toolbar messages). With Explorer hung they never return,
            // and the dock must still be able to end: wait a while, then leave the thread to die with the process.
            if !matches!(self.ended.recv_timeout(END_WAIT), Err(std::sync::mpsc::RecvTimeoutError::Timeout)) {
                let _ = t.join();
            } else {
                log::warn!("dock: the system window did not end in {END_WAIT:?}; the toolbar band may stay until Explorer notices");
            }
        }
    }
}

/// If the dock panics (the release build then aborts, and no destructor runs) the toolbar band is given back first, from the panic
/// hook. Installed once; the hook that was there (the crash log) still runs after it.
fn install_panic_cleanup() {
    static ONCE: std::sync::Once = std::sync::Once::new();
    ONCE.call_once(|| {
        let previous = std::panic::take_hook();
        std::panic::set_hook(Box::new(move |info| {
            remove_registered_bar();
            previous(info);
        }));
    });
}

/// `ABM_REMOVE` for the window that holds a registration, if any. Safe to call from any thread and more than once.
fn remove_registered_bar() {
    let h = BAR_WINDOW.swap(0, Ordering::SeqCst);
    if h != 0 {
        let mut d = bar_data(windows::Win32::Foundation::HWND(h as *mut _));
        unsafe { windows::Win32::UI::Shell::SHAppBarMessage(windows::Win32::UI::Shell::ABM_REMOVE, &mut d) };
    }
    // (try_lock: the hook may run on the thread that holds the list)
    let others = OTHER_BAR_WINDOWS.try_lock().map(|mut g| std::mem::take(&mut *g)).unwrap_or_default();
    for h in others {
        let mut d = bar_data(windows::Win32::Foundation::HWND(h as *mut _));
        unsafe { windows::Win32::UI::Shell::SHAppBarMessage(windows::Win32::UI::Shell::ABM_REMOVE, &mut d) };
    }
}

/// The id of the broadcast message Explorer sends every top-level window when its taskbar is (re)created: after it crashed or was
/// restarted it has forgotten every application toolbar.
fn taskbar_created() -> u32 {
    static ID: std::sync::OnceLock<u32> = std::sync::OnceLock::new();
    *ID.get_or_init(|| unsafe { windows::Win32::UI::WindowsAndMessaging::RegisterWindowMessageW(windows::core::w!("TaskbarCreated")) })
}

// ---------------------------------------------------------------- the toolbar messages, straight to Explorer
//
// WHY NOT `SHAppBarMessage`. It sends to the FIRST window of class `Shell_TrayWnd`, and while the tray host runs that window is ours,
// in this very process; the host passes every message on to Explorer. For the messages that ask for an answer (`ABM_QUERYPOS`,
// `ABM_SETPOS`) that did not work from this process: measured on 2026-12-04, they came back at once with the rectangle that was sent and
// Explorer changed nothing (a band registered above the visible taskbar stayed there when the taskbar hid itself: 48 px of nothing above
// the dock; a changed thickness was never taken). The same calls from another program through the same host worked, and so did the
// dock's own when a relay of ANOTHER process stood in front. Why this process's are lost was not found (shell32 allocates the answer's
// memory in the process that owns the window it found, which here is the sender itself). So the dock does not go through its own
// window: it builds the request as shell32 does (`tray_wire::appbar`) and sends it to Explorer's own taskbar window, with a time limit
// (shell32 waits for ever, and this thread must be able to end).

thread_local! {
    /// Explorer's own taskbar window and its process, as last found (looked up again when the window is no longer that process's).
    static EXPLORER_TRAY: std::cell::Cell<Option<(isize, u32)>> = const { std::cell::Cell::new(None) };
}

/// How long one toolbar message may take. Explorer answers in a millisecond or two; one that hangs must not hold the dock's thread.
const BAR_SEND_MS: u32 = 4000;

fn explorer_tray() -> Option<(isize, u32)> {
    use windows::Win32::Foundation::HWND;
    use windows::Win32::UI::WindowsAndMessaging::GetWindowThreadProcessId;
    if let Some((hwnd, pid)) = EXPLORER_TRAY.with(std::cell::Cell::get) {
        let mut now = 0u32;
        // SAFETY: reads the owner of a window handle; a handle that is gone gives 0.
        if unsafe { GetWindowThreadProcessId(HWND(hwnd as *mut _), Some(&mut now)) } != 0 && now == pid {
            return Some((hwnd, pid));
        }
    }
    let found = explorer_tray_id().map(|t| (t.hwnd, t.pid));
    EXPLORER_TRAY.with(|c| c.set(found));
    found
}

/// Whether Explorer on this Windows answers a request built here (0: not asked yet, 1: yes, 2: no). The layout of the request is read
/// from Windows 11; a Windows that does not understand it must not lose the dock's band, so the first use asks a question that
/// changes nothing (where the taskbar is) and looks at the answer.
static DIRECT: std::sync::atomic::AtomicU8 = std::sync::atomic::AtomicU8::new(0);

/// A taskbar rectangle that can be one: not empty.
fn sane_taskbar_rect(rc: &windows::Win32::Foundation::RECT) -> bool {
    rc.right > rc.left && rc.bottom > rc.top
}

fn direct_works(tray: isize, pid: u32) -> bool {
    match DIRECT.load(Ordering::Relaxed) {
        1 => return true,
        2 => return false,
        _ => {}
    }
    let mut d = windows::Win32::UI::Shell::APPBARDATA { cbSize: size_of::<windows::Win32::UI::Shell::APPBARDATA>() as u32, ..Default::default() };
    // SAFETY: a read-only question; `d` is ours.
    let answer = unsafe { send_to_explorer(tray, pid, windows::Win32::UI::Shell::ABM_GETTASKBARPOS, &mut d) };
    let ok = answer != 0 && sane_taskbar_rect(&d.rc);
    if !ok {
        log::warn!("dock: Explorer did not answer a toolbar message sent to it directly on this Windows; shell32's own call is used");
    }
    DIRECT.store(if ok { 1 } else { 2 }, Ordering::Relaxed);
    ok
}

/// One toolbar message for the window in `d`; `d` takes the answer of the messages that have one. The return value is Explorer's
/// (0: refused, not delivered in time, or no answer could be read). Sent to Explorer's own taskbar window when there is one and this
/// Windows answers such a request ([`direct_works`]); otherwise the call is shell32's own, as before.
unsafe fn bar_message(msg: u32, d: &mut windows::Win32::UI::Shell::APPBARDATA) -> usize {
    match explorer_tray() {
        Some((tray, pid)) if direct_works(tray, pid) => unsafe { send_to_explorer(tray, pid, msg, d) },
        _ => unsafe { windows::Win32::UI::Shell::SHAppBarMessage(msg, d) },
    }
}

/// The request as shell32 builds it, to the taskbar window `tray` of process `pid`.
unsafe fn send_to_explorer(tray: isize, pid: u32, msg: u32, d: &mut windows::Win32::UI::Shell::APPBARDATA) -> usize {
    use crate::tray_wire::appbar::{ABD_LEN, AbMessage, AppBarLayout, AppBarRequest, reply};
    use windows::Win32::Foundation::{HWND, LPARAM, WPARAM};
    use windows::Win32::System::DataExchange::COPYDATASTRUCT;
    use windows::Win32::UI::Shell::{ABM_GETTASKBARPOS, ABM_QUERYPOS, ABM_SETPOS, SHAllocShared, SHFreeShared, SHLockShared, SHUnlockShared};
    use windows::Win32::UI::WindowsAndMessaging::{SMTO_ABORTIFHUNG, SendMessageTimeoutW, WM_COPYDATA};
    let mut req = AppBarRequest {
        layout: AppBarLayout::V3,
        abd_cb_size: ABD_LEN as u32,
        hwnd: d.hWnd.0 as usize as u32,
        callback_message: d.uCallbackMessage,
        edge: d.uEdge,
        rect: crate::tray_wire::Rect { left: d.rc.left, top: d.rc.top, right: d.rc.right, bottom: d.rc.bottom },
        lparam: d.lParam.0 as i64,
        message: AbMessage::from_u32(msg),
        shared_memory: 0,
        // (the process that owns the tray window, as shell32 writes it: the memory for the answer is allocated there)
        source_pid: pid,
        trailing_len: 0,
    };
    let wants_answer = matches!(msg, ABM_QUERYPOS | ABM_SETPOS | ABM_GETTASKBARPOS);
    let shared = if wants_answer {
        let abd = req.encode();
        // SAFETY: `abd` holds at least ABD_LEN bytes; the function copies them into a block of Explorer's.
        let h = unsafe { SHAllocShared(Some(abd.as_ptr() as *const _), ABD_LEN as u32, pid) };
        if h.is_invalid() {
            return 0;
        }
        req.shared_memory = h.0 as isize as i64;
        Some(h)
    } else {
        None
    };
    let block = req.encode();
    let cds = COPYDATASTRUCT { dwData: crate::tray_wire::DW_APPBAR, cbData: block.len() as u32, lpData: block.as_ptr() as *mut _ };
    let mut answer = 0usize;
    // SAFETY: `cds` and `block` live until the call returns; the system copies them for the receiver.
    let sent = unsafe { SendMessageTimeoutW(HWND(tray as *mut _), WM_COPYDATA, WPARAM(d.hWnd.0 as usize), LPARAM(&cds as *const _ as isize), SMTO_ABORTIFHUNG, BAR_SEND_MS, Some(&mut answer)) };
    if let Some(h) = shared {
        if sent.0 != 0 {
            // SAFETY: the block was made above with ABD_LEN bytes; it is read while locked and given back.
            unsafe {
                let p = SHLockShared(h, pid);
                if p.is_null() {
                    answer = 0;
                } else {
                    if let Some((edge, rc)) = reply(std::slice::from_raw_parts(p as *const u8, ABD_LEN)) {
                        d.uEdge = edge;
                        d.rc = windows::Win32::Foundation::RECT { left: rc.left, top: rc.top, right: rc.right, bottom: rc.bottom };
                    }
                    let _ = SHUnlockShared(p);
                }
            }
        }
        // SAFETY: frees the block made above (also when Explorer did not answer: it cannot write into it later).
        unsafe {
            let _ = SHFreeShared(h, pid);
        }
    }
    if sent.0 == 0 {
        log::warn!("dock: Explorer did not take a toolbar message ({}) in {BAR_SEND_MS} ms", AbMessage::from_u32(msg).name());
        EXPLORER_TRAY.with(|c| c.set(None));
        return 0;
    }
    answer
}

/// The toolbar message block of `SHAppBarMessage`, for this window.
fn bar_data(hwnd: windows::Win32::Foundation::HWND) -> windows::Win32::UI::Shell::APPBARDATA {
    windows::Win32::UI::Shell::APPBARDATA { cbSize: size_of::<windows::Win32::UI::Shell::APPBARDATA>() as u32, hWnd: hwnd, uCallbackMessage: WM_BAR, ..Default::default() }
}

/// The real toolbar calls: messages to Explorer's taskbar window (`SHAppBarMessage`), for this window.
struct RealBar {
    hwnd: windows::Win32::Foundation::HWND,
    edge: DockEdge,
    /// The band of a dock on another monitor (its window is kept in the list of those, not as the home dock's).
    other: bool,
}

impl RealBar {
    fn home(hwnd: windows::Win32::Foundation::HWND, edge: DockEdge) -> RealBar {
        RealBar { hwnd, edge, other: false }
    }

    fn note(&self, held: bool) {
        let h = self.hwnd.0 as isize;
        if self.other {
            let mut g = OTHER_BAR_WINDOWS.lock().unwrap_or_else(|p| p.into_inner());
            g.retain(|x| *x != h);
            if held {
                g.push(h);
            }
        } else {
            BAR_WINDOW.store(if held { h } else { 0 }, Ordering::SeqCst);
        }
    }
}

impl AppBarCalls for RealBar {
    fn register(&mut self) -> bool {
        let mut d = bar_data(self.hwnd);
        if unsafe { bar_message(windows::Win32::UI::Shell::ABM_NEW, &mut d) } == 0 {
            return false;
        }
        self.note(true);
        true
    }

    fn query(&mut self, edge: Rect) -> Rect {
        let mut d = bar_data(self.hwnd);
        d.uEdge = match self.edge {
            DockEdge::Bottom => windows::Win32::UI::Shell::ABE_BOTTOM,
            DockEdge::Right => windows::Win32::UI::Shell::ABE_RIGHT,
        };
        d.rc = windows::Win32::Foundation::RECT { left: edge.left, top: edge.top, right: edge.right, bottom: edge.bottom };
        unsafe { bar_message(windows::Win32::UI::Shell::ABM_QUERYPOS, &mut d) };
        rect_of(d.rc)
    }

    fn set_pos(&mut self, rc: Rect) {
        let mut d = bar_data(self.hwnd);
        d.uEdge = match self.edge {
            DockEdge::Bottom => windows::Win32::UI::Shell::ABE_BOTTOM,
            DockEdge::Right => windows::Win32::UI::Shell::ABE_RIGHT,
        };
        d.rc = windows::Win32::Foundation::RECT { left: rc.left, top: rc.top, right: rc.right, bottom: rc.bottom };
        unsafe { bar_message(windows::Win32::UI::Shell::ABM_SETPOS, &mut d) };
    }

    fn remove(&mut self) {
        let mut d = bar_data(self.hwnd);
        unsafe { bar_message(windows::Win32::UI::Shell::ABM_REMOVE, &mut d) };
        self.note(false);
    }
}

/// Brings the band in line with what the app wants (see `band.rs` for the rules) and tells the app when it changed.
unsafe fn apply_reservation(hwnd: windows::Win32::Foundation::HWND, ctx: &mut Ctx) {
    use windows::Win32::UI::WindowsAndMessaging::SetTimer;
    // While the host owns the bottom edge no band is registered (the host sets the work area itself): the wish is "none".
    let (want, edge) = {
        let shared = ctx.shared();
        (if APPBAR_SUPPRESSED.load(Ordering::SeqCst) { None } else { shared.want }, shared.edge)
    };
    let view = primary_monitor().map(|m| (m.rect, m.work));
    let applied = ctx.band.apply_on(&mut RealBar::home(hwnd, edge), want, view, edge);
    APPBAR_HELD.store(ctx.band.registered(), Ordering::SeqCst);
    if !ctx.band.registered() {
        ctx.tray_at_registration = None;
        let stale = ctx.shared().band.take().is_some();
        if stale && applied != Applied::Released {
            ctx.emit(SystemEvent::LayoutChanged);
        }
    }
    match applied {
        Applied::Set(granted) => {
            ctx.register_tries = 0;
            if ctx.tray_at_registration.is_none() {
                ctx.tray_at_registration = explorer_tray_id();
            }
            ctx.shared().band = Some(granted);
            log::debug!("dock: reserved {granted:?}");
            ctx.emit(SystemEvent::LayoutChanged);
        }
        Applied::Released => {
            ctx.shared().band = None;
            ctx.emit(SystemEvent::LayoutChanged);
        }
        Applied::RegisterFailed => {
            ctx.register_tries += 1;
            if ctx.register_tries < MAX_REGISTER_TRIES {
                log::debug!("dock: the desktop toolbar was refused (try {}), again in {RETRY_MS} ms", ctx.register_tries);
                unsafe { SetTimer(Some(hwnd), TIMER_RETRY, RETRY_MS, None) };
            } else {
                log::warn!("dock: the desktop toolbar could not be registered ({} tries); it is tried again at the next change of the screen or of the taskbar", ctx.register_tries);
                ctx.register_tries = 0;
            }
        }
        Applied::Unchanged => {}
    }
    unsafe { apply_other_bands(hwnd, ctx, edge) };
}

/// Brings the bands of the docks on the other monitors in line with the wish ([`set_other_bands`]): a hidden window and a
/// registration for each wanted monitor that is there, none for the others. Called wherever the home band is looked at (the wish
/// changed, Explorer moved a toolbar, the screens changed, Explorer started again).
unsafe fn apply_other_bands(system: windows::Win32::Foundation::HWND, ctx: &mut Ctx, edge: DockEdge) {
    use windows::Win32::UI::WindowsAndMessaging::{DestroyWindow, SetTimer};
    // While the host owns the edges it sets these monitors' work areas itself: no band is registered.
    let want = if APPBAR_SUPPRESSED.load(Ordering::SeqCst) { Vec::new() } else { other_want() };
    if want.is_empty() && ctx.others.is_empty() {
        return;
    }
    let displays = super::monitors::displays();
    let present: Vec<String> = displays.iter().filter(|d| !d.primary).map(|d| d.name.clone()).collect();
    let held: Vec<String> = ctx.others.iter().map(|o| o.monitor.clone()).collect();
    let (go, come) = other_bands_plan(&held, &want, &present);
    for m in &go {
        if let Some(i) = ctx.others.iter().position(|o| o.monitor == *m) {
            let mut o = ctx.others.remove(i);
            let hwnd = windows::Win32::Foundation::HWND(o.hwnd as *mut _);
            o.band.apply(&mut RealBar { hwnd, edge, other: true }, None, None);
            unsafe {
                let _ = DestroyWindow(hwnd);
            }
            log::debug!("dock: the band on {m} is given back");
        }
    }
    for m in come {
        match unsafe { other_bar_window(system) } {
            Some(hwnd) => ctx.others.push(OtherBar { monitor: m, hwnd, band: Band::new() }),
            None => log::warn!("dock: no window for the band on {m}; that monitor's work area stays as it is"),
        }
    }
    let mut refused = false;
    for o in ctx.others.iter_mut() {
        let Some(thickness) = want.iter().find(|(m, _)| *m == o.monitor).map(|(_, t)| (*t).max(1)) else { continue };
        let Some(d) = displays.iter().find(|d| d.name == o.monitor) else { continue };
        let hwnd = windows::Win32::Foundation::HWND(o.hwnd as *mut _);
        match o.band.apply_on(&mut RealBar { hwnd, edge, other: true }, Some(thickness), Some((d.info.rect, d.info.work)), edge) {
            Applied::Set(granted) => log::debug!("dock: reserved {granted:?} on {}", o.monitor),
            Applied::RegisterFailed => refused = true,
            Applied::Released | Applied::Unchanged => {}
        }
    }
    if refused {
        unsafe { SetTimer(Some(system), TIMER_RETRY, RETRY_MS, None) };
    }
}

/// A hidden window for one other monitor's band. Its only work is to pass Explorer's toolbar notifications on to the system window,
/// which looks at every band then.
unsafe fn other_bar_window(system: windows::Win32::Foundation::HWND) -> Option<isize> {
    use windows::Win32::System::LibraryLoader::GetModuleHandleW;
    use windows::Win32::UI::WindowsAndMessaging::{CreateWindowExW, GWLP_USERDATA, RegisterClassExW, SetWindowLongPtrW, WNDCLASSEXW, WS_EX_NOACTIVATE, WS_EX_TOOLWINDOW, WS_POPUP};
    use windows::core::w;
    unsafe {
        let hinst = GetModuleHandleW(None).ok()?;
        let class = w!("RustyfilesDockBand");
        let wc = WNDCLASSEXW { cbSize: size_of::<WNDCLASSEXW>() as u32, lpfnWndProc: Some(other_bar_proc), hInstance: hinst.into(), lpszClassName: class, ..Default::default() };
        // (registered again for every window: that failing the second time is fine)
        RegisterClassExW(&wc);
        let hwnd = CreateWindowExW(WS_EX_TOOLWINDOW | WS_EX_NOACTIVATE, class, w!(""), WS_POPUP, 0, 0, 0, 0, None, None, Some(hinst.into()), None).ok()?;
        SetWindowLongPtrW(hwnd, GWLP_USERDATA, system.0 as isize);
        Some(hwnd.0 as isize)
    }
}

unsafe extern "system" fn other_bar_proc(hwnd: windows::Win32::Foundation::HWND, msg: u32, wp: windows::Win32::Foundation::WPARAM, lp: windows::Win32::Foundation::LPARAM) -> windows::Win32::Foundation::LRESULT {
    use windows::Win32::Foundation::{HWND, LPARAM, LRESULT, WPARAM};
    use windows::Win32::UI::WindowsAndMessaging::{DefWindowProcW, GWLP_USERDATA, GetWindowLongPtrW, PostMessageW};
    unsafe {
        // ABN_STATECHANGE 0, ABN_POSCHANGED 1: the taskbar or another toolbar changed. Posted, not sent: Explorer waits for this answer.
        if msg == WM_BAR && wp.0 <= 1 {
            let system = GetWindowLongPtrW(hwnd, GWLP_USERDATA);
            if system != 0 {
                let _ = PostMessageW(Some(HWND(system as *mut _)), WM_RESERVE, WPARAM(0), LPARAM(0));
            }
            return LRESULT(0);
        }
        DefWindowProcW(hwnd, msg, wp, lp)
    }
}

/// Explorer's own taskbar window right now (the one of class `Shell_TrayWnd` that Explorer owns): handle, owner, the owner's start
/// time. `None` when there is none or it cannot be told. A look through the list of windows, made only when an announcement or a
/// registration needs it.
fn explorer_tray_id() -> Option<TrayId> {
    let live = rf_shellguard::win::tbwin::list_taskbar_windows().ok()?;
    live.iter().find(|w| w.class == rf_shellguard::tbmodel::PRIMARY && w.explorer && w.start != 0).map(|w| TrayId { hwnd: w.handle, pid: w.pid, start: w.start })
}

/// The 2 s tick and the taskbar announcement ask the shell watch whether the shell window is another one; the app is told when it is.
fn watch_shell(ctx: &mut Ctx, cause: Cause) {
    let now = ctx.started.elapsed().as_millis() as u64;
    if let Seen::Changed { mode, mode_changed } = ctx.shell.check(&SystemLook, now, cause) {
        log::info!("shell host: the shell window changed, mode {}{}", mode.name(), if mode_changed { " (the mode changed)" } else { "" });
        ctx.emit(SystemEvent::ShellChanged(mode));
    }
}

fn run(ctx: Box<Ctx>, tx: std::sync::mpsc::Sender<Result<isize, String>>) {
    use windows::Win32::System::LibraryLoader::GetModuleHandleW;
    use windows::Win32::UI::WindowsAndMessaging::{
        CreateWindowExW, DispatchMessageW, GetMessageW, MSG, RegisterClassExW, SetTimer, TranslateMessage, WNDCLASSEXW, WS_EX_NOACTIVATE, WS_EX_TOOLWINDOW, WS_POPUP,
    };
    use windows::core::w;
    unsafe {
        let hinst = match GetModuleHandleW(None) {
            Ok(h) => h,
            Err(e) => {
                let _ = tx.send(Err(format!("module handle: {e}")));
                return;
            }
        };
        let class = w!("RustyfilesDockSystem");
        let wc = WNDCLASSEXW { cbSize: size_of::<WNDCLASSEXW>() as u32, lpfnWndProc: Some(wndproc), hInstance: hinst.into(), lpszClassName: class, ..Default::default() };
        // a second DockSystem in the same process registers the same class again: that failing is fine
        RegisterClassExW(&wc);
        let raw = Box::into_raw(ctx);
        let hwnd = CreateWindowExW(WS_EX_TOOLWINDOW | WS_EX_NOACTIVATE, class, w!(""), WS_POPUP, 0, 0, 0, 0, None, None, Some(hinst.into()), Some(raw as *const _));
        let hwnd = match hwnd {
            Ok(h) => h,
            Err(e) => {
                drop(Box::from_raw(raw));
                let _ = tx.send(Err(format!("the dock's system window: {e}")));
                return;
            }
        };
        SetTimer(Some(hwnd), TIMER_POLL, POLL_MS, None);
        SYSTEM_WINDOW.store(hwnd.0 as isize, Ordering::SeqCst);
        let _ = tx.send(Ok(hwnd.0 as isize));
        let mut msg = MSG::default();
        while GetMessageW(&mut msg, None, 0, 0).as_bool() {
            let _ = TranslateMessage(&msg);
            DispatchMessageW(&msg);
        }
    }
}

unsafe extern "system" fn wndproc(hwnd: windows::Win32::Foundation::HWND, msg: u32, wp: windows::Win32::Foundation::WPARAM, lp: windows::Win32::Foundation::LPARAM) -> windows::Win32::Foundation::LRESULT {
    use windows::Win32::Foundation::LRESULT;
    use windows::Win32::UI::WindowsAndMessaging::{
        CREATESTRUCTW, DefWindowProcW, DestroyWindow, GWLP_USERDATA, GetWindowLongPtrW, KillTimer, PostQuitMessage, SetTimer, SetWindowLongPtrW, WM_CLOSE, WM_DESTROY,
        WM_DISPLAYCHANGE, WM_ENDSESSION, WM_NCCREATE, WM_POWERBROADCAST, WM_SETTINGCHANGE, WM_THEMECHANGED, WM_TIMECHANGE, WM_TIMER,
    };
    // WM_DWMCOLORIZATIONCOLORCHANGED
    const WM_DWM_COLOR: u32 = 0x0320;
    // PBT_APMRESUMEAUTOMATIC
    const PBT_RESUME: usize = 0x0012;
    const SPI_SETWORKAREA: usize = 0x002F;

    unsafe {
        if msg == WM_NCCREATE {
            let cs = &*(lp.0 as *const CREATESTRUCTW);
            SetWindowLongPtrW(hwnd, GWLP_USERDATA, cs.lpCreateParams as isize);
            return DefWindowProcW(hwnd, msg, wp, lp);
        }
        let ptr = GetWindowLongPtrW(hwnd, GWLP_USERDATA) as *mut Ctx;
        if ptr.is_null() {
            return DefWindowProcW(hwnd, msg, wp, lp);
        }
        if msg == WM_DESTROY {
            // the last message: free the state, end the loop
            let mut ctx = Box::from_raw(ptr);
            SetWindowLongPtrW(hwnd, GWLP_USERDATA, 0);
            // (the band is given back: want None)
            SYSTEM_WINDOW.store(0, Ordering::SeqCst);
            ctx.band.apply(&mut RealBar::home(hwnd, DockEdge::Bottom), None, None);
            for mut o in std::mem::take(&mut ctx.others) {
                let other = windows::Win32::Foundation::HWND(o.hwnd as *mut _);
                o.band.apply(&mut RealBar { hwnd: other, edge: DockEdge::Bottom, other: true }, None, None);
                let _ = DestroyWindow(other);
            }
            APPBAR_HELD.store(false, Ordering::SeqCst);
            ctx.shared().band = None;
            drop(ctx);
            PostQuitMessage(0);
            return LRESULT(0);
        }
        let ctx = &mut *ptr;
        let schedule_layout = |ctx: &mut Ctx| {
            if !ctx.layout_pending {
                ctx.layout_pending = true;
                SetTimer(Some(hwnd), TIMER_DEBOUNCE, DEBOUNCE_MS, None);
            }
        };
        if msg == taskbar_created() {
            // Explorer started again and knows nothing of our toolbar: register anew. The granted band is the same rectangle as
            // before, so forget it, or the new registration would be skipped as "unchanged". (Not every announcement is a restart - our
            // own tray host broadcasts it too - so `Band` gives a registration that is still held back first. BAR_WINDOW is left as it
            // is: it names the window that may hold a registration, which the panic hook gives back.)
            //
            // A broadcast that is not a restart (our own tray host sends one when it starts and stops) leaves the registration alone:
            // Explorer's taskbar window is provably the same one (see `announcement_is_restart`).
            let registered = ctx.band.registered();
            let restart = announcement_is_restart(registered, ctx.tray_at_registration, if registered { explorer_tray_id() } else { None });
            if restart {
                ctx.band.announced();
                for o in ctx.others.iter_mut() {
                    o.band.announced();
                }
                ctx.tray_at_registration = None;
                ctx.register_tries = 0;
                ctx.shared().band = None;
                apply_reservation(hwnd, ctx);
                schedule_layout(ctx);
            } else {
                log::debug!("dock: TaskbarCreated from another program; Explorer's taskbar is the same one, the band stays");
            }
            // (and the shell window is looked at: it is new, and the parts that depend on it - the desktop, the band - are told)
            watch_shell(ctx, Cause::Announced);
            return LRESULT(0);
        }
        match msg {
            WM_RESERVE => {
                apply_reservation(hwnd, ctx);
                // the host took or gave back the bottom edge (beside Explorer, or by itself with no shell: the own band): the islands are
                // placed again (from the edge, or from the work area)
                let edge = (APPBAR_SUPPRESSED.load(Ordering::SeqCst), edge_band(), own_band());
                if edge != ctx.edge_seen {
                    ctx.edge_seen = edge;
                    ctx.emit(SystemEvent::LayoutChanged);
                }
                LRESULT(0)
            }
            WM_BAR => {
                // ABN_STATECHANGE 0, ABN_POSCHANGED 1: the Windows taskbar or another toolbar changed, ask again where the band may go
                // ABN_FULLSCREENAPP 2: look at the window in front now
                match wp.0 {
                    0 | 1 => {
                        apply_reservation(hwnd, ctx);
                        schedule_layout(ctx);
                    }
                    2 => check_fullscreen(ctx),
                    _ => {}
                }
                LRESULT(0)
            }
            WM_DISPLAYCHANGE => {
                schedule_layout(ctx);
                LRESULT(0)
            }
            WM_SETTINGCHANGE => {
                if wp.0 == SPI_SETWORKAREA {
                    schedule_layout(ctx);
                } else if wp.0 == 0 && lp.0 != 0 {
                    // a named setting: "ImmersiveColorSet" is the theme or the accent, "TraySettings" the Windows taskbar's own
                    let name = windows::core::PCWSTR(lp.0 as *const u16).to_string().unwrap_or_default();
                    match name.as_str() {
                        "ImmersiveColorSet" => ctx.emit(SystemEvent::ThemeChanged),
                        "TraySettings" | "WindowMetrics" => schedule_layout(ctx),
                        _ => {}
                    }
                }
                DefWindowProcW(hwnd, msg, wp, lp)
            }
            WM_THEMECHANGED | WM_DWM_COLOR => {
                ctx.emit(SystemEvent::ThemeChanged);
                DefWindowProcW(hwnd, msg, wp, lp)
            }
            WM_TIMECHANGE => {
                ctx.emit(SystemEvent::TimeChanged);
                LRESULT(0)
            }
            WM_POWERBROADCAST => {
                if wp.0 == PBT_RESUME {
                    ctx.emit(SystemEvent::TimeChanged);
                    schedule_layout(ctx);
                }
                LRESULT(1) // TRUE: the request is granted
            }
            WM_TIMER => {
                match wp.0 {
                    TIMER_DEBOUNCE => {
                        let _ = KillTimer(Some(hwnd), TIMER_DEBOUNCE);
                        ctx.layout_pending = false;
                        // the band depends on the monitor (its size, the taskbar's place): ask again, then tell the app
                        apply_reservation(hwnd, ctx);
                        ctx.last_monitor = primary_monitor();
                        ctx.emit(SystemEvent::LayoutChanged);
                    }
                    TIMER_RETRY => {
                        let _ = KillTimer(Some(hwnd), TIMER_RETRY);
                        apply_reservation(hwnd, ctx);
                    }
                    TIMER_POLL => {
                        check_fullscreen(ctx);
                        ctx.ticks = ctx.ticks.wrapping_add(1);
                        // every 2 s: a DPI change does not always come with a message to a window that is not shown
                        if ctx.ticks.is_multiple_of(4) {
                            // (one GetShellWindow call; see shellhost/watch.rs)
                            watch_shell(ctx, Cause::Tick);
                            let now = primary_monitor();
                            if now != ctx.last_monitor && !ctx.layout_pending {
                                ctx.last_monitor = now;
                                schedule_layout(ctx);
                            }
                            // the other monitors (a DPI change of one of them is not told to this window): only with docks on them
                            if WATCH_ALL.load(Ordering::Relaxed) {
                                let all: Vec<MonitorInfo> = super::monitors::displays().into_iter().map(|d| d.info).collect();
                                if all != ctx.last_all {
                                    let first = ctx.last_all.is_empty();
                                    ctx.last_all = all;
                                    if !first && !ctx.layout_pending {
                                        schedule_layout(ctx);
                                    }
                                }
                            } else if !ctx.last_all.is_empty() {
                                ctx.last_all.clear();
                            }
                        }
                    }
                    _ => {}
                }
                LRESULT(0)
            }
            WM_ENDSESSION => {
                if wp.0 != 0 {
                    // (written to the log so that a dock that ends with the session says why)
                    log::warn!("shell host exits: the session is ending");
                    ctx.band.apply(&mut RealBar::home(hwnd, DockEdge::Bottom), None, None);
                    for o in ctx.others.iter_mut() {
                        let other = windows::Win32::Foundation::HWND(o.hwnd as *mut _);
                        o.band.apply(&mut RealBar { hwnd: other, edge: DockEdge::Bottom, other: true }, None, None);
                    }
                }
                LRESULT(0)
            }
            WM_CLOSE => {
                let _ = DestroyWindow(hwnd);
                LRESULT(0)
            }
            _ => DefWindowProcW(hwnd, msg, wp, lp),
        }
    }
}

fn check_fullscreen(ctx: &mut Ctx) {
    let now = super::fullscreen::on_primary();
    if ctx.fullscreen.swap(now, Ordering::Relaxed) != now {
        ctx.emit(SystemEvent::Fullscreen(now));
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn the_primary_monitor_is_readable() {
        // read-only: this machine has a display (the suite needs a desktop session anyway)
        let m = primary_monitor().expect("a primary monitor");
        assert!(m.rect.width() > 0 && m.rect.height() > 0);
        assert!(m.rect.covers(&m.work), "{m:?}");
        assert!(m.dpi >= 96 || m.dpi > 0);
        assert!(m.scale() > 0.5);
    }

    /// The statics are the process's: this is the only test that touches them. There is no system window here (the id is 0), so
    /// nothing is posted and nothing reaches Explorer.
    #[test]
    fn taking_the_edge_suppresses_the_registration_and_giving_it_back_registers_again_and_is_safe_twice() {
        assert!(!APPBAR_SUPPRESSED.load(Ordering::SeqCst) && edge_band().is_none() && !appbar_held(), "nothing is taken at the start");
        let strip = Rect::new(0, 1362, 2560, 1440);
        take_edge(strip);
        assert!(APPBAR_SUPPRESSED.load(Ordering::SeqCst), "the registration is not to be held");
        assert_eq!(edge_band(), Some(strip), "the placement works from the monitor's bottom edge");
        // telling again only moves the strip
        let thinner = Rect::new(0, 1348, 2560, 1440);
        take_edge(thinner);
        assert_eq!(edge_band(), Some(thinner));
        give_back_edge();
        assert!(!APPBAR_SUPPRESSED.load(Ordering::SeqCst) && edge_band().is_none());
        give_back_edge();
        assert!(!APPBAR_SUPPRESSED.load(Ordering::SeqCst) && edge_band().is_none(), "a second give-back changes nothing");
        // (with no system window the held flag is simply false: the host's wait for the dock to let go ends at once)
        assert!(!appbar_held());
    }

    #[test]
    fn only_a_rectangle_that_is_one_counts_as_the_taskbars_answer() {
        use windows::Win32::Foundation::RECT;
        assert!(sane_taskbar_rect(&RECT { left: 0, top: 1392, right: 2560, bottom: 1440 }));
        assert!(sane_taskbar_rect(&RECT { left: -1440, top: 2311, right: 0, bottom: 2359 }), "a monitor to the left");
        assert!(!sane_taskbar_rect(&RECT::default()), "what comes back when nothing was written");
        assert!(!sane_taskbar_rect(&RECT { left: 0, top: 1440, right: 2560, bottom: 1440 }));
    }

    #[test]
    fn the_bands_on_other_monitors_come_for_wanted_monitors_that_are_there_and_go_for_the_rest() {
        let n = |s: &str| s.to_string();
        let want = vec![(n("B"), 48), (n("C"), 48)];
        // nothing held yet: one for each wanted monitor that is plugged in
        assert_eq!(other_bands_plan(&[], &want, &[n("B"), n("C")]), (vec![], vec![n("B"), n("C")]));
        // a wanted monitor that is not there gets none
        assert_eq!(other_bands_plan(&[], &want, &[n("B")]), (vec![], vec![n("B")]));
        // held and still wanted: nothing to do
        assert_eq!(other_bands_plan(&[n("B"), n("C")], &want, &[n("B"), n("C")]), (vec![], vec![]));
        // a monitor that was unplugged, and one that is no longer wanted, give theirs back
        assert_eq!(other_bands_plan(&[n("B"), n("C")], &want, &[n("B")]), (vec![n("C")], vec![]));
        assert_eq!(other_bands_plan(&[n("B"), n("C")], &[(n("C"), 30)], &[n("B"), n("C")]), (vec![n("B")], vec![]));
        // the wish emptied: all go
        assert_eq!(other_bands_plan(&[n("B")], &[], &[n("B")]), (vec![n("B")], vec![]));
        // a monitor named twice in the wish gets one band
        assert_eq!(other_bands_plan(&[], &[(n("B"), 48), (n("B"), 30)], &[n("B")]), (vec![], vec![n("B")]));
    }

    #[test]
    fn events_are_comparable_and_small() {
        assert_eq!(SystemEvent::Fullscreen(true), SystemEvent::Fullscreen(true));
        assert_ne!(SystemEvent::Fullscreen(true), SystemEvent::Fullscreen(false));
        assert!(size_of::<SystemEvent>() <= 2);
    }
}