rustimal 0.7.0

A minimal, GPU-rendered terminal for Windows that runs Git Bash, with animated split panes and a glass look
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
//! T3 Code in a pane: its web UI in a web view (WebView2) laid over the pane it was asked
//! for. The shell keeps running underneath, and Ctrl+Shift+T switches between the two.
//! Which page to show comes from [`crate::t3`].
//!
//! The web view is a window of its own on top of rustimal's drawing, with two results.
//! It is hidden while rustimal has something to draw over the pane, such as the command
//! palette. And while it has the keyboard rustimal sees no keys, so a small script in the
//! page passes rustimal's pane shortcuts back.

use std::collections::BTreeMap;
use std::path::PathBuf;

use winit::event::KeyEvent;
use winit::event_loop::ActiveEventLoop;
use winit::raw_window_handle::{HasWindowHandle, RawWindowHandle};
use winit::window::Window;
use wry::dpi::{PhysicalPosition, PhysicalSize};
use wry::{NewWindowResponse, WebContext, WebView, WebViewBuilder};

use super::{App, State};
use crate::keys::{Action, Chord, Keymap};
use crate::layout::{PaneId, Rect};
use crate::links::{self, Target};
use crate::pane::UserEvent;
use crate::t3::Page;

/// Space left around the view, in logical pixels, so the pane's rim and focus ring show.
const INSET: f32 = 6.0;

/// Actions that still work while T3 Code has the keyboard. The rest of rustimal's keys
/// are left to T3 Code.
const FORWARDED: &[Action] = &[
    Action::T3,
    Action::Chat,
    Action::FocusLeft,
    Action::FocusRight,
    Action::FocusUp,
    Action::FocusDown,
    Action::ResizeLeft,
    Action::ResizeRight,
    Action::ResizeUp,
    Action::ResizeDown,
    Action::SplitLeft,
    Action::SplitRight,
    Action::SplitUp,
    Action::SplitDown,
    Action::ClosePane,
    Action::Zoom,
];

#[derive(Default)]
pub(super) struct Views {
    views: Vec<View>,
    /// The pane whose view was last given the keyboard.
    keys: Option<PaneId>,
    /// Panes whose page is being looked up.
    opening: Vec<PaneId>,
    /// Where the views keep their sign-in and settings. Declared after them, so it is
    /// dropped after them.
    context: Option<WebContext>,
}

struct View {
    pane: PaneId,
    web: WebView,
    /// The folder it was opened for.
    dir: PathBuf,
    /// Switched away from: the terminal is showing.
    hidden: bool,
    /// What the web view was last told, to only tell it changes.
    shown: bool,
    bounds: Option<[i32; 4]>,
}

impl Views {
    fn get(&self, pane: PaneId) -> Option<&View> {
        self.views.iter().find(|v| v.pane == pane)
    }

    fn get_mut(&mut self, pane: PaneId) -> Option<&mut View> {
        self.views.iter_mut().find(|v| v.pane == pane)
    }

    /// Switch a pane's view away, as the shortcut does.
    pub(super) fn hide(&mut self, pane: PaneId) {
        if let Some(view) = self.get_mut(pane) {
            view.hidden = true;
        }
    }

    /// Drop a pane's view, taking the keyboard back from it first.
    pub(super) fn remove(&mut self, pane: PaneId) {
        if let Some(i) = self.views.iter().position(|v| v.pane == pane) {
            if self.keys == Some(pane) {
                let _ = self.views[i].web.focus_parent();
                self.keys = None;
            }
            self.views.remove(i);
        }
        self.opening.retain(|&p| p != pane);
    }
}

/// Is this window the one in front? A web view with the keyboard counts as the window.
fn in_foreground(window: &Window) -> bool {
    #[link(name = "user32")]
    unsafe extern "system" {
        fn GetForegroundWindow() -> isize;
    }
    let Ok(handle) = window.window_handle() else { return false };
    let RawWindowHandle::Win32(h) = handle.as_raw() else { return false };
    // SAFETY: takes no arguments and only returns a handle to compare.
    unsafe { GetForegroundWindow() == h.hwnd.get() }
}

