crcbl-shell 0.8.1

Crucible windowing shell: own Wayland, X11, Web/canvas and headless backends
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
//! Panels on Win32: frameless tool windows placed by their anchors.
//!
//! What each [`PanelDesc`] field becomes here:
//!
//! | field | Win32 |
//! | --- | --- |
//! | `layer` | `WS_EX_TOPMOST` for `Top` and `Overlay`, which share the one topmost band; the bottom of the z-order for `Bottom` and `Background`, which is above the desktop and no lower |
//! | `anchor`, `margins`, the size | a rectangle on the monitor, from [`geometry::panel_rect`] |
//! | `reserve` | `None` places the panel inside the monitor's work area, clear of the taskbar and every appbar; `IgnoreOthers` places it on the whole monitor; `OwnExtent` makes it an appbar — see below |
//! | `keyboard` | `None` is `WS_EX_NOACTIVATE`, and the panel is shown without activating, so clicking and hovering it leave the keyboard where it was. `OnDemand` activates on a click. `Exclusive` takes the foreground when shown, with [`FocusRefused`](crate::ShellEvent::FocusRefused) when the system refuses it; the user can click it away, so [`PANEL_EXCLUSIVE_KEYBOARD`](crate::ShellCaps::PANEL_EXCLUSIVE_KEYBOARD) is clear |
//! | `monitor` | the one asked for, else the one under the pointer |
//! | `namespace` | nothing: Win32 has no rules keyed by one |
//!
//! Every panel is `WS_EX_TOOLWINDOW`, which keeps it out of the taskbar and
//! Alt-Tab.
//!
//! # A reserving panel is an appbar
//!
//! `SHAppBarMessage` is how Windows reserves an edge: the taskbar is one, and
//! a maximised window stops at every one. [`Reserve::OwnExtent`] registers the
//! panel with `ABM_NEW`, proposes a strip of its monitor as deep as the
//! panel's extent across the edge plus its margin on it, lets `ABM_QUERYPOS`
//! move that strip clear of the taskbar and the other appbars, and reserves
//! the result with `ABM_SETPOS`. The window goes inside the strip, its margins
//! from the strip's sides. When the shell sends `ABN_POSCHANGED` — the
//! taskbar moved, another appbar came, the display changed — the panel asks
//! again. `ABM_REMOVE` gives the space back when the panel is destroyed and
//! when the shell is dropped.
//!
//! **A process that dies without `ABM_REMOVE` leaves the space reserved**
//! until Explorer restarts, and nothing here can run after a hard crash. A
//! panic unwinds through [`Drop`](Win32Shell), which removes it.
//! `docs/backlog.md` carries the crash-safe path. If the shell refuses
//! `ABM_NEW`, the panel is placed as `Reserve::None` and a warning says so.
//!
//! # Placed again when the desktop moves
//!
//! A panel's rectangle comes from its monitor's geometry, so it is computed
//! again by [`Shell::set_panel`], after `WM_DISPLAYCHANGE`, after a DPI
//! change, and after a work area moves without a display change (the taskbar
//! moved, an appbar came or went), which arrives as `WM_SETTINGCHANGE`. A
//! panel whose monitor was unplugged is asked to close; see
//! [`ShellEvent::MonitorRemoved`](crate::ShellEvent::MonitorRemoved).

use core::ptr;

use crate::{
    LogicalSize, Margins, MonitorId, MonitorInfo, PanelAnchor, PanelDesc, PanelKeyboard,
    PanelLayer, PhysicalRect, Reserve, Shell, ShellError, WindowDesc, WindowId,
};

use super::ffi::{self, AppBarData, Handle, Point, appbar, msg, style, value};
use super::geometry::{self, Insets};
use super::shell::Win32Shell;
use super::window::{Created, class_name};

/// What a panel was created with, kept so it can be placed again.
#[derive(Clone, Copy, Debug, PartialEq)]
pub(super) struct Panel {
    /// The monitor asked for. `None` was the one under the pointer when the
    /// panel was made, and is then whichever one the panel is on.
    pub monitor: Option<MonitorId>,
    pub layer: PanelLayer,
    pub anchor: PanelAnchor,
    pub reserve: Reserve,
    pub margins: Margins,
    pub keyboard: PanelKeyboard,
    /// [`WindowDesc::size`]: the size along every axis that is not
    /// stretched.
    pub size: LogicalSize,
    /// The edge [`Reserve::OwnExtent`] reserves, or `None` for a panel that
    /// reserves nothing.
    pub edge: Option<PanelAnchor>,
    /// Whether the shell accepted the panel as an appbar.
    pub appbar: bool,
}

