ratty 0.4.1

A GPU-rendered terminal emulator that supports inline 3D graphics
Documentation
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
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
//! Mouse input handling and selection state.

use bevy::ecs::message::MessageReader;
use bevy::ecs::system::SystemParam;
use bevy::input::ButtonState;
use bevy::input::mouse::{MouseButton, MouseButtonInput, MouseScrollUnit, MouseWheel};
use bevy::prelude::*;
use bevy::window::{CursorMoved, PrimaryWindow, Window};
use vt100::{MouseProtocolEncoding, MouseProtocolMode};

use crate::runtime::TerminalRuntime;
use crate::scene::{
    MobiusTransition, TerminalPlaneView, TerminalPresentation, TerminalPresentationMode,
    TerminalViewport,
};
use crate::terminal::TerminalSurface;

/// Active terminal text selection.
#[derive(Resource, Clone, Default)]
pub struct TerminalSelection {
    start: Option<UVec2>,
    end: Option<UVec2>,
    dragging: bool,
    cursor_position: Option<Vec2>,
}

#[derive(Default)]
pub(crate) struct ForwardedMouseState {
    left_pressed: bool,
    middle_pressed: bool,
    right_pressed: bool,
    last_cell: Option<UVec2>,
}

#[derive(Default)]
pub(crate) struct LocalScrollState {
    pixel_remainder: f32,
}

/// Normalized selection bounds.
#[derive(Copy, Clone)]
pub struct SelectionBounds {
    /// First selected row.
    pub start_row: u32,
    /// Last selected row.
    pub end_row: u32,
    /// First selected column.
    pub start_col: u32,
    /// Last selected column.
    pub end_col: u32,
}

impl SelectionBounds {
    /// Returns whether a cell is inside the bounds.
    pub fn contains(&self, row: u16, col: u16) -> bool {
        let row = row as u32;
        let col = col as u32;

        if row < self.start_row || row > self.end_row {
            return false;
        }

        if self.start_row == self.end_row {
            return col >= self.start_col && col <= self.end_col;
        }

        if row == self.start_row {
            return col >= self.start_col;
        }

        if row == self.end_row {
            return col <= self.end_col;
        }

        true
    }
}

impl TerminalSelection {
    /// Returns normalized selection bounds.
    pub fn normalized_bounds(&self) -> Option<SelectionBounds> {
        let start = self.start?;
        let end = self.end.unwrap_or(start);
        Some(SelectionBounds {
            start_row: start.y.min(end.y),
            end_row: start.y.max(end.y),
            start_col: start.x.min(end.x),
            end_col: start.x.max(end.x),
        })
    }

    /// Starts a selection at a cell.
    pub fn begin(&mut self, cell: UVec2) -> bool {
        let changed = self.start != Some(cell) || self.end != Some(cell) || !self.dragging;
        self.start = Some(cell);
        self.end = Some(cell);
        self.dragging = true;
        changed
    }

    /// Updates the selection end cell.
    pub fn update(&mut self, cell: UVec2) -> bool {
        if self.dragging && self.end != Some(cell) {
            self.end = Some(cell);
            return true;
        }
        false
    }

    /// Ends an in-progress selection.
    pub fn end(&mut self) -> bool {
        let changed = self.dragging;
        self.dragging = false;
        changed
    }

    /// Clears the selection.
    pub fn clear(&mut self) -> bool {
        let changed = self.start.is_some() || self.end.is_some() || self.dragging;
        self.start = None;
        self.end = None;
        self.dragging = false;
        self.cursor_position = None;
        changed
    }

    /// Stores the current pointer position.
    pub fn set_cursor_position(&mut self, position: Vec2) {
        self.cursor_position = Some(position);
    }

    /// Returns the current pointer position.
    pub fn cursor_position(&self) -> Option<Vec2> {
        self.cursor_position
    }