/// The chords the page should hand back, as `chord -> action id`. A key without Ctrl or
/// Alt is never taken, so that typing in T3 Code always works.
fn forwarded_chords(keymap: &Keymap) -> BTreeMap<String, &'static str> {
    let is_function_key = |c: &Chord| c.key.len() > 1 && c.key.starts_with('f');
    FORWARDED
        .iter()
        .flat_map(|&a| keymap.chords(a).into_iter().map(move |c| (c, a)))
        .filter(|(c, _)| c.ctrl || c.alt || is_function_key(c))
        .map(|(c, a)| (c.to_config(), a.id()))
        .collect()
}

/// The action a forwarded message asks for. Only the forwarded ones are accepted.
fn forwarded_action(message: &str) -> Option<Action> {
    Action::from_id(message.strip_prefix("key:")?).filter(|a| FORWARDED.contains(a))
}

/// Runs in T3 Code's page: passes rustimal's shortcuts back, and says when the page is
/// clicked, so rustimal knows which pane has the focus.
fn bridge_script(keymap: &Keymap) -> String {
    let chords = serde_json::to_string(&forwarded_chords(keymap)).unwrap_or_else(|_| "{}".into());
    format!(
        r#"(() => {{
    const chords = {chords};
    const named = {{ ArrowLeft: "left", ArrowRight: "right", ArrowUp: "up", ArrowDown: "down", " ": "space" }};
    addEventListener("keydown", (e) => {{
        const key = named[e.key] || e.key.toLowerCase();
        const chord = (e.ctrlKey ? "ctrl+" : "") + (e.altKey ? "alt+" : "") + (e.shiftKey ? "shift+" : "") + key;
        if (!Object.hasOwn(chords, chord)) return;
        e.preventDefault();
        e.stopImmediatePropagation();
        window.ipc.postMessage("key:" + chords[chord]);
    }}, true);
    addEventListener("pointerdown", () => window.ipc.postMessage("focus"), true);
}})();"#
    )
}

/// Is `url` a page of the server at `origin`?
fn same_origin(url: &str, origin: &str) -> bool {
    url.strip_prefix(origin).is_some_and(|rest| rest.is_empty() || rest.starts_with('/'))
}

/// Links that lead away from T3 Code belong in the browser.
fn open_outside(url: &str) {
    if url.starts_with("https://") || url.starts_with("http://") {
        links::open(&Target::Url(url.to_string()), "");
    }
}

/// Where a pane's view goes, as `[x, y, width, height]`.
fn view_bounds(pane: Rect, scale: f32) -> [i32; 4] {
    let inset = (INSET * scale).round();
    let size = |s: f32| (s - 2.0 * inset).max(1.0).round() as i32;
    [(pane.x + inset).round() as i32, (pane.y + inset).round() as i32, size(pane.w), size(pane.h)]
}

fn to_web_rect([x, y, w, h]: [i32; 4]) -> wry::Rect {
    wry::Rect {
        position: PhysicalPosition::new(x, y).into(),
        size: PhysicalSize::new(w.max(1) as u32, h.max(1) as u32).into(),
    }
}

impl App {
    /// `t3` in a shell: look up the folder's conversation, off the UI thread.
    pub(super) fn open_t3(&mut self, pane: PaneId, dir: PathBuf, number: usize) {
        let keys = self.keymap.describe(Action::T3);
        let Some(st) = self.state.as_mut() else { return };
        if st.t3.opening.contains(&pane) {
            return;
        }
        st.t3.opening.push(pane);
        let proxy = self.proxy.clone();
        std::thread::spawn(move || {
            let page = crate::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(super) fn t3_page(&mut self, pane: PaneId, dir: PathBuf, page: Result<Page, String>) {
        let Some(st) = self.state.as_mut() else { return };
        // The pane may have been closed while the page was looked up.
        if !st.t3.opening.contains(&pane) {
            return;
        }
        st.t3.opening.retain(|&p| p != pane);
        let shown = page.and_then(|page| match st.t3.get_mut(pane) {
            Some(view) => {
                view.dir = dir;
                view.hidden = false;
                // Reloading the page it is already on would only lose the place in it.
                if view.web.url().is_ok_and(|url| url == page.url) {
                    Ok(())
                } else {
                    view.web.load_url(&page.url).map_err(|e| e.to_string())
                }
            }
            None => build_view(st, &self.proxy, &self.keymap, pane, dir, &page),
        });
        match shown {
            Ok(()) => {
                st.t3.keys = None;
                if let Some(chat) = st.panes.iter_mut().find(|p| p.id == pane).and_then(|p| p.chat.as_mut()) {
                    chat.hidden = true;
                }
                st.window.request_redraw();
            }
            Err(e) => {
                log::warn!("T3 Code: {e}");
                // A toast is one line.
                self.toast(format!("T3 Code: {}", e.lines().next().unwrap_or_default()));
            }
        }
    }

    /// The shortcut: switch the focused pane between T3 Code and its terminal.
    pub(super) fn toggle_t3(&mut self) {
        let Some(st) = self.state.as_mut() else { return };
        let id = st.focused;
        let cwd = st.panes.iter().find(|p| p.id == id).and_then(|p| p.cwd.clone()).or_else(|| self.start_dir.clone());
        let Some(cwd) = cwd.or_else(dirs::home_dir) else { return };
        match st.t3.get_mut(id) {
            Some(view) if !view.hidden => view.hidden = true,
            // Back to the same place, unless the shell has moved to another folder.
            Some(view) if view.dir == cwd => {
                view.hidden = false;
                if let Some(chat) = st.panes.iter_mut().find(|p| p.id == id).and_then(|p| p.chat.as_mut()) {
                    chat.hidden = true;
                }
            }
            _ => return self.open_t3(id, cwd, 1),
        }
        st.blink_epoch = std::time::Instant::now();
        st.window.request_redraw();
    }

    /// Something a view's page sent.
    pub(super) fn t3_message(&mut self, event_loop: &ActiveEventLoop, pane: PaneId, message: &str) {
        let Some(st) = self.state.as_mut() else { return };
        // A message can arrive after its view has been switched away from.
        if st.t3.get(pane).is_none_or(|v| !v.shown) {
            return;
        }
        if st.focused != pane {
            let prev = st.focused;
            st.focused = pane;
            // The click that did this already gave the view the keyboard.
            st.t3.keys = Some(pane);
            super::notify_focus(st, prev);
        }
        st.window.request_redraw();
        if let Some(action) = forwarded_action(message) {
            self.run_action(event_loop, action, false);
        }
    }

    /// A key that reached rustimal although the focused pane shows T3 Code (after a click
    /// on the title bar, say). Shortcuts work; nothing reaches the hidden shell.
    pub(super) fn t3_key(&mut self, event_loop: &ActiveEventLoop, event: &KeyEvent) -> bool {
        let Some(st) = self.state.as_mut() else { return false };
        if st.t3.get(st.focused).is_none_or(|v| !v.shown) {
            return false;
        }
        st.t3.keys = None;
        st.window.request_redraw();
        let action = Chord::from_event(event, st.mods).and_then(|c| self.keymap.get(&c));
        if action.is_some_and(|a| FORWARDED.contains(&a) || matches!(a, Action::Palette | Action::Settings)) {
            self.shortcut(event_loop, event);
        }
        true
    }

    /// winit reports the window losing focus when a view takes the keyboard.
    pub(super) fn t3_focus_changed(&mut self, focused: bool) -> bool {
        let Some(st) = self.state.as_mut() else { return focused };
        if st.t3.views.is_empty() {
            return focused;
        }
        if focused {
            // The window itself has the keyboard again; hand it back to the view.
            st.t3.keys = None;
        }
        focused || in_foreground(&st.window)
    }

    /// While a view has the keyboard, winit doesn't hear that another app came to the
    /// front, so check before relying on it.
    pub(super) fn t3_window_focus(&mut self) {
        if let Some(st) = self.state.as_mut()
            && !st.t3.views.is_empty()
        {
            st.window_focused = in_foreground(&st.window);
        }
    }

    /// Put each view over its pane, hide the ones that must not show, and move the
    /// keyboard to the focused one. Called with every frame.
    pub(super) fn sync_t3(&mut self) {
        let Some(st) = self.state.as_ref() else { return };
        if st.t3.views.is_empty() {
            return;
        }
        let covered = st.overlay.is_some() || self.review_covers(st);
        let review_keys = Self::review_has_keys(st);
        let Some(st) = self.state.as_mut() else { return };
        let State { t3, panes, picker, focused, scale, window_focused, .. } = st;
        for view in t3.views.iter_mut() {
            let pane = panes.iter().find(|p| p.id == view.pane);
            let rect = 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 && !view.hidden && picker.as_ref().is_none_or(|k| k.pane != view.pane))
                .map(|p| view_bounds(p.rect, *scale));
            if let Some(bounds) = rect
                && view.bounds != Some(bounds)
                && view.web.set_bounds(to_web_rect(bounds)).is_ok()
            {
                view.bounds = Some(bounds);
            }
            let show = rect.is_some();
            if view.shown != show {
                if !show && t3.keys == Some(view.pane) {
                    let _ = view.web.focus_parent();
                    t3.keys = None;
                }
                if view.web.set_visible(show).is_ok() {
                    view.shown = show;
                }
            }
        }
        // Never pull the keyboard over from another app.
        if !*window_focused {
            return;
        }
        let want = (!review_keys && t3.get(*focused).is_some_and(|v| v.shown)).then_some(*focused);
        if t3.keys == want {
            return;
        }
        match want {
            Some(id) => {
                if let Some(view) = t3.get(id) {
                    let _ = view.web.focus();
                }
            }
            None => {
                if let Some(view) = t3.keys.and_then(|id| t3.get(id)) {
                    let _ = view.web.focus_parent();
                }
            }
        }
        t3.keys = want;
    }
}

fn build_view(
    st: &mut State,
    proxy: &winit::event_loop::EventLoopProxy<UserEvent>,
    keymap: &Keymap,
    pane: PaneId,
    dir: PathBuf,
    page: &Page,
) -> Result<(), String> {
    let Some(rect) = st.panes.iter().find(|p| p.id == pane).map(|p| p.rect) else { return Ok(()) };
    let context = st.t3.context.get_or_insert_with(|| {
        // Without a folder of its own, WebView2 writes next to the exe.
        WebContext::new(dirs::data_local_dir().map(|d| d.join("rustimal").join("webview")))
    });
    let (origin, navigation, proxy) = (page.origin.clone(), page.origin.clone(), proxy.clone());
    let web = WebViewBuilder::new_with_web_context(context)
        .with_url(&page.url)
        .with_bounds(to_web_rect(view_bounds(rect, st.scale)))
        .with_visible(false)
        .with_focused(false)
        .with_background_color((10, 10, 10, 255))
        .with_initialization_script(bridge_script(keymap))
        .with_ipc_handler(move |request| {
            if same_origin(&request.uri().to_string(), &origin) {
                let _ = proxy.send_event(UserEvent::T3Message(pane, request.into_body()));
            }
        })
        .with_navigation_handler(move |url| {
            let stays = same_origin(&url, &navigation);
            if !stays {
                open_outside(&url);
            }
            stays
        })
        .with_new_window_req_handler(|url, _| {
            open_outside(&url);
            NewWindowResponse::Deny
        })
        .build_as_child(&*st.window)
        .map_err(|e| format!("could not start the web view: {e}"))?;
    st.t3.views.push(View { pane, web, dir, hidden: false, shown: false, bounds: None });
    Ok(())
}

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

    #[test]
    fn only_pane_shortcuts_come_back_from_the_page() {
        let (keymap, _) = Keymap::build(&Default::default());
        let chords = forwarded_chords(&keymap);
        assert_eq!(chords.get("ctrl+shift+t"), Some(&"t3"));
        assert_eq!(chords.get("alt+left"), Some(&"focus_left"));
        assert_eq!(chords.get("ctrl+v"), None, "pasting stays T3 Code's");
        assert_eq!(forwarded_action("key:t3"), Some(Action::T3));
        assert_eq!(forwarded_action("key:paste"), None, "a page can't ask for anything else");
        assert_eq!(forwarded_action("focus"), None);
        assert!(bridge_script(&keymap).contains(r#""ctrl+shift+t":"t3""#));
    }

    #[test]
    fn other_sites_are_not_the_local_server() {
        let origin = "http://127.0.0.1:3773";
        assert!(same_origin("http://127.0.0.1:3773/e/t", origin));
        assert!(same_origin(origin, origin));
        assert!(!same_origin("http://127.0.0.1:37730/", origin));
        assert!(!same_origin("http://127.0.0.1:3773@example.com/", origin));
        assert!(!same_origin("https://example.com/", origin));
    }

    #[test]
    fn the_view_leaves_the_pane_rim_showing() {
        assert_eq!(view_bounds(Rect::new(10.0, 20.0, 300.0, 200.0), 1.0), [16, 26, 288, 188]);
        assert_eq!(view_bounds(Rect::new(0.0, 0.0, 4.0, 4.0), 1.0), [6, 6, 1, 1], "never empty");
    }
}