impl Panel {
    pub(super) fn new(desc: &PanelDesc<'_>, size: LogicalSize) -> Self {
        Self {
            monitor: desc.monitor,
            layer: desc.layer,
            anchor: desc.anchor,
            reserve: desc.reserve,
            margins: desc.margins,
            keyboard: desc.keyboard,
            size,
            edge: match desc.reserve {
                Reserve::OwnExtent => desc.reserved_edge(),
                Reserve::None | Reserve::IgnoreOthers => None,
            },
            appbar: false,
        }
    }

    /// The descriptor it stands for, under `namespace`, which Win32 places
    /// nothing by and so keeps apart.
    pub(super) fn desc<'a>(&self, namespace: &'a str) -> PanelDesc<'a> {
        PanelDesc {
            namespace,
            monitor: self.monitor,
            layer: self.layer,
            anchor: self.anchor,
            reserve: self.reserve,
            margins: self.margins,
            keyboard: self.keyboard,
        }
    }

    /// How deep its appbar strip is, in pixels at `scale`: its extent across
    /// the reserved edge, plus its margin on that edge.
    fn depth(&self, edge: PanelAnchor, scale: f64) -> i32 {
        let (extent, margin) = match edge {
            PanelAnchor::BOTTOM => (self.size.height, self.margins.bottom),
            PanelAnchor::LEFT => (self.size.width, self.margins.left),
            PanelAnchor::RIGHT => (self.size.width, self.margins.right),
            _ => (self.size.height, self.margins.top),
        };
        geometry::pixels(extent, scale).saturating_add(geometry::pixels(margin, scale))
    }

    /// The insets its margins are at `scale`.
    fn insets(&self, scale: f64) -> Insets {
        Insets {
            top: geometry::pixels(self.margins.top, scale),
            right: geometry::pixels(self.margins.right, scale),
            bottom: geometry::pixels(self.margins.bottom, scale),
            left: geometry::pixels(self.margins.left, scale),
        }
    }

    /// Its rectangle on `monitor`, in desktop pixels.
    pub(super) fn rect_on(&self, monitor: &MonitorInfo) -> PhysicalRect {
        let area = match self.reserve {
            Reserve::IgnoreOthers => monitor.bounds,
            Reserve::None | Reserve::OwnExtent => monitor.work_area,
        };
        let scale = monitor.scale_factor;
        geometry::panel_rect(
            area,
            self.anchor,
            self.size.to_physical(scale),
            self.insets(scale),
        )
    }
}

impl Win32Shell {
    /// The monitor `panel` belongs on: the one it asked for, else the one
    /// under the pointer — where the user is, which is what a launcher has to
    /// open on.
    fn panel_monitor(&self, panel: &Panel) -> Option<MonitorInfo> {
        if let Some(id) = panel.monitor {
            return self.monitors.iter().find(|m| m.id == id).cloned();
        }
        let mut cursor = Point::default();
        // SAFETY: `cursor` is a live `POINT` the call writes into.
        let under = if unsafe { ffi::GetCursorPos(&raw mut cursor) } == 0 {
            None
        } else {
            // SAFETY: a pure query; the `HMONITOR` is a system-owned
            // pseudo-handle that needs no release.
            let handle =
                unsafe { ffi::MonitorFromPoint(cursor, value::MONITOR_DEFAULT_TO_NEAREST) };
            super::monitors::device_name(handle).and_then(|device| self.monitor_id_of(&device))
        };
        under
            .and_then(|id| self.monitors.iter().find(|m| m.id == id))
            .or_else(|| self.monitors.iter().find(|m| m.is_primary))
            .or_else(|| self.monitors.first())
            .cloned()
    }

