rustimal 0.8.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
use std::path::PathBuf;
use std::sync::Arc;
use std::time::{Duration, Instant};

use alacritty_terminal::event::Event as TermEvent;
use alacritty_terminal::grid::Scroll;
use alacritty_terminal::index::{Column, Line, Point, Side};
use alacritty_terminal::selection::{Selection, SelectionType};
use alacritty_terminal::term::TermMode;
use alacritty_terminal::vte::ansi::Rgb;
use winit::application::ApplicationHandler;
use winit::dpi::LogicalSize;
use winit::event::{ElementState, KeyEvent, MouseButton, MouseScrollDelta, StartCause, WindowEvent};
use winit::event_loop::{ActiveEventLoop, ControlFlow, EventLoopProxy};
use winit::keyboard::{Key, ModifiersState, NamedKey};
use winit::platform::windows::WindowAttributesExtWindows;
use winit::window::{CursorIcon, Icon, ResizeDirection, UserAttentionType, Window, WindowId};

mod actions;
mod chat;
mod chrome;
mod frame;
mod host;
mod keyboard;
mod notify;
mod overlays;
mod panes;
mod pointer;
mod reload;
mod review;
mod session;
mod term_events;
mod web;
pub use chrome::{Hit, title_buttons, titlebar_height};
use notify::{notify_done, notify_focus};
pub use web::CodeRequest;

use crate::agent::claude::Usage;
use crate::config::keys::{Action, Chord, Keymap};
use crate::config::{Config, Palette};
use crate::platform::hotkey::Hotkey;
use crate::render;
use crate::render::glyphs::Glyphs;
use crate::render::gpu::{Gpu, Quad};
use crate::terminal::editing::Move;
use crate::terminal::events::{Done, TitleSignal, UserEvent};
use crate::terminal::input;
use crate::terminal::layout::{self, Dir, Node, PaneId, Rect};
use crate::terminal::layouts::{self, Layout};
use crate::terminal::links::{self, ClickMode, Link, Target};
use crate::terminal::pane::{GridSize, Pane};
use crate::terminal::search::Search;
use crate::ui::anim::Tween;
use crate::ui::overlay::{Command, Entry, Menu, MenuAction, MenuItem, Outcome, Overlay, Palette as CommandPalette};
use crate::ui::picker::{Choice, Picker};
use crate::ui::settings::{Page, Settings};

const RESIZE_DEBOUNCE: Duration = Duration::from_millis(60);
// Animation durations, in seconds at animation_speed = 1.
const LAYOUT_SECS: f32 = 0.22;
const FADE_IN_SECS: f32 = 0.18;
const FADE_OUT_SECS: f32 = 0.14;
const FOCUS_SECS: f32 = 0.16;
const BELL_SECS: f32 = 0.5;
/// How long a toast message stays up.
pub const TOAST_SECS: Duration = Duration::from_millis(2200);

pub struct App {
    proxy: EventLoopProxy<UserEvent>,
    config: Config,
    keymap: Keymap,
    /// The global show/hide key, if one is set and could be registered.
    hotkey: Option<Hotkey>,
    /// Started with a folder (from Explorer, say), so don't restore the last session over it.
    explicit_dir: bool,
    /// `--layout NAME`: open this saved layout.
    startup_layout: Option<String>,
    palette: Palette,
    start_dir: Option<PathBuf>,
    shell_env: Vec<(String, String)>,
    /// Print the `rustimal --install` tip in the first shell.
    install_hint: bool,
    state: Option<State>,
}

