rustimal 0.8.0

A minimal, GPU-rendered terminal for Windows that runs Git Bash, with animated split panes and a glass look
//! Other programs in a pane: a browser, a Tauri or Electron app, a native app. The shell's
//! `embed` runs one, and its window is taken in and laid over the pane, as a web view is
//! (see `web`), and Ctrl+Shift+T switches between it and the terminal, where its output is.
//! Finding and moving the window is [`crate::programs::hosted`]'s work.

use std::time::{Duration, Instant};

use winit::event_loop::ActiveEventLoop;

use super::web::{FORWARDED, forwarded_chords, view_bounds};
use super::{App, State};
use crate::config::keys::Action;
use crate::platform::win32;
use crate::programs::hosted::{Found, Keys, Mode, Watch, Window};
use crate::terminal::embeds::Embed;
use crate::terminal::layout::PaneId;

/// How often windows are looked for, and a program's window and focus are looked at.
pub(super) const TICK: Duration = Duration::from_millis(150);

struct Host {
    pane: PaneId,
    window: Window,
    /// Switched away from.
    hidden: bool,
    /// What the window was last told, to only tell it changes.
    shown: bool,
    bounds: Option<[i32; 4]>,
    /// Where rustimal's client area was on the screen when the window was last placed, for a
    /// window that is not its child and has to follow it when it moves.
    origin: [i32; 2],
    /// Which program of its own it is (`browser`, `fork`): another request for one of the
    /// kind brings this back to the front instead of starting a second. None for the rest.
    kind: Option<String>,
    /// Where the window was found right after it was placed: a program may not take the
    /// size it was given (a minimum), and is only put back when it moves from there.
    settled: Option<[i32; 4]>,
}

#[derive(Default)]
pub(super) struct Hosts {
    list: Vec<Host>,
    /// Commands whose window is still to come, for the pane they run in.
    watches: Vec<(PaneId, Watch, Option<String>)>,
    /// The pane whose program has the keyboard, as far as rustimal knows.
    keys: Option<PaneId>,
    /// Where the keyboard focus was last found, to notice it moving into a program.
    focus_seen: Option<PaneId>,
    polled: Option<Instant>,
}

impl Hosts {
    pub(super) fn is_empty(&self) -> bool {
        self.list.is_empty()
    }

    /// Anything to keep an eye on, so that the window is woken to do it.
    pub(super) fn busy(&self) -> bool {
        !self.list.is_empty() || !self.watches.is_empty()
    }

    /// Does this pane show a program, as opposed to its terminal?
    pub(super) fn is_active(&self, pane: PaneId) -> bool {
        self.list.iter().any(|h| h.pane == pane && !h.hidden)
    }

    pub(super) fn shown(&self, pane: PaneId) -> bool {
        self.list.iter().any(|h| h.pane == pane && !h.hidden && h.shown)
    }

    /// Switch a pane's programs away, back to what is drawn underneath.
    pub(super) fn hide(&mut self, pane: PaneId) {
        for host in self.list.iter_mut().filter(|h| h.pane == pane) {
            host.hidden = true;
        }
    }

    /// The pane is gone: so is whatever it ran. The programs are asked to close.
    pub(super) fn remove(&mut self, pane: PaneId) {
        self.watches.retain(|&(p, ..)| p != pane);
        for host in self.list.iter().filter(|h| h.pane == pane) {
            if self.keys == Some(pane) {
                host.window.give_back();
            }
            host.window.close();
        }
        if self.keys == Some(pane) {
            self.keys = None;
        }
        self.list.retain(|h| h.pane != pane);
    }

    /// rustimal ends: its programs would be left without a window of their own.
    pub(super) fn close_all(&self) {
        for host in &self.list {
            host.window.close();
        }
    }
}

/// Put the program of a pane in front of everything else the pane has.
pub(super) fn show_host(st: &mut State, pane: PaneId) {
    st.web.release_keys(pane);
    st.web.hide(pane);
    for host in st.web.hosts.list.iter_mut().filter(|h| h.pane == pane) {
        host.hidden = false;
    }
    if let Some(p) = st.panes.iter_mut().find(|p| p.id == pane) {
        p.embeds.shown(Embed::Host);
        if let Some(chat) = p.chat.as_mut() {
            chat.hidden = true;
        }
        if let Some(review) = p.review.as_mut() {
            review.hidden = true;
        }
    }
    st.blink_epoch = Instant::now();
    st.window.request_redraw();
}