    /// Creates a panel's window, placed and shown as the [module docs](self)
    /// say.
    ///
    /// # Errors
    ///
    /// [`ShellError::InvalidDescriptor`] for a title with a NUL in it, and
    /// [`ShellError::WindowCreation`] if there is no monitor to place it on or
    /// the system refused the window.
    pub(super) fn create_panel(
        &self,
        desc: &WindowDesc<'_>,
        panel: &mut Panel,
    ) -> Result<Created, ShellError> {
        let title = ffi::wide(desc.title).ok_or_else(|| {
            ShellError::InvalidDescriptor("title contains a NUL byte".to_string())
        })?;
        let monitor = self.panel_monitor(panel).ok_or_else(|| {
            ShellError::WindowCreation("there is no monitor to place a panel on".to_string())
        })?;
        let rect = panel.rect_on(&monitor);
        let styles = geometry::with_transparency(
            geometry::panel_styles(panel.layer, panel.keyboard),
            desc.transparent,
        );
        let name = class_name();
        // SAFETY: as `create_native_window`: NUL-terminated strings that
        // outlive the call, this shell's registered class, a top-level window
        // with no menu, and the `Shared` this shell owns as the parameter. The
        // window is created hidden, whatever `visible` says, so that showing it
        // is `show_panel`'s decision about activation and not the system's,
        // made by `create_window` once the window has a handle to report a
        // refused foreground against.
        let hwnd = unsafe {
            ffi::CreateWindowExW(
                styles.ex_style,
                name.as_ptr(),
                title.as_ptr(),
                styles.style,
                rect.x,
                rect.y,
                i32::try_from(rect.width).unwrap_or(i32::MAX),
                i32::try_from(rect.height).unwrap_or(i32::MAX),
                ptr::null_mut(),
                ptr::null_mut(),
                self.instance(),
                self.shared_ptr(),
            )
        };
        if hwnd.is_null() {
            // SAFETY: reads this thread's last error code.
            let error = unsafe { ffi::GetLastError() };
            return Err(ShellError::WindowCreation(format!(
                "CreateWindowExW failed with Win32 error {error}"
            )));
        }
        if let Some(edge) = panel.edge {
            panel.appbar = Self::register_appbar(hwnd);
            if panel.appbar {
                Self::place_appbar(hwnd, panel, &monitor, edge);
            }
        }
        if matches!(panel.layer, PanelLayer::Bottom | PanelLayer::Background) {
            // SAFETY: this shell's own window; `HWND_BOTTOM` is the documented
            // pseudo-handle, and the size and position are unused.
            unsafe {
                ffi::SetWindowPos(
                    hwnd,
                    value::HWND_BOTTOM as Handle,
                    0,
                    0,
                    0,
                    0,
                    value::SWP_NO_MOVE | value::SWP_NO_SIZE | value::SWP_NO_ACTIVATE,
                );
            }
        }
        Ok(Created {
            hwnd,
            dpi: Self::dpi_of(hwnd),
            size: Self::client_size_of(hwnd),
        })
    }

    /// Shows a panel: without activating it, unless it takes the keyboard
    /// outright, in which case it is also brought to the foreground.
    ///
    /// `false` when the system refused the foreground, which it does to a
    /// process the user is not working in; the caller reports it as
    /// [`FocusRefused`](crate::ShellEvent::FocusRefused). Judged by
    /// [`foreground_granted`], which asks the system who holds the foreground
    /// afterwards rather than trusting the request's answer.
    #[must_use]
    pub(super) fn show_panel(hwnd: Handle, keyboard: PanelKeyboard) -> bool {
        let command = match keyboard {
            PanelKeyboard::Exclusive => value::SW_SHOW_NORMAL,
            PanelKeyboard::None | PanelKeyboard::OnDemand => value::SW_SHOW_NO_ACTIVATE,
        };
        // SAFETY: this shell's own window; dispatches `WM_SHOWWINDOW` into the
        // window procedure synchronously, and nothing here is borrowed.
        unsafe { ffi::ShowWindow(hwnd, command) };
        if keyboard == PanelKeyboard::Exclusive {
            // SAFETY: a request about this shell's own window.
            let answered = unsafe { ffi::SetForegroundWindow(hwnd) };
            // SAFETY: no arguments; the handle is only compared.
            let foreground = unsafe { ffi::GetForegroundWindow() };
            return foreground_granted(hwnd, answered, foreground);
        }
        true
    }

    /// Places every panel again after the monitors changed, and asks each
    /// panel created for a monitor in `removed` to close.
    ///
    /// Except appbars, which the shell tells to move itself, with
    /// `ABN_POSCHANGED`. Reserving moves the work area, which arrives here as
    /// a monitor change, so an appbar placed again from here would reserve
    /// again in answer to its own reservation.
    pub(super) fn place_panels(&mut self, removed: &[MonitorId]) {
        let panels: Vec<WindowId> = self
            .windows_iter()
            .filter(|(_, window)| window.panel.is_some())
            .map(|(id, _)| id)
            .collect();
        for window in panels {
            let Ok(state) = self.window(window) else {
                continue;
            };
            let Some(panel) = state.panel else { continue };
            if panel
                .monitor
                .is_some_and(|monitor| removed.contains(&monitor))
            {
                self.close_requested(window);
                continue;
            }
            if !panel.appbar {
                self.place_panel(window);
            }
        }
    }