pub struct State {
    /// Web apps shown in panes. First, so the views are dropped before the window.
    web: web::Views,
    pub window: Arc<Window>,
    pub gpu: Gpu,
    pub glyphs: Glyphs,
    pub scale: f32,
    font_pt: f32,
    pub panes: Vec<Pane>,
    pub closing: Vec<Pane>,
    layout: Node,
    pub focused: PaneId,
    next_id: PaneId,
    mods: ModifiersState,
    mouse: (f32, f32),
    selecting: Option<PaneId>,
    /// A drag that started on a command line, and moves its cursor.
    cmd_drag: Option<PaneId>,
    mouse_reporting: Option<PaneId>,
    last_click: Option<(Instant, u8, (f32, f32))>,
    /// Timestamp of the frame being drawn; every animation samples at this instant.
    pub now: Instant,
    pub blink_epoch: Instant,
    pub window_focused: bool,
    clipboard: Option<arboard::Clipboard>,
    pub quads: Vec<Quad>,
    pub multi: f32,
    multi_anim: Tween<f32>,
    last_focused: PaneId,
    /// Latest known Claude plan usage (shared by all Claude panes).
    pub usage: Usage,
    shown: bool,
    wake_at: Option<Instant>,
    pub window_title: String,
    pub picker: Option<Picker>,
    pub hover: Hit,
    pub pressed: Hit,
    last_title_click: Option<Instant>,
    /// When Backspace was last pressed at an empty prompt (a second press soon after goes up a folder).
    last_empty_backspace: Option<Instant>,
    /// The link under the mouse while Ctrl is held, and the pane it's in.
    hover_link: Option<(PaneId, Link)>,
    /// The cell the link search last looked at, so a moving mouse does not re-check the same one.
    link_probe: Option<(PaneId, i32, usize, ClickMode)>,
    /// A plain press on a link: it opens on release if the mouse has not moved.
    link_press: Option<(PaneId, (f32, f32), Link)>,
    /// A popup over the window: the link menu or the command palette. Takes the keys and mouse.
    pub overlay: Option<Overlay>,
    /// The review panel, kept (hidden) once opened so its place is not lost.
    /// The pane shown full size while the others are tucked away (Ctrl+Shift+Z).
    pub zoomed: Option<PaneId>,
    /// A file is being dragged over the window.
    pub drop_hover: bool,
    /// A short message shown over the window for a moment ("Copied 12 lines").
    pub toast: Option<(String, Instant)>,
    /// What finished while the window was in the background; shown as the window title
    /// (taskbar tooltip) until the window gets focus again.
    notice: Option<String>,
}

impl App {
    pub fn new(
        proxy: EventLoopProxy<UserEvent>,
        config: Config,
        start_dir: Option<PathBuf>,
        explicit_dir: bool,
        startup_layout: Option<String>,
    ) -> Self {
        let palette = Palette::from_theme(&config.theme);
        let shell_env = config.shell_env();
        // Open shells re-read PATH from this file when installers change it.
        if shell_env.iter().any(|(k, _)| k == "RUSTIMAL_STATE")
            && let Some(dir) = crate::config::state_dir()
        {
            crate::platform::winenv::watch(dir.join("winpath"));
        }
        let install_hint = config.take_install_hint();
        crate::config::watch(proxy.clone());
        let hotkey = (!config.hotkey.trim().is_empty()).then(|| Hotkey::start(&config.hotkey, proxy.clone())).flatten();
        let (keymap, problems) = Keymap::build(&config.keys);
        for problem in problems {
            log::warn!("{problem}");
        }
        Self {
            proxy,
            config,
            keymap,
            hotkey,
            explicit_dir,
            startup_layout,
            palette,
            start_dir,
            shell_env,
            install_hint,
            state: None,
        }
    }

    fn font_px(&self, pt: f32, scale: f32) -> f32 {
        (pt * 96.0 / 72.0 * scale).round()
    }

    /// Scale a base duration by the configured animation speed (0 = instant).
    fn dur(&self, secs: f32) -> f32 {
        if self.config.animation_speed <= 0.0 { 0.0 } else { secs / self.config.animation_speed }
    }

    fn focused_pane(&self) -> Option<&Pane> {
        let st = self.state.as_ref()?;
        st.panes.iter().find(|p| p.id == st.focused)
    }

    /// Show a message over the window for a moment.
    fn toast(&mut self, text: impl Into<String>) {
        if let Some(st) = self.state.as_mut() {
            st.toast = Some((text.into(), Instant::now()));
            st.window.request_redraw();
        }
    }
}