impl App {
    /// The shell's `embed` is about to run a command: watch for its window. `args` is
    /// `start:PID`, the Windows id of the shell, with `:KIND` after it (`:browser`, `:fork`)
    /// for a program that runs once. Returns true when one of the kind is already there: it
    /// is brought to the front, and the shell is told to hand its page to the one that runs.
    pub(super) fn shell_embed(&mut self, pane: PaneId, args: &str) -> bool {
        let mut parts = args.strip_prefix("start:").unwrap_or_default().split(':');
        let Some(root) = parts.next().and_then(|n| n.trim().parse::<u32>().ok()) else { return false };
        let kind = parts.next().filter(|k| !k.is_empty()).map(str::to_string);
        if let Some(kind) = &kind
            && let Some(st) = self.state.as_mut()
            && st.web.hosts.list.iter().any(|h| h.pane == pane && h.kind.as_ref() == Some(kind) && h.window.alive())
        {
            show_host(st, pane);
            return true;
        }
        self.watch_for_window(pane, root, kind);
        false
    }

    /// Look for a window opened below process `root`, for this pane.
    pub(super) fn watch_for_window(&mut self, pane: PaneId, root: u32, kind: Option<String>) {
        let keys = self.keymap.describe(Action::Embed);
        let Some(st) = self.state.as_mut() else { return };
        st.web.hosts.watches.retain(|&(p, ..)| p != pane);
        st.web.hosts.watches.push((pane, Watch::new(root), kind));
        st.web.hosts.polled = None;
        st.window.request_redraw();
        self.toast(format!("Waiting for its window\u{2026} {keys} switches back"));
    }

    /// Take a found window into the pane.
    fn take_in(&mut self, pane: PaneId, hwnd: isize, kind: Option<String>) {
        let chords = forwarded_chords(&self.keymap);
        let Some(st) = self.state.as_mut() else { return };
        let Some(parent) = win32::handle_of(&st.window) else { return };
        if !st.panes.iter().any(|p| p.id == pane) {
            return;
        }
        // One program to a pane: the one before it is asked to leave.
        st.web.hosts.remove(pane);
        // The see-through window has no bitmap for GDI and WPF programs to draw in as its
        // children, so there a program gets a window of its own over the pane.
        let mode = if self.config.glass { Mode::Owned } else { Mode::Child };
        let window = Window::adopt(hwnd, parent, mode);
        st.web.hosts.list.push(Host {
            pane,
            window,
            hidden: false,
            shown: false,
            bounds: None,
            origin: [0, 0],
            kind,
            settled: None,
        });
        Keys::install(&self.proxy, chords);
        show_host(st, pane);
    }

    /// The program of a pane asked for one of rustimal's shortcuts, through the keyboard hook.
    pub(super) fn host_key(&mut self, event_loop: &ActiveEventLoop, id: &str) {
        if let Some(action) = Action::from_id(id).filter(|a| FORWARDED.contains(a)) {
            self.run_action(event_loop, action, false);
        }
    }

    /// Close the program a pane is showing, leaving the pane and its shell. Returns false
    /// if the pane shows none.
    pub(super) fn close_host(&mut self, pane: PaneId) -> bool {
        let Some(st) = self.state.as_mut() else { return false };
        let Some(host) = st.web.hosts.list.iter().find(|h| h.pane == pane && !h.hidden && h.shown) else {
            return false;
        };
        // It may ask to save first; the pane goes back to its terminal once it is gone.
        host.window.close();
        true
    }