    /// Moves one panel to where it belongs now. The resize it causes is
    /// reported as any other, through `WM_SIZE`.
    pub(super) fn place_panel(&self, window: WindowId) {
        let Ok(state) = self.window(window) else {
            return;
        };
        let Some(panel) = state.panel else { return };
        let hwnd = state.raw();
        let monitor = match panel.monitor {
            Some(_) => self.panel_monitor(&panel),
            None => self
                .monitor_of(hwnd)
                .and_then(|id| self.monitors.iter().find(|m| m.id == id).cloned()),
        };
        let Some(monitor) = monitor else { return };
        if let (true, Some(edge)) = (panel.appbar, panel.edge) {
            Self::place_appbar(hwnd, &panel, &monitor, edge);
            return;
        }
        let rect = panel.rect_on(&monitor);
        // SAFETY: this shell's own window; the z-order is left alone, and the
        // panel is not activated by being moved.
        unsafe {
            ffi::SetWindowPos(
                hwnd,
                ptr::null_mut(),
                rect.x,
                rect.y,
                i32::try_from(rect.width).unwrap_or(i32::MAX),
                i32::try_from(rect.height).unwrap_or(i32::MAX),
                value::SWP_NO_Z_ORDER | value::SWP_NO_ACTIVATE,
            );
        }
    }

    /// Gives a panel a new size and descriptor in place, for
    /// [`Shell::set_panel`]: the styles of its new layer and keyboard, the
    /// topmost band joined or left, an appbar registered or removed as it now
    /// reserves or does not, and its place worked out again. The resize is
    /// reported as any other, through `WM_SIZE`.
    ///
    /// # Errors
    ///
    /// What [`crate::role::check_set_panel`] refuses.
    pub(super) fn reconfigure_panel(
        &mut self,
        window: WindowId,
        size: LogicalSize,
        desc: &PanelDesc<'_>,
    ) -> Result<(), ShellError> {
        let state = self.window(window)?;
        let was = state.panel.map(|panel| panel.desc(&state.panel_namespace));
        crate::role::check_set_panel(window, was, desc, self.caps(), self.backend(), |monitor| {
            self.monitor(monitor).is_some()
        })?;
        let old = state
            .panel
            .ok_or_else(|| crate::role::not_a_panel(window))?;
        let (hwnd, transparent) = (state.raw(), state.transparent);
        let mut panel = Panel::new(desc, size);
        panel.appbar = match (old.appbar, panel.edge.is_some()) {
            (true, true) => true,
            (true, false) => {
                Self::remove_appbar(hwnd);
                false
            }
            (false, true) => Self::register_appbar(hwnd),
            (false, false) => false,
        };
        let styles = geometry::with_transparency(
            geometry::panel_styles(panel.layer, panel.keyboard),
            transparent,
        );
        let was_topmost =
            geometry::panel_styles(old.layer, old.keyboard).ex_style & style::EX_TOPMOST;
        // SAFETY: reading this shell's own window's style, for the visible
        // bit, which is state and not style.
        let visible =
            unsafe { ffi::GetWindowLongPtrW(hwnd, value::GWL_STYLE) } as u32 & style::VISIBLE;
        Self::set_styles(hwnd, styles.style | visible, styles.ex_style);
        // The topmost bit is the one style `SetWindowLongPtrW` cannot change:
        // only the z-order can, so a panel changing band is moved into it.
        let (after, z_order) = if styles.ex_style & style::EX_TOPMOST == was_topmost {
            (ptr::null_mut(), value::SWP_NO_Z_ORDER)
        } else if styles.ex_style & style::EX_TOPMOST != 0 {
            (value::HWND_TOPMOST as Handle, 0)
        } else {
            (value::HWND_BOTTOM as Handle, 0)
        };
        // SAFETY: this shell's own window; the insert-after is null or a
        // documented pseudo-handle, the size and position are unused, and
        // `SWP_FRAME_CHANGED` makes the system take the styles just written.
        unsafe {
            ffi::SetWindowPos(
                hwnd,
                after,
                0,
                0,
                0,
                0,
                value::SWP_NO_MOVE
                    | value::SWP_NO_SIZE
                    | value::SWP_NO_ACTIVATE
                    | value::SWP_FRAME_CHANGED
                    | z_order,
            );
        }
        let state = self.window_mut(window)?;
        state.panel = Some(panel);
        state.requested_size = size;
        let state = self.window(window)?;
        self.refresh_limits(state);
        self.place_panel(window);
        Ok(())
    }

