rustimal 0.8.0

A minimal, GPU-rendered terminal for Windows that runs Git Bash, with animated split panes and a glass look
//! Another program's window, made a child of rustimal's and laid over a pane.

use super::*;
use crate::platform::win32::GetForegroundWindow;

pub(super) const GWL_STYLE: i32 = -16;

pub(super) const GWL_EXSTYLE: i32 = -20;

pub(super) const GWLP_HWNDPARENT: i32 = -8;

pub(super) const GW_OWNER: u32 = 4;

pub(super) const GA_ROOT: u32 = 2;

pub(super) const WS_POPUP: isize = 0x8000_0000u32 as i32 as isize;

pub(super) const WS_CHILD: isize = 0x4000_0000;

pub(super) const WS_CLIPSIBLINGS: isize = 0x0400_0000;

pub(super) const WS_CAPTION: isize = 0x00C0_0000;

pub(super) const WS_THICKFRAME: isize = 0x0004_0000;

pub(super) const WS_SYSMENU: isize = 0x0008_0000;

pub(super) const WS_MINIMIZEBOX: isize = 0x0002_0000;

pub(super) const WS_MAXIMIZEBOX: isize = 0x0001_0000;

pub(super) const WS_EX_DLGMODALFRAME: isize = 0x0000_0001;

pub(super) const WS_EX_WINDOWEDGE: isize = 0x0000_0100;

pub(super) const WS_EX_CLIENTEDGE: isize = 0x0000_0200;

pub(super) const WS_EX_TOOLWINDOW: isize = 0x0000_0080;

pub(super) const WS_EX_APPWINDOW: isize = 0x0004_0000;

pub(super) const WS_EX_STATICEDGE: isize = 0x0002_0000;

pub(super) const WS_EX_NOACTIVATE: isize = 0x0800_0000;

pub(super) const SWP_NOZORDER: u32 = 0x0004;

pub(super) const SWP_NOACTIVATE: u32 = 0x0010;

pub(super) const SWP_FRAMECHANGED: u32 = 0x0020;

pub(super) const SWP_ASYNCWINDOWPOS: u32 = 0x4000;

pub(super) const SW_HIDE: i32 = 0;

pub(super) const SW_SHOWNA: i32 = 8;

pub(super) const SW_RESTORE: i32 = 9;

pub(super) const WM_CLOSE: u32 = 0x0010;

pub(super) const RDW_INVALIDATE: u32 = 0x0001;

pub(super) const RDW_ERASE: u32 = 0x0004;

pub(super) const RDW_FRAME: u32 = 0x0400;

pub(super) const RDW_ALLCHILDREN: u32 = 0x0080;

/// How a program's window is held in a pane.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Mode {
    /// A child of rustimal's window. Programs that draw with GDI or WPF show nothing as a
    /// child of the see-through (glass) window, which has no bitmap for them to draw in;
    /// every other kind of window does.
    Child,
    /// A window of its own, owned by rustimal's: it stays over it, goes where it goes and is
    /// hidden with it, and any program draws in it as it would anywhere.
    Owned,
}

/// Another program's window, laid over a pane.
pub struct Window {
    pub hwnd: Hwnd,
    parent: Hwnd,
    mode: Mode,
}

impl Window {
    /// Take `hwnd` into `parent` (rustimal's window), frameless, in the way `mode` says.
    pub fn adopt(hwnd: Hwnd, parent: Hwnd, mode: Mode) -> Window {
        if mode == Mode::Owned {
            return Self::own(hwnd, parent);
        }
        // SAFETY: plain window calls on handles that may be gone; each just fails then.
        unsafe {
            if IsZoomed(hwnd) != 0 {
                ShowWindow(hwnd, SW_RESTORE);
            }
            let style = GetWindowLongPtrW(hwnd, GWL_STYLE);
            let style = style & !(WS_CAPTION | WS_THICKFRAME | WS_SYSMENU | WS_MINIMIZEBOX | WS_MAXIMIZEBOX | WS_POPUP);
            // Before `SetParent`, as its documentation says for a window made a child.
            SetWindowLongPtrW(hwnd, GWL_STYLE, style | WS_CHILD | WS_CLIPSIBLINGS);
            let ex = GetWindowLongPtrW(hwnd, GWL_EXSTYLE);
            let ex =
                ex & !(WS_EX_DLGMODALFRAME | WS_EX_WINDOWEDGE | WS_EX_CLIENTEDGE | WS_EX_APPWINDOW | WS_EX_STATICEDGE);
            SetWindowLongPtrW(hwnd, GWL_EXSTYLE, ex);
            SetParent(hwnd, parent);
            SetWindowPos(hwnd, 0, 0, 0, 0, 0, SWP_NOZORDER | SWP_NOACTIVATE | SWP_FRAMECHANGED | 0x0001 | 0x0002);
        }
        // SAFETY: only reads.
        unsafe {
            log::debug!(
                "adopted {hwnd:#x} into {parent:#x}: parent now {:#x}, style {:#x}",
                GetParent(hwnd),
                GetWindowLongPtrW(hwnd, GWL_STYLE)
            );
        }
        Window { hwnd, parent, mode: Mode::Child }
    }

