rustimal 0.8.0

A minimal, GPU-rendered terminal for Windows that runs Git Bash, with animated split panes and a glass look
//! T3 Code in a pane: looking up the conversation, and pairing the view with the server.

use super::*;

/// After asking to be paired, how long before another request is believed.
pub(super) const PAIR_PATIENCE: Duration = Duration::from_secs(20);

/// How many times a view is paired before it is left to the person.
pub(super) const PAIR_TRIES: u8 = 2;

/// Says "pair" when T3 Code asks to be paired, and "paired" once it has moved on. T3 Code
/// changes pages without loading them anew, so this has to keep looking.
pub(super) const PAIRING_WATCH: &str = r#"
    let said = null;
    setInterval(() => {
        const asking = location.pathname === "/pair";
        // With a token in the address it is busy pairing.
        if (asking && location.hash.includes("token")) return;
        const now = asking ? "pair" : "paired";
        if (now !== said) {
            said = now;
            window.ipc.postMessage(now);
        }
    }, 400);"#;

/// Load `url` even if only what follows its `#` differs from the page showing. Browsers
/// just move within a page then, and T3 Code reads its pairing token as it loads.
pub(super) fn go_and_reload(url: &str) -> String {
    // As a JSON string it can't be taken for anything but a string.
    let url = serde_json::to_string(url).unwrap_or_else(|_| "\"\"".into());
    format!("location.replace({url}); location.reload();")
}

impl App {
    /// `t3` in a shell: look up the folder's conversation, off the UI thread.
    pub(in crate::app) fn open_t3(&mut self, pane: PaneId, dir: PathBuf, number: usize) {
        let keys = self.keymap.describe(Action::Embed);
        let Some(st) = self.state.as_mut() else { return };
        if st.web.opening.contains(&(pane, WebKind::T3)) {
            return;
        }
        st.web.opening.push((pane, WebKind::T3));
        let proxy = self.proxy.clone();
        std::thread::spawn(move || {
            let page = crate::programs::t3::page(&dir, number);
            let _ = proxy.send_event(UserEvent::T3Page { pane, dir, page });
        });
        self.toast(format!("Opening T3 Code\u{2026} {keys} switches back"));
    }

    /// The page is known: show it in the pane.
    pub(in crate::app) fn t3_page(&mut self, pane: PaneId, dir: PathBuf, page: Result<Page, String>) {
        if !self.stop_waiting(pane, WebKind::T3) {
            return;
        }
        let shown = page.and_then(|page| self.show_page(pane, WebKind::T3, dir, &page.origin, &page.url, true));
        self.report(WebKind::T3, shown);
    }

    /// T3 Code asks to be paired, or has stopped asking. This view of this computer's own
    /// server is rustimal's, so pair it without bothering anyone.
    pub(super) fn t3_pairing(&mut self, pane: PaneId, asking: bool) {
        let Some(view) = self.state.as_mut().and_then(|st| st.web.get_mut(pane, WebKind::T3)) else { return };
        if !asking {
            if std::mem::take(&mut view.pairing) {
                view.pair_tries = 0;
                // Pairing leaves it on the start page.
                if view.web.url().is_ok_and(|at| at != view.wanted) {
                    let _ = view.web.load_url(&view.wanted);
                }
            }
            return;
        }
        if view.pair_tries >= PAIR_TRIES || view.paired_at.is_some_and(|t| t.elapsed() < PAIR_PATIENCE) {
            return;
        }
        view.pair_tries += 1;
        view.paired_at = Some(Instant::now());
        view.pairing = true;
        let (origin, proxy) = (view.origin.clone(), self.proxy.clone());
        std::thread::spawn(move || {
            let link = crate::programs::t3::pairing_link(&origin);
            let _ = proxy.send_event(UserEvent::T3Pairing { pane, link });
        });
    }

    /// A one-time link that pairs the view.
    pub(in crate::app) fn t3_pair_link(&mut self, pane: PaneId, link: Result<String, String>) {
        let Some(view) = self.state.as_mut().and_then(|st| st.web.get_mut(pane, WebKind::T3)) else { return };
        let result = link.and_then(|link| {
            if !same_origin(&link, &view.origin) {
                return Err("the pairing link leads elsewhere".to_string());
            }
            view.web.evaluate_script(&go_and_reload(&link)).map_err(|e| e.to_string())
        });
        if result.is_err() {
            view.pairing = false;
        }
        self.report(WebKind::T3, result.map_err(|e| format!("could not pair the view: {e}")));
    }
}