    /// Registers `hwnd` as an appbar, with [`msg::APP_BAR`] for its
    /// notifications. `false`, with a warning, if the shell refuses.
    fn register_appbar(hwnd: Handle) -> bool {
        let mut data = AppBarData::new(hwnd);
        data.callback_message = msg::APP_BAR;
        // SAFETY: `data` is a live, self-describing `APPBARDATA` for this
        // shell's own window.
        let registered = unsafe { ffi::SHAppBarMessage(appbar::NEW, &raw mut data) } != 0;
        if !registered {
            crcbl_core::log::warn!(
                "win32: the shell refused a reserving panel as an appbar; it reserves nothing"
            );
        }
        registered
    }

    /// Reserves an appbar's strip of `monitor` and moves the window into it;
    /// see the [module docs](self).
    fn place_appbar(hwnd: Handle, panel: &Panel, monitor: &MonitorInfo, edge: PanelAnchor) {
        let scale = monitor.scale_factor;
        let depth = panel.depth(edge, scale);
        let mut data = AppBarData::new(hwnd);
        data.edge = match edge {
            PanelAnchor::BOTTOM => appbar::EDGE_BOTTOM,
            PanelAnchor::LEFT => appbar::EDGE_LEFT,
            PanelAnchor::RIGHT => appbar::EDGE_RIGHT,
            _ => appbar::EDGE_TOP,
        };
        data.rc = geometry::with_depth(geometry::rect_from(monitor.bounds), edge, depth);
        // SAFETY: `data` is a live, self-describing `APPBARDATA` for this
        // shell's registered appbar; each call writes `data.rc`.
        unsafe {
            ffi::SHAppBarMessage(appbar::QUERY_POS, &raw mut data);
            data.rc = geometry::with_depth(data.rc, edge, depth);
            ffi::SHAppBarMessage(appbar::SET_POS, &raw mut data);
        }
        let rect = geometry::panel_rect(
            geometry::desktop_rect(data.rc),
            panel.anchor,
            panel.size.to_physical(scale),
            panel.insets(scale),
        );
        // SAFETY: this shell's own window; the z-order is left alone.
        unsafe {
            ffi::SetWindowPos(
                hwnd,
                ptr::null_mut(),
                rect.x,
                rect.y,
                i32::try_from(rect.width).unwrap_or(i32::MAX),
                i32::try_from(rect.height).unwrap_or(i32::MAX),
                value::SWP_NO_Z_ORDER | value::SWP_NO_ACTIVATE,
            );
        }
    }

    /// Gives an appbar's space back.
    pub(super) fn remove_appbar(hwnd: Handle) {
        let mut data = AppBarData::new(hwnd);
        // SAFETY: `data` is a live, self-describing `APPBARDATA` for this
        // shell's own appbar.
        unsafe { ffi::SHAppBarMessage(appbar::REMOVE, &raw mut data) };
    }
}

/// What an `ABN_*` notification asks of the appbar it went to.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(super) enum AppBarNotice {
    /// The taskbar or another appbar moved: ask for this one's place again.
    Moved,
    /// A full-screen window opened on the appbar's monitor (`true`) or the
    /// last one closed (`false`).
    FullScreenApp(bool),
}

/// Whether `SetForegroundWindow(hwnd)`, which answered `answered`, gave `hwnd`
/// the foreground, when `GetForegroundWindow` reported `foreground` after it.
///
/// Both have to say so. The answer alone is not enough: under the foreground
/// lock the call can answer success while another process keeps the
/// foreground, and the panel then never hears `Focus` or anything else. A zero
/// answer is taken at its word, as the call's documentation states it: the
/// window was not brought to the foreground.
pub(super) fn foreground_granted(hwnd: Handle, answered: ffi::Bool32, foreground: Handle) -> bool {
    answered != 0 && ptr::eq(foreground, hwnd)
}

/// Decodes the `ABN_*` code and `lParam` of an appbar's callback message, or
/// `None` for one a panel does nothing with.
pub(super) const fn appbar_notice(notification: u32, param: isize) -> Option<AppBarNotice> {
    match notification {
        appbar::POS_CHANGED => Some(AppBarNotice::Moved),
        appbar::FULL_SCREEN_APP => Some(AppBarNotice::FullScreenApp(param != 0)),
        _ => None,
    }
}

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

    /// `ABN_STATECHANGE` and `ABN_WINDOWARRANGE`, the codes a panel ignores.
    const STATE_CHANGE: u32 = 0;
    const WINDOW_ARRANGE: u32 = 3;

    /// `set_panel` compares against the descriptor a panel stands for, so
    /// it has to be the one it was made from; and a bar given a new height
    /// is placed at that height, in the same place.
    #[test]
    fn a_panel_stands_for_its_descriptor_and_is_placed_at_its_new_size() {
        let desc = PanelDesc {
            namespace: "bar",
            monitor: Some(MonitorId(7)),
            layer: PanelLayer::Overlay,
            anchor: PanelAnchor::TOP | PanelAnchor::LEFT | PanelAnchor::RIGHT,
            reserve: Reserve::IgnoreOthers,
            margins: Margins {
                top: 4.0,
                right: 0.0,
                bottom: 0.0,
                left: 2.0,
            },
            keyboard: PanelKeyboard::OnDemand,
        };
        let bar = Panel::new(&desc, LogicalSize::new(0.0, 30.0));
        assert_eq!(bar.desc("bar"), desc);

        let monitor = MonitorInfo {
            id: MonitorId(7),
            name: "DISPLAY1".to_string(),
            bounds: PhysicalRect::new(0, 0, 1920, 1080),
            work_area: PhysicalRect::new(0, 0, 1920, 1040),
            scale_factor: 1.5,
            refresh_millihertz: 60_000,
            is_primary: true,
        };
        let taller = Panel::new(&desc, LogicalSize::new(0.0, 50.0)).rect_on(&monitor);
        assert_eq!(taller, PhysicalRect::new(3, 6, 1917, 75));
        let before = bar.rect_on(&monitor);
        assert_eq!(
            (before.x, before.y, before.width),
            (taller.x, taller.y, taller.width)
        );
    }

    #[test]
    fn an_appbar_notice_is_decoded_from_its_code_and_lparam() {
        assert_eq!(
            appbar_notice(appbar::POS_CHANGED, 0),
            Some(AppBarNotice::Moved)
        );
        assert_eq!(
            appbar_notice(appbar::FULL_SCREEN_APP, 1),
            Some(AppBarNotice::FullScreenApp(true))
        );
        assert_eq!(
            appbar_notice(appbar::FULL_SCREEN_APP, 0),
            Some(AppBarNotice::FullScreenApp(false))
        );
        assert_eq!(
            appbar_notice(appbar::FULL_SCREEN_APP, -1),
            Some(AppBarNotice::FullScreenApp(true)),
            "any nonzero BOOL is TRUE"
        );
        assert_eq!(appbar_notice(STATE_CHANGE, 1), None);
        assert_eq!(appbar_notice(WINDOW_ARRANGE, 1), None);
    }

    /// **The foreground counts as granted only when the request said so and
    /// the system then names the panel as the foreground window**: a success
    /// answer while another process keeps the foreground, which is what the
    /// foreground lock does to a launcher shown from the background, is a
    /// refusal.
    #[test]
    fn the_foreground_is_granted_only_when_the_panel_holds_it_afterwards() {
        // Distinct non-null stand-ins: the decision only compares handles.
        let mut cells = [0_u8; 2];
        let panel: Handle = (&raw mut cells[0]).cast();
        let other: Handle = (&raw mut cells[1]).cast();
        let none: Handle = ptr::null_mut();

        assert!(foreground_granted(panel, 1, panel));
        assert!(
            foreground_granted(panel, -1, panel),
            "any nonzero BOOL is TRUE"
        );
        assert!(
            !foreground_granted(panel, 1, other),
            "success while another window kept the foreground"
        );
        assert!(
            !foreground_granted(panel, 1, none),
            "success with no foreground window at all"
        );
        assert!(!foreground_granted(panel, 0, other));
        assert!(
            !foreground_granted(panel, 0, panel),
            "a refusal is taken at its word"
        );
    }
}