    /// Returns the selected screen text.
    pub fn selected_text(&self, screen: &vt100::Screen) -> Option<String> {
        let bounds = self.normalized_bounds()?;

        let (_, cols) = screen.size();
        let mut out = String::new();

        let start_row = bounds.start_row as u16;
        let end_row = bounds.end_row as u16;
        let start_col = bounds.start_col as u16;
        let end_col = bounds.end_col as u16;

        for row in start_row..=end_row {
            let row_start = if row == start_row { start_col } else { 0 };
            let row_end = if row == end_row {
                end_col.min(cols.saturating_sub(1))
            } else {
                cols.saturating_sub(1)
            };

            for col in row_start..=row_end {
                let Some(cell) = screen.cell(row, col) else {
                    continue;
                };
                if cell.is_wide_continuation() {
                    continue;
                }

                let symbol = if cell.has_contents() {
                    cell.contents()
                } else {
                    " "
                };
                out.push_str(symbol);
            }

            if row != end_row {
                while out.ends_with(' ') {
                    out.pop();
                }
                out.push('\n');
            }
        }

        Some(out)
    }
}

/// Mouse input system parameters.
#[derive(SystemParam)]
pub struct MouseSystemParams<'w, 's> {
    primary_window: Query<'w, 's, (Entity, &'static Window), With<PrimaryWindow>>,
    runtime: NonSendMut<'w, TerminalRuntime>,
    terminal: NonSend<'w, TerminalSurface>,
    viewport: Res<'w, TerminalViewport>,
    presentation: Res<'w, TerminalPresentation>,
    mobius_transition: Res<'w, MobiusTransition>,
    plane_view: ResMut<'w, TerminalPlaneView>,
    selection: ResMut<'w, TerminalSelection>,
    redraw: ResMut<'w, crate::terminal::TerminalRedrawState>,
}

/// Handles terminal mouse input.
pub(crate) fn handle_mouse_input(
    mut cursor_events: MessageReader<CursorMoved>,
    mut button_events: MessageReader<MouseButtonInput>,
    mut wheel_events: MessageReader<MouseWheel>,
    mut params: MouseSystemParams,
    mut forwarded_mouse: Local<ForwardedMouseState>,
    mut local_scroll: Local<LocalScrollState>,
) {
    let MouseSystemParams {
        primary_window,
        runtime,
        terminal,
        viewport,
        presentation,
        mobius_transition,
        plane_view,
        selection,
        redraw,
    } = &mut params;
    let Ok((primary_window, window)) = primary_window.single() else {
        return;
    };
    let mouse_mode = runtime.parser.screen().mouse_protocol_mode();
    let mouse_encoding = runtime.parser.screen().mouse_protocol_encoding();
    let mobius_animating =
        presentation.mode == TerminalPresentationMode::Mobius3d && mobius_transition.active;
    let forward_mouse = presentation.mode == TerminalPresentationMode::Flat2d
        && mouse_mode != MouseProtocolMode::None;

    for event in cursor_events.read() {
        if event.window != primary_window {
            continue;
        }

        selection.set_cursor_position(event.position);
        if mobius_animating {
            continue;
        }

        if matches!(
            presentation.mode,
            TerminalPresentationMode::Plane3d | TerminalPresentationMode::Mobius3d
        ) {
            if plane_view.rotating {
                if let Some(last) = plane_view.last_rotate_cursor {
                    let delta = event.position - last;
                    plane_view.yaw += delta.x * 0.005;
                    plane_view.pitch -= delta.y * 0.005;
                    redraw.request();
                }
                plane_view.last_rotate_cursor = Some(event.position);
            } else if plane_view.panning {
                if let Some(last) = plane_view.last_pan_cursor {
                    let delta = event.position - last;
                    plane_view.camera_offset.x -= delta.x * plane_view.zoom;
                    plane_view.camera_offset.y += delta.y * plane_view.zoom;
                    redraw.request();
                }
                plane_view.last_pan_cursor = Some(event.position);
            }
        } else if forward_mouse {
            if let Some(cell) = position_to_cell(event.position, viewport, terminal)
                && forwarded_mouse.last_cell != Some(cell)
                && match mouse_mode {
                    MouseProtocolMode::ButtonMotion => {
                        forwarded_mouse.left_pressed
                            || forwarded_mouse.middle_pressed
                            || forwarded_mouse.right_pressed
                    }
                    MouseProtocolMode::AnyMotion => true,
                    _ => false,
                }
            {
                let button_code = if forwarded_mouse.left_pressed {
                    32
                } else if forwarded_mouse.middle_pressed {
                    33
                } else if forwarded_mouse.right_pressed {
                    34
                } else {
                    35
                };
                runtime.write_input(&encode_mouse_event(
                    cell,
                    button_code,
                    false,
                    mouse_encoding,
                ));
                forwarded_mouse.last_cell = Some(cell);
            }
        } else if selection.dragging
            && let Some(cell) = position_to_cell(event.position, viewport, terminal)
            && selection.update(cell)
        {
            redraw.request();
        }
    }

    for event in button_events.read() {
        if event.window != primary_window {
            continue;
        }

        if mobius_animating {
            continue;
        }

        match (event.button, event.state) {
            (MouseButton::Left, ButtonState::Pressed) => {
                if forward_mouse {
                    forwarded_mouse.left_pressed = true;
                    if let Some(cell) = window
                        .cursor_position()
                        .or(selection.cursor_position())
                        .and_then(|position| position_to_cell(position, viewport, terminal))
                    {
                        runtime.write_input(&encode_mouse_event(cell, 0, false, mouse_encoding));
                        forwarded_mouse.last_cell = Some(cell);
                    }
                } else if matches!(
                    presentation.mode,
                    TerminalPresentationMode::Plane3d | TerminalPresentationMode::Mobius3d
                ) {
                    plane_view.rotating = true;
                    plane_view.last_rotate_cursor = selection.cursor_position();
                } else if let Some(pos) = selection.cursor_position()
                    && let Some(cell) = position_to_cell(pos, viewport, terminal)
                    && selection.begin(cell)
                {
                    redraw.request();
                }
            }
            (MouseButton::Left, ButtonState::Released) => {
                if forward_mouse {
                    forwarded_mouse.left_pressed = false;
                    if let Some(cell) = window
                        .cursor_position()
                        .or(selection.cursor_position())
                        .and_then(|position| position_to_cell(position, viewport, terminal))
                    {
                        runtime.write_input(&encode_mouse_event(cell, 0, true, mouse_encoding));
                        forwarded_mouse.last_cell = Some(cell);
                    }
                } else if matches!(
                    presentation.mode,
                    TerminalPresentationMode::Plane3d | TerminalPresentationMode::Mobius3d
                ) {
                    plane_view.rotating = false;
                    plane_view.last_rotate_cursor = selection.cursor_position();
                } else {
                    let _ = selection.end();
                }
            }
            (MouseButton::Middle, ButtonState::Pressed) if forward_mouse => {
                forwarded_mouse.middle_pressed = true;
                if let Some(cell) = window
                    .cursor_position()
                    .or(selection.cursor_position())
                    .and_then(|position| position_to_cell(position, viewport, terminal))
                {
                    runtime.write_input(&encode_mouse_event(cell, 1, false, mouse_encoding));
                    forwarded_mouse.last_cell = Some(cell);
                }
            }
            (MouseButton::Middle, ButtonState::Released) if forward_mouse => {
                forwarded_mouse.middle_pressed = false;
                if let Some(cell) = window
                    .cursor_position()
                    .or(selection.cursor_position())
                    .and_then(|position| position_to_cell(position, viewport, terminal))
                {
                    runtime.write_input(&encode_mouse_event(cell, 1, true, mouse_encoding));
                    forwarded_mouse.last_cell = Some(cell);
                }
            }
            (MouseButton::Right, ButtonState::Pressed) if forward_mouse => {
                forwarded_mouse.right_pressed = true;
                if let Some(cell) = window
                    .cursor_position()
                    .or(selection.cursor_position())
                    .and_then(|position| position_to_cell(position, viewport, terminal))
                {
                    runtime.write_input(&encode_mouse_event(cell, 2, false, mouse_encoding));
                    forwarded_mouse.last_cell = Some(cell);
                }
            }
            (MouseButton::Right, ButtonState::Released) if forward_mouse => {
                forwarded_mouse.right_pressed = false;
                if let Some(cell) = window
                    .cursor_position()
                    .or(selection.cursor_position())
                    .and_then(|position| position_to_cell(position, viewport, terminal))
                {
                    runtime.write_input(&encode_mouse_event(cell, 2, true, mouse_encoding));
                    forwarded_mouse.last_cell = Some(cell);
                }
            }
            (MouseButton::Right, ButtonState::Pressed)
                if matches!(
                    presentation.mode,
                    TerminalPresentationMode::Plane3d | TerminalPresentationMode::Mobius3d
                ) =>
            {
                plane_view.panning = true;
                plane_view.last_pan_cursor = selection.cursor_position();
            }
            (MouseButton::Right, ButtonState::Released)
                if matches!(
                    presentation.mode,
                    TerminalPresentationMode::Plane3d | TerminalPresentationMode::Mobius3d
                ) =>
            {
                plane_view.panning = false;
                plane_view.last_pan_cursor = selection.cursor_position();
            }
            _ => {}
        }
    }

    for event in wheel_events.read() {
        if mobius_animating {
            continue;
        }

        let delta = match event.unit {
            MouseScrollUnit::Line => event.y * 0.1,
            MouseScrollUnit::Pixel => event.y * 0.001,
        };

        if forward_mouse && delta != 0.0 {
            if let Some(cell) = window
                .cursor_position()
                .or(selection.cursor_position())
                .and_then(|position| position_to_cell(position, viewport, terminal))
            {
                runtime.write_input(&encode_mouse_event(
                    cell,
                    if delta > 0.0 { 64 } else { 65 },
                    false,
                    mouse_encoding,
                ));
            }
        } else if presentation.mode == TerminalPresentationMode::Flat2d
            && !runtime.parser.screen().alternate_screen()
        {
            let amount = match event.unit {
                MouseScrollUnit::Line => event.y.round() as isize,
                MouseScrollUnit::Pixel => {
                    let char_height = terminal.char_dimensions().y.max(1) as f32;
                    local_scroll.pixel_remainder += event.y / char_height;
                    let amount = local_scroll.pixel_remainder.trunc() as isize;
                    local_scroll.pixel_remainder -= amount as f32;
                    amount
                }
            };

            if amount != 0 {
                let screen = runtime.parser.screen_mut();
                let current = screen.scrollback() as isize;
                let next = (current + amount).max(0) as usize;
                screen.set_scrollback(next);
                selection.clear();
                redraw.request();
            }
        } else if matches!(
            presentation.mode,
            TerminalPresentationMode::Plane3d | TerminalPresentationMode::Mobius3d
        ) && delta != 0.0
        {
            plane_view.zoom = (plane_view.zoom - delta).clamp(0.1, 4.0);
            redraw.request();
        }
    }
}

fn encode_mouse_event(
    cell: UVec2,
    button_code: u16,
    release: bool,
    encoding: MouseProtocolEncoding,
) -> Vec<u8> {
    let col = cell.x + 1;
    let row = cell.y + 1;
    match encoding {
        MouseProtocolEncoding::Sgr => {
            let final_byte = if release { 'm' } else { 'M' };
            format!("\x1b[<{button_code};{col};{row}{final_byte}").into_bytes()
        }
        MouseProtocolEncoding::Default | MouseProtocolEncoding::Utf8 => {
            let code = if release { 3 } else { button_code }.saturating_add(32);
            let x = (col + 32).min(u8::MAX as u32) as u8;
            let y = (row + 32).min(u8::MAX as u32) as u8;
            vec![0x1b, b'[', b'M', code as u8, x, y]
        }
    }
}

pub(crate) fn encode_mouse_wheel(
    cell: UVec2,
    up: bool,
    encoding: MouseProtocolEncoding,
) -> Vec<u8> {
    encode_mouse_event(cell, if up { 64 } else { 65 }, false, encoding)
}

fn position_to_cell(
    position: Vec2,
    viewport: &TerminalViewport,
    terminal: &TerminalSurface,
) -> Option<UVec2> {
    if viewport.size.x <= 0.0 || viewport.size.y <= 0.0 {
        return None;
    }

    let cols = terminal.cols.max(1) as f32;
    let rows = terminal.rows.max(1) as f32;
    let cell_width = viewport.size.x / cols;
    let cell_height = viewport.size.y / rows;
    if cell_width <= 0.0 || cell_height <= 0.0 {
        return None;
    }

    let x = position.x.clamp(0.0, viewport.size.x - 1.0);
    let y = position.y.clamp(0.0, viewport.size.y - 1.0);
    let col = (x / cell_width).floor() as u32;
    let row = (y / cell_height).floor() as u32;

    Some(UVec2::new(
        col.min(terminal.cols.saturating_sub(1) as u32),
        row.min(terminal.rows.saturating_sub(1) as u32),
    ))
}