    /// Find the windows waited for, drop the ones that closed, put each program over its
    /// pane and give the keyboard to the focused one. Called with every frame.
    pub(super) fn sync_hosts(&mut self) {
        let Some(st) = self.state.as_mut() else { return };
        if !st.web.hosts.busy() {
            return;
        }
        let due = st.web.hosts.polled.is_none_or(|t| t.elapsed() >= TICK);
        if due {
            st.web.hosts.polled = Some(Instant::now());
            let mut found = Vec::new();
            st.web.hosts.watches.retain_mut(|(pane, watch, kind)| match watch.poll() {
                Found::Window(hwnd) => {
                    found.push((*pane, hwnd, kind.clone()));
                    false
                }
                Found::Waiting => true,
                Found::Over => false,
            });
            // Programs that have gone: the window was closed, or the app quit.
            let gone: Vec<PaneId> = st.web.hosts.list.iter().filter(|h| !h.window.alive()).map(|h| h.pane).collect();
            for pane in gone {
                if let Some(i) = st.web.hosts.list.iter().position(|h| h.pane == pane) {
                    st.web.hosts.list.remove(i);
                }
                if st.web.hosts.keys == Some(pane) {
                    st.web.hosts.keys = None;
                }
                if st.web.hosts.focus_seen == Some(pane) {
                    st.web.hosts.focus_seen = None;
                }
                if let Some(p) = st.panes.iter_mut().find(|p| p.id == pane) {
                    p.embeds.closed(Embed::Host);
                }
                // The keyboard goes back to the window, for the terminal.
                st.window.focus_window();
                st.blink_epoch = Instant::now();
                st.window.request_redraw();
            }
            for (pane, hwnd, kind) in found {
                self.take_in(pane, hwnd, kind);
            }
        }
        let Some(st) = self.state.as_mut() else { return };
        let covered = st.overlay.is_some();
        let parent = win32::handle_of(&st.window).unwrap_or(0);
        let State { web, panes, picker, focused, scale, window_focused, .. } = st;
        let hosts = &mut web.hosts;
        for host in hosts.list.iter_mut() {
            let rect = panes
                .iter()
                .find(|p| p.id == host.pane)
                // A pane tucked away by a zoom has no place in the layout.
                .filter(|p| p.target.w > 0.0 && p.opacity > 0.5)
                .filter(|_| !covered && !host.hidden && picker.as_ref().is_none_or(|k| k.pane != host.pane))
                .map(|p| view_bounds(p.rect, *scale));
            // Also when the program has put itself somewhere else.
            // Where the program ended up is only known a moment after it was asked.
            if due && host.settled.is_none() {
                host.settled = host.window.bounds();
            }
            let moved = due && host.shown && host.settled.is_some_and(|s| host.window.bounds() != Some(s));
            let origin = host.window.screen_origin();
            if let Some(bounds) = rect
                && (host.bounds != Some(bounds) || moved || host.origin != origin)
            {
                host.window.place(bounds);
                host.bounds = Some(bounds);
                host.origin = origin;
                host.settled = None;
            }
            let show = rect.is_some();
            if host.shown != show {
                if !show && hosts.keys == Some(host.pane) {
                    host.window.give_back();
                    hosts.keys = None;
                }
                host.window.show(show);
                host.shown = show;
            }
        }
        // Never pull the keyboard over from another app. Asked of Windows itself: winit
        // reports the window losing focus when a program takes the keyboard.
        let in_front = win32::is_in_front(parent);
        *window_focused = in_front;
        Keys::set_watching(!hosts.list.is_empty());
        if !in_front {
            Keys::set_active(false);
            return;
        }
        // A click in a program is not seen by rustimal: notice the keyboard moving there.
        let now_in = hosts.list.iter().find(|h| h.shown && h.window.has_focus()).map(|h| h.pane);
        let mut moved_to = None;
        if now_in != hosts.focus_seen {
            hosts.focus_seen = now_in;
            if let Some(pane) = now_in {
                hosts.keys = Some(pane);
                moved_to = Some(pane).filter(|&p| p != *focused);
            }
        }
        if let Some(pane) = moved_to {
            let prev = std::mem::replace(focused, pane);
            super::notify_focus(st, prev);
            st.window.request_redraw();
        }
        self.sync_hosts_keys(due);
    }

    /// Give the keyboard to the focused pane's program, or take it back for the terminal.
    fn sync_hosts_keys(&mut self, due: bool) {
        let Some(st) = self.state.as_mut() else { return };
        let want = st.web.hosts.shown(st.focused).then_some(st.focused);
        let hosts = &mut st.web.hosts;
        if hosts.keys != want {
            match want {
                Some(id) => {
                    if let Some(host) = hosts.list.iter().find(|h| h.pane == id && !h.hidden) {
                        host.window.focus();
                        hosts.focus_seen = Some(id);
                    }
                }
                None => {
                    if let Some(host) = hosts.list.iter().find(|h| Some(h.pane) == hosts.keys) {
                        host.window.give_back();
                    }
                    hosts.focus_seen = None;
                }
            }
            hosts.keys = want;
        }
        // Chromium-based programs (Brave, Electron apps) don't take the keyboard when they are
        // clicked, and typing would go to rustimal's window. So see that they have it.
        if due
            && let Some(id) = hosts.keys
            && let Some(host) = hosts.list.iter().find(|h| h.pane == id && !h.hidden && h.shown)
            && !host.window.has_focus()
        {
            host.window.focus();
        }
        Keys::set_active(hosts.keys.is_some());
    }

    /// A mouse button went down at this place on the screen: if it is on a program, the pane
    /// of that program is the focused one, and the program has the keyboard.
    pub(super) fn host_click(&mut self, x: i32, y: i32) {
        let Some(st) = self.state.as_mut() else { return };
        let Some(pane) = st.web.hosts.list.iter().find(|h| h.shown && h.window.contains(x, y)).map(|h| h.pane) else {
            return;
        };
        if st.focused != pane {
            let prev = std::mem::replace(&mut st.focused, pane);
            super::notify_focus(st, prev);
        }
        st.window.request_redraw();
        // The next frame hands it the keyboard.
        st.web.hosts.polled = None;
        st.web.hosts.keys = None;
    }

    /// Debug builds: `RUSTIMAL_OPEN="embed:notepad"` starts a program and takes its window
    /// into the focused pane, for trying this without a shell.
    pub(super) fn debug_embed(&mut self, command: &str) {
        let mut parts = command.split_whitespace();
        let Some(program) = parts.next() else { return };
        if let Err(e) = std::process::Command::new(program).args(parts).spawn() {
            log::warn!("could not start {program}: {e}");
            return;
        }
        if let Some(pane) = self.state.as_ref().map(|st| st.focused) {
            self.watch_for_window(pane, std::process::id(), None);
        }
    }
}