    /// Make `hwnd` a frameless window owned by `parent`, out of the taskbar.
    fn own(hwnd: Hwnd, parent: Hwnd) -> Window {
        // SAFETY: plain window calls on handles that may be gone; each just fails then.
        unsafe {
            if IsZoomed(hwnd) != 0 {
                ShowWindow(hwnd, SW_RESTORE);
            }
            let style = GetWindowLongPtrW(hwnd, GWL_STYLE);
            let style = style & !(WS_CAPTION | WS_THICKFRAME | WS_SYSMENU | WS_MINIMIZEBOX | WS_MAXIMIZEBOX | WS_CHILD);
            SetWindowLongPtrW(hwnd, GWL_STYLE, style | WS_POPUP);
            let ex = GetWindowLongPtrW(hwnd, GWL_EXSTYLE);
            let ex =
                ex & !(WS_EX_DLGMODALFRAME | WS_EX_WINDOWEDGE | WS_EX_CLIENTEDGE | WS_EX_APPWINDOW | WS_EX_STATICEDGE);
            SetWindowLongPtrW(hwnd, GWL_EXSTYLE, ex | WS_EX_TOOLWINDOW);
            // The owner of a top-level window is what `GWLP_HWNDPARENT` sets.
            SetWindowLongPtrW(hwnd, GWLP_HWNDPARENT, parent);
            SetWindowPos(hwnd, 0, 0, 0, 0, 0, SWP_NOZORDER | SWP_NOACTIVATE | SWP_FRAMECHANGED | 0x0001 | 0x0002);
        }
        Window { hwnd, parent, mode: Mode::Owned }
    }

    /// Where rustimal's client area starts on the screen, for a window that is not its child:
    /// it has to be put somewhere else when rustimal moves.
    pub fn screen_origin(&self) -> [i32; 2] {
        if self.mode == Mode::Child {
            return [0, 0];
        }
        let mut at = [0, 0];
        // SAFETY: the point is where the position goes.
        unsafe { ClientToScreen(self.parent, &mut at) };
        at
    }

    pub fn alive(&self) -> bool {
        // SAFETY: only asks about a handle.
        unsafe {
            IsWindow(self.hwnd) != 0
                && (self.mode == Mode::Owned || GetAncestor(self.hwnd, GA_ROOT) == GetAncestor(self.parent, GA_ROOT))
        }
    }

    /// `[x, y, width, height]` in the parent's pixels.
    pub fn place(&self, [x, y, w, h]: [i32; 4]) {
        // SAFETY: moves a window; fails harmlessly if it is gone.
        unsafe {
            // Asynchronously: a program that is slow to answer must not hold rustimal up while
            // a pane is being resized frame by frame.
            let [ox, oy] = self.screen_origin();
            SetWindowPos(
                self.hwnd,
                0,
                x + ox,
                y + oy,
                w.max(1),
                h.max(1),
                SWP_NOZORDER | SWP_NOACTIVATE | SWP_ASYNCWINDOWPOS,
            );
            // A program has a smallest size (a browser's is wide), and would spill over the
            // panes beside it: only the part that is the pane's is shown. The system owns
            // the region once it is given.
            SetWindowRgn(self.hwnd, CreateRectRgn(0, 0, w.max(1), h.max(1)), 0);
            // A program that was not told it was moved may not draw its new size by itself.
            RedrawWindow(self.hwnd, std::ptr::null(), 0, RDW_INVALIDATE | RDW_ERASE | RDW_FRAME | RDW_ALLCHILDREN);
        }
    }

    /// Where the window is now, as `[x, y, width, height]` in the parent's pixels. A program
    /// may move itself (to the size it had last time, say), and has to be put back.
    pub fn bounds(&self) -> Option<[i32; 4]> {
        let r = rect_of(self.hwnd)?;
        let mut corners = [r.left, r.top, r.right, r.bottom];
        // SAFETY: two points, as the count says.
        unsafe { MapWindowPoints(0, self.parent, corners.as_mut_ptr(), 2) };
        Some([corners[0], corners[1], corners[2] - corners[0], corners[3] - corners[1]])
    }

    /// Is this place on the screen inside the window?
    pub fn contains(&self, x: i32, y: i32) -> bool {
        rect_of(self.hwnd).is_some_and(|r| x >= r.left && x < r.right && y >= r.top && y < r.bottom)
    }

    pub fn show(&self, show: bool) {
        // SAFETY: as above.
        unsafe { ShowWindow(self.hwnd, if show { SW_SHOWNA } else { SW_HIDE }) };
    }

    pub fn focus(&self) {
        // SAFETY: a child shares the parent's input queue, so it may take the focus; a window
        // of its own is brought to the front, which rustimal, being in front, may do.
        unsafe {
            if self.mode == Mode::Owned {
                SetForegroundWindow(self.hwnd);
            } else {
                SetFocus(self.hwnd);
            }
        }
    }

    /// Hand the keyboard back to rustimal's own window.
    pub fn give_back(&self) {
        // SAFETY: as above.
        unsafe {
            if self.mode == Mode::Owned {
                SetForegroundWindow(self.parent);
            } else {
                SetFocus(self.parent);
            }
        }
    }

    /// Does the keyboard focus lie in this window?
    pub fn has_focus(&self) -> bool {
        // SAFETY: only asks about handles.
        unsafe {
            if self.mode == Mode::Owned {
                // The window in front, or what it opened (a menu, a dialog), which it owns.
                let mut at = GetForegroundWindow();
                for _ in 0..4 {
                    if at == 0 {
                        return false;
                    }
                    if at == self.hwnd {
                        return true;
                    }
                    at = GetWindow(at, GW_OWNER);
                }
                return false;
            }
            let at = GetFocus();
            at != 0 && (at == self.hwnd || IsChild(self.hwnd, at) != 0)
        }
    }

    /// Ask the program to close, as the close button would.
    pub fn close(&self) {
        // SAFETY: posts a message, which the program may refuse.
        unsafe { PostMessageW(self.hwnd, WM_CLOSE, 0, 0) };
    }
}