impl ApplicationHandler<UserEvent> for App {
    fn resumed(&mut self, event_loop: &ActiveEventLoop) {
        if self.state.is_some() {
            return;
        }
        let attrs = Window::default_attributes()
            .with_title("rustimal")
            .with_inner_size(LogicalSize::new(1180.0, 740.0))
            .with_min_inner_size(LogicalSize::new(360.0, 220.0))
            .with_theme(Some(winit::window::Theme::Dark))
            .with_window_icon(window_icon(32))
            .with_taskbar_icon(window_icon(64))
            .with_decorations(false)
            .with_undecorated_shadow(true)
            .with_transparent(self.config.glass)
            .with_no_redirection_bitmap(self.config.glass)
            .with_visible(false);
        let window = Arc::new(event_loop.create_window(attrs).expect("create window"));
        window.set_cursor(CursorIcon::Text);
        let scale = window.scale_factor() as f32;
        let gpu = Gpu::new(window.clone(), self.config.glass);
        if gpu.transparent && !crate::platform::glass::apply(&window) {
            log::warn!("no blurred backdrop available");
        }
        let glyphs =
            Glyphs::new(&self.config.font_family, self.font_px(self.config.font_size, scale), self.config.line_height);
        let now = Instant::now();
        let mut st = State {
            web: web::Views::default(),
            window,
            gpu,
            glyphs,
            scale,
            font_pt: self.config.font_size,
            panes: Vec::new(),
            closing: Vec::new(),
            layout: Node::Leaf(1),
            focused: 1,
            next_id: 2,
            mods: ModifiersState::empty(),
            mouse: (0.0, 0.0),
            selecting: None,
            cmd_drag: None,
            mouse_reporting: None,
            last_click: None,
            now,
            blink_epoch: now,
            window_focused: true,
            clipboard: arboard::Clipboard::new().ok(),
            quads: Vec::new(),
            multi: 0.0,
            multi_anim: Tween::new(0.0),
            last_focused: 1,
            usage: crate::config::state_dir().map(|d| Usage::load(&d.join("claude-usage.json"))).unwrap_or_default(),
            shown: false,
            wake_at: None,
            window_title: String::new(),
            picker: None,
            hover: Hit::None,
            pressed: Hit::None,
            last_title_click: None,
            last_empty_backspace: None,
            overlay: None,
            zoomed: None,
            drop_hover: false,
            toast: None,
            hover_link: None,
            link_probe: None,
            link_press: None,
            notice: None,
        };
        let mut restored = false;
        if let Some(layout) = self.startup_layout() {
            self.state = Some(st);
            restored = self.apply_layout(layout, true);
            st = self.state.take().unwrap();
        }
        if !restored {
            st.layout = Node::Leaf(1);
            st.next_id = st.next_id.max(2);
            let target = self.target_rects(&st)[0].1;
            if !self.spawn_pane(&mut st, 1, target, target, self.start_dir.clone()) {
                event_loop.exit();
                return;
            }
            st.panes[0].opacity_anim.snap(1.0);
            st.panes[0].opacity = 1.0;
        }
        self.state = Some(st);
        if cfg!(debug_assertions) {
            // For screenshots without driving the keyboard: RUSTIMAL_OPEN=palette
            let what = std::env::var("RUSTIMAL_OPEN").unwrap_or_default();
            if let Some(args) = what.strip_prefix("review:") {
                let dir = self.start_dir.clone().unwrap_or_default();
                self.shell_review(1, dir, args);
            } else if what == "palette" {
                self.open_palette();
            } else if what == "menu" {
                let path = self.start_dir.clone().unwrap_or_default().join("src");
                let link = Link { line: 0, start: 0, end: 3, target: Target::Entry { path, name: "src".into() } };
                if let Some(st) = self.state.as_mut() {
                    st.mouse = (300.0, 200.0);
                }
                self.open_link_menu(1, &link);
            } else if what == "toast" {
                self.toast("Copied the last output (12 lines)");
            } else if what == "t3" {
                let dir = self.start_dir.clone().unwrap_or_default();
                self.open_t3(1, dir, 1);
            } else if let Some(command) = what.strip_prefix("embed:") {
                self.debug_embed(command);
            } else if what == "zoom" {
                self.toggle_zoom();
            } else if let Some(page) = what.strip_prefix("settings") {
                self.open_settings();
                let page = match page {
                    ":theme" => Some(Page::Theme),
                    ":shortcuts" => Some(Page::Shortcuts),
                    _ => None,
                };
                if let (Some(page), Some(Overlay::Settings(settings))) =
                    (page, self.state.as_mut().and_then(|st| st.overlay.as_mut()))
                {
                    settings.show_page(page);
                }
            }
        }
        // Hidden windows get no redraw events on Windows, so draw the first frame now.
        self.redraw();
    }

    fn exiting(&mut self, _: &ActiveEventLoop) {
        if let Some(st) = self.state.as_ref() {
            st.web.hosts.close_all();
        }
        self.autosave_session();
    }

    fn user_event(&mut self, event_loop: &ActiveEventLoop, event: UserEvent) {
        match event {
            UserEvent::Term(id, e) => self.handle_user_event(event_loop, id, e),
            UserEvent::Hotkey => self.toggle_summon(),
            UserEvent::ConfigChanged => self.reload_config(false),
            UserEvent::Review(pane, message) => self.review_message(pane, *message),
            UserEvent::T3Page { pane, dir, page } => self.t3_page(pane, dir, page),
            UserEvent::WebMessage(pane, kind, message) => self.web_message(event_loop, pane, kind, &message),
            UserEvent::T3Pairing { pane, link } => self.t3_pair_link(pane, link),
            UserEvent::CodeReady { pane, request, server } => self.code_ready(pane, request, server),
            UserEvent::HostKey(action) => self.host_key(event_loop, &action),
            UserEvent::HostClick(x, y) => self.host_click(x, y),
            UserEvent::Chat { pane, run, update } => self.chat_update(pane, run, update),
        }
    }

    fn new_events(&mut self, _: &ActiveEventLoop, cause: StartCause) {
        if let StartCause::ResumeTimeReached { .. } = cause
            && let Some(st) = self.state.as_mut()
        {
            st.wake_at = None;
            st.window.request_redraw();
        }
    }

    fn about_to_wait(&mut self, event_loop: &ActiveEventLoop) {
        match self.state.as_ref().and_then(|s| s.wake_at) {
            Some(t) => event_loop.set_control_flow(ControlFlow::WaitUntil(t)),
            None => event_loop.set_control_flow(ControlFlow::Wait),
        }
    }

    fn window_event(&mut self, event_loop: &ActiveEventLoop, _: WindowId, event: WindowEvent) {
        if self.state.is_none() {
            return;
        }
        match event {
            WindowEvent::CloseRequested => event_loop.exit(),
            WindowEvent::RedrawRequested => self.redraw(),
            WindowEvent::Moved(_) => {
                if let Some(st) = self.state.as_ref() {
                    st.web.window_moved();
                    // Programs that are not its children follow it.
                    st.window.request_redraw();
                }
            }
            WindowEvent::Resized(size) => {
                if let Some(st) = self.state.as_mut() {
                    st.gpu.resize(size.width, size.height);
                    crate::platform::glass::hide_caption_buttons(&st.window);
                }
                self.relayout(true, false);
            }
            WindowEvent::ScaleFactorChanged { scale_factor, .. } => {
                let Some(st) = self.state.as_mut() else { return };
                st.scale = scale_factor as f32;
                let pt = st.font_pt;
                self.set_font_size(pt);
            }
            WindowEvent::Focused(focused) => self.on_focus(focused),
            WindowEvent::ModifiersChanged(m) => {
                self.state.as_mut().unwrap().mods = m.state();
                self.update_link(false);
            }
            WindowEvent::KeyboardInput { event, is_synthetic: false, .. } => self.on_key(event_loop, event),
            WindowEvent::CursorMoved { position, .. } => self.on_cursor_moved(position),
            WindowEvent::MouseInput { state, button, .. } => self.on_mouse_button(event_loop, state, button),
            WindowEvent::HoveredFile(_) => {
                let st = self.state.as_mut().unwrap();
                st.drop_hover = true;
                st.window.request_redraw();
            }
            WindowEvent::HoveredFileCancelled => {
                let st = self.state.as_mut().unwrap();
                st.drop_hover = false;
                st.window.request_redraw();
            }
            WindowEvent::DroppedFile(path) => {
                self.state.as_mut().unwrap().drop_hover = false;
                self.drop_path(&path);
            }
            WindowEvent::CursorLeft { .. } => {
                let st = self.state.as_mut().unwrap();
                if st.hover != Hit::None {
                    st.hover = Hit::None;
                    st.window.request_redraw();
                }
            }
            WindowEvent::MouseWheel { delta, .. } => self.on_mouse_wheel(delta),
            _ => {}
        }
    }
}

fn window_icon(size: u32) -> Option<Icon> {
    Icon::from_rgba(crate::platform::icon::render(size), size, size).ok()
}