freya-terminal 0.5.4

Terminal emulator integration for Freya
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
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
use std::{
    cell::RefCell,
    path::PathBuf,
    rc::Rc,
    time::{
        Duration,
        Instant,
    },
};

use freya_core::prelude::{
    Platform,
    TaskHandle,
    UseId,
    UserEvent,
    spawn_in_window,
};
use futures_lite::StreamExt;
use keyboard_types::{
    Key,
    Modifiers,
    NamedKey,
};
use rio_vt::{
    ansi::CursorShape,
    crosswords::{
        Crosswords,
        CrosswordsSize,
        Mode,
        grid::Scroll,
        pos::{
            Column,
            Line,
            Pos,
            Side,
        },
    },
    event::{
        EventListener,
        RioEvent,
        WindowId,
    },
    performer::handler::Processor,
    selection::{
        Selection,
        SelectionType,
    },
};
use tiny_cache::FifoCache;
use tiny_notify::ArcNotify;

use crate::{
    backends::{
        TerminalBackend,
        TerminalOutput,
    },
    cell::snapshot_row,
    parser::{
        TerminalMouseButton,
        encode_mouse_move,
        encode_mouse_press,
        encode_mouse_release,
        encode_wheel_event,
    },
    rendering::CachedRow,
    url::url_at,
};

/// Unique identifier for a terminal instance
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct TerminalId(pub usize);

impl TerminalId {
    pub fn new() -> Self {
        Self(UseId::<TerminalId>::get_in_hook())
    }
}

impl Default for TerminalId {
    fn default() -> Self {
        Self::new()
    }
}

/// Error type for terminal operations
#[derive(Debug, thiserror::Error)]
pub enum TerminalError {
    #[error("Write error: {0}")]
    WriteError(String),

    #[error("Failed to start terminal backend: {0}")]
    StartError(String),

    #[error("Terminal closed")]
    Closed,
}

impl From<std::io::Error> for TerminalError {
    fn from(e: std::io::Error) -> Self {
        TerminalError::WriteError(e.to_string())
    }
}

type SharedBackend = Rc<RefCell<Option<Box<dyn TerminalBackend>>>>;

/// Listener proxy passed into rio-vt's `Crosswords`. Routes its side-effects
/// (PtyWrite, Title, ClipboardStore) into the freya-side state.
#[derive(Clone)]
pub struct EventProxy {
    backend: SharedBackend,
    title: Rc<RefCell<Option<String>>>,
    title_notifier: ArcNotify,
    clipboard_content: Rc<RefCell<Option<String>>>,
    clipboard_notifier: ArcNotify,
}

impl EventListener for EventProxy {
    fn send_event(&self, event: RioEvent, _window_id: WindowId) {
        match event {
            RioEvent::PtyWrite(_route, text) => {
                if let Some(backend) = &mut *self.backend.borrow_mut() {
                    let _ = backend.write(text.as_bytes());
                }
            }
            RioEvent::Title(_, t) => {
                *self.title.borrow_mut() = Some(t);
                self.title_notifier.notify();
            }
            RioEvent::ResetTitle => {
                *self.title.borrow_mut() = None;
                self.title_notifier.notify();
            }
            RioEvent::ClipboardStore(_, text) => {
                *self.clipboard_content.borrow_mut() = Some(text);
                self.clipboard_notifier.notify();
            }
            // Bell, Wakeup, ColorRequest, etc.
            _ => {}
        }
    }
}

/// Drops the backend and the parser task when the last handle is dropped.
pub(crate) struct TerminalCleaner {
    backend: SharedBackend,
    /// Output reader/parser task.
    task: TaskHandle,
    /// Notifier that signals when the terminal should close.
    closer_notifier: ArcNotify,
}

/// Handle-local input tracking.
pub(crate) struct TerminalInner {
    pub(crate) last_write_time: Instant,
    pub(crate) pressed_button: Option<TerminalMouseButton>,
    pub(crate) modifiers: Modifiers,
}

impl Drop for TerminalCleaner {
    fn drop(&mut self) {
        *self.backend.borrow_mut() = None;
        self.task.try_cancel();
        self.closer_notifier.notify();
    }
}

/// Handle to a running terminal instance. Multiple `Terminal` components can share
/// the same handle, and the backend is dropped when the last handle is dropped.
#[derive(Clone)]
pub struct TerminalHandle {
    /// Unique identifier for this terminal instance, used for `PartialEq`.
    pub(crate) id: TerminalId,
    /// rio-vt's terminal model: grid, modes, scrollback. The renderer
    /// borrows this directly during paint, so there is no parallel snapshot.
    pub(crate) term: Rc<RefCell<Crosswords<EventProxy>>>,
    /// Keeps row drawing results alive across layout measurements.
    pub(crate) row_cache: Rc<RefCell<FifoCache<u64, CachedRow>>>,
    /// Program the terminal is attached to, `None` once it has closed.
    pub(crate) backend: SharedBackend,
    /// Handle-local state (input tracking).
    pub(crate) inner: Rc<RefCell<TerminalInner>>,
    /// Window title reported by the shell via OSC 0 or OSC 2.
    pub(crate) title: Rc<RefCell<Option<String>>>,
    /// Notifier that signals when the terminal closes.
    pub(crate) closer_notifier: ArcNotify,
    /// Kept alive purely so its `Drop` runs when the last handle dies.
    #[allow(dead_code)]
    pub(crate) cleaner: Rc<TerminalCleaner>,
    /// Notifier that signals each time new output is received from the backend.
    pub(crate) output_notifier: ArcNotify,
    /// Notifier that signals when the window title changes via OSC 0 or OSC 2.
    pub(crate) title_notifier: ArcNotify,
    /// Clipboard content set by the terminal app via OSC 52.
    pub(crate) clipboard_content: Rc<RefCell<Option<String>>>,
    /// Notifier that signals when clipboard content changes via OSC 52.
    pub(crate) clipboard_notifier: ArcNotify,
}

impl PartialEq for TerminalHandle {
    fn eq(&self, other: &Self) -> bool {
        self.id == other.id
    }
}

impl TerminalHandle {
    /// Start `backend` and return a handle driving it. Defaults to 1000 lines
    /// of scrollback when `scrollback_length` is `None`.
    pub fn new(
        id: TerminalId,
        mut backend: impl TerminalBackend + 'static,
        scrollback_length: Option<usize>,
    ) -> Result<Self, TerminalError> {
        let (sender, mut receiver) = futures_channel::mpsc::unbounded();
        backend.start(TerminalOutput { sender })?;
        let backend: SharedBackend = Rc::new(RefCell::new(Some(Box::new(backend))));

        let closer_notifier = ArcNotify::new();
        let output_notifier = ArcNotify::new();
        let title_notifier = ArcNotify::new();
        let title: Rc<RefCell<Option<String>>> = Rc::new(RefCell::new(None));
        let clipboard_content: Rc<RefCell<Option<String>>> = Rc::new(RefCell::new(None));
        let clipboard_notifier = ArcNotify::new();

        let event_proxy = EventProxy {
            backend: backend.clone(),
            title: title.clone(),
            title_notifier: title_notifier.clone(),
            clipboard_content: clipboard_content.clone(),
            clipboard_notifier: clipboard_notifier.clone(),
        };

        let term = Rc::new(RefCell::new(Crosswords::new(
            CrosswordsSize::new(80, 24),
            CursorShape::Block,
            event_proxy,
            WindowId::from(0),
            0,
            scrollback_length.unwrap_or(1000),
        )));

        let row_cache = Rc::new(RefCell::new(FifoCache::new(term.borrow().screen_lines())));

        let inner = Rc::new(RefCell::new(TerminalInner {
            last_write_time: Instant::now(),
            pressed_button: None,
            modifiers: Modifiers::empty(),
        }));

        let platform = Platform::get().current_window();
        let task = spawn_in_window({
            let term = term.clone();
            let backend = backend.clone();
            let closer_notifier = closer_notifier.clone();
            let output_notifier = output_notifier.clone();
            async move {
                let mut processor = Processor::default();
                while let Some(bytes) = receiver.next().await {
                    processor.advance(&mut *term.borrow_mut(), &bytes);
                    output_notifier.notify();
                    platform.send(UserEvent::RequestRedraw);
                }
                // Output ended, drop the backend and notify observers.
                *backend.borrow_mut() = None;
                closer_notifier.notify();
                platform.send(UserEvent::RequestRedraw);
            }
        });

        Ok(Self {
            closer_notifier: closer_notifier.clone(),
            cleaner: Rc::new(TerminalCleaner {
                backend: backend.clone(),
                task,
                closer_notifier,
            }),
            id,
            term,
            row_cache,
            backend,
            inner,
            title,
            title_notifier,
            clipboard_content,
            clipboard_notifier,
            output_notifier,
        })
    }

    /// Write data to the backend. Drops any selection and snaps the viewport to the bottom.
    pub fn write(&self, data: &[u8]) -> Result<(), TerminalError> {
        self.write_raw(data)?;
        let mut term = self.term.borrow_mut();
        term.selection = None;
        term.scroll_display(Scroll::Bottom);
        self.inner.borrow_mut().last_write_time = Instant::now();
        Ok(())
    }

    /// Time since the user last wrote input to the backend.
    pub fn last_write_elapsed(&self) -> Duration {
        self.inner.borrow().last_write_time.elapsed()
    }

    /// Write a key event to the backend as the matching escape sequence. Returns whether it was recognised.
    pub fn write_key(&self, key: &Key, modifiers: Modifiers) -> Result<bool, TerminalError> {
        let shift = modifiers.contains(Modifiers::SHIFT);
        let ctrl = modifiers.contains(Modifiers::CONTROL);
        let alt = modifiers.contains(Modifiers::ALT);

        // CSI u / xterm modifier byte: `1 + shift + alt*2 + ctrl*4`.
        let modifier = || 1 + shift as u8 + (alt as u8) * 2 + (ctrl as u8) * 4;

        let seq: Vec<u8> = match key {
            Key::Character(ch) if ctrl && ch.len() == 1 => vec![ch.as_bytes()[0] & 0x1f],
            Key::Named(NamedKey::Enter) if shift || ctrl => {
                format!("\x1b[13;{}u", modifier()).into_bytes()
            }
            Key::Named(NamedKey::Enter) => b"\r".to_vec(),
            Key::Named(NamedKey::Backspace) if ctrl => vec![0x08],
            Key::Named(NamedKey::Backspace) if alt => vec![0x1b, 0x7f],
            Key::Named(NamedKey::Backspace) => vec![0x7f],
            Key::Named(NamedKey::Delete) if alt || ctrl || shift => {
                format!("\x1b[3;{}~", modifier()).into_bytes()
            }
            Key::Named(NamedKey::Delete) => b"\x1b[3~".to_vec(),
            Key::Named(NamedKey::Tab) if shift => b"\x1b[Z".to_vec(),
            Key::Named(NamedKey::Tab) => b"\t".to_vec(),
            Key::Named(NamedKey::Escape) => vec![0x1b],
            Key::Named(
                dir @ (NamedKey::ArrowUp
                | NamedKey::ArrowDown
                | NamedKey::ArrowLeft
                | NamedKey::ArrowRight),
            ) => {
                let ch = match dir {
                    NamedKey::ArrowUp => 'A',
                    NamedKey::ArrowDown => 'B',
                    NamedKey::ArrowRight => 'C',
                    NamedKey::ArrowLeft => 'D',
                    _ => unreachable!(),
                };
                if shift || ctrl {
                    format!("\x1b[1;{}{ch}", modifier()).into_bytes()
                } else {
                    vec![0x1b, b'[', ch as u8]
                }
            }
            Key::Named(NamedKey::Home) => {
                self.scroll(i32::MAX);
                if self.term.borrow().display_offset() != 0 {
                    return Ok(true);
                }
                if shift || ctrl {
                    format!("\x1b[1;{}H", modifier()).into_bytes()
                } else {
                    b"\x1b[H".to_vec()
                }
            }
            Key::Named(NamedKey::End) => {
                if self.term.borrow().display_offset() != 0 {
                    self.scroll_to_bottom();
                    return Ok(true);
                }
                if shift || ctrl {
                    format!("\x1b[1;{}F", modifier()).into_bytes()
                } else {
                    b"\x1b[F".to_vec()
                }
            }
            Key::Character(ch) => ch.as_bytes().to_vec(),
            Key::Named(NamedKey::Shift) => {
                self.shift_pressed(true);
                return Ok(true);
            }
            _ => return Ok(false),
        };

        self.write(&seq)?;
        Ok(true)
    }

    /// Paste text into the backend, wrapping in bracketed-paste markers if the app enabled them.
    pub fn paste(&self, text: &str) -> Result<(), TerminalError> {
        if self.mode().contains(Mode::BRACKETED_PASTE) {
            let filtered = text.replace(['\x1b', '\x03'], "");
            self.write_raw(b"\x1b[200~")?;
            self.write_raw(filtered.as_bytes())?;
            self.write_raw(b"\x1b[201~")?;
        } else {
            let normalized = text.replace("\r\n", "\r").replace('\n', "\r");
            self.write_raw(normalized.as_bytes())?;
        }
        Ok(())
    }

    /// Report a keyboard focus change to the program if it enabled focus reporting (mode 1004).
    pub fn focus_changed(&self, focused: bool) {
        if self.mode().contains(Mode::FOCUS_IN_OUT) {
            let _ = self.write_raw(if focused { b"\x1b[I" } else { b"\x1b[O" });
        }
    }

    /// Write data to the backend without resetting scroll or selection state.
    fn write_raw(&self, data: &[u8]) -> Result<(), TerminalError> {
        let mut backend = self.backend.borrow_mut();
        let backend = backend.as_mut().ok_or(TerminalError::Closed)?;
        backend.write(data)
    }

    /// Resize the terminal. Lossless: the grid reflows on width, preserves scrollback on height.
    pub fn resize(&self, rows: u16, cols: u16) {
        // Backend first so SIGWINCH reaches the program before we update locally.
        if let Some(backend) = &mut *self.backend.borrow_mut() {
            backend.resize(rows, cols);
        }

        self.term
            .borrow_mut()
            .resize(CrosswordsSize::new(cols as usize, rows as usize));
        self.row_cache.borrow_mut().set_capacity(rows as usize);
    }

    /// Scroll by delta. Positive moves up into scrollback (vt100 convention).
    pub fn scroll(&self, delta: i32) {
        self.scroll_to(Scroll::Delta(delta));
    }

    /// Scroll to the bottom of the buffer.
    pub fn scroll_to_bottom(&self) {
        self.scroll_to(Scroll::Bottom);
    }

    fn scroll_to(&self, target: Scroll) {
        let mut term = self.term.borrow_mut();
        if term.mode().contains(Mode::ALT_SCREEN) {
            return;
        }
        term.scroll_display(target);
        Platform::get().current_window().request_redraw();
    }

    /// Current working directory reported via OSC 7.
    pub fn cwd(&self) -> Option<PathBuf> {
        self.term.borrow().current_directory.clone()
    }

    /// Window title reported via OSC 0 / 2.
    pub fn title(&self) -> Option<String> {
        self.title.borrow().clone()
    }

    /// Latest clipboard content set via OSC 52.
    pub fn clipboard_content(&self) -> Option<String> {
        self.clipboard_content.borrow().clone()
    }

    /// Snapshot of the active terminal mode bits.
    fn mode(&self) -> Mode {
        self.term.borrow().mode()
    }

    fn pressed_button(&self) -> Option<TerminalMouseButton> {
        self.inner.borrow().pressed_button
    }

    fn set_pressed_button(&self, button: Option<TerminalMouseButton>) {
        self.inner.borrow_mut().pressed_button = button;
    }

    fn is_shift_held(&self) -> bool {
        self.inner.borrow().modifiers.contains(Modifiers::SHIFT)
    }

    /// Handle a mouse move/drag. `row` and `col` are fractional cell units.
    /// The fraction of `col` picks which cell half anchors the selection.
    pub fn mouse_move(&self, row: f32, col: f32) {
        let held = self.pressed_button();

        if self.is_shift_held() && held.is_some() {
            self.update_selection(row, col);
            return;
        }

        let mode = self.mode();
        if mode.contains(Mode::MOUSE_MOTION) {
            // Any-motion mode: report regardless of button state.
            let _ = self
                .write_raw(encode_mouse_move(row as usize, col as usize, held, mode).as_bytes());
        } else if mode.contains(Mode::MOUSE_DRAG)
            && let Some(button) = held
        {
            // Button-motion mode: only while a button is held.
            let _ = self.write_raw(
                encode_mouse_move(row as usize, col as usize, Some(button), mode).as_bytes(),
            );
        } else if !mode.intersects(Mode::MOUSE_MODE) && held.is_some() {
            self.update_selection(row, col);
        }
    }

    /// Handle a mouse button press. `selection_type` picks the selection kind when not in mouse mode:
    /// [`SelectionType::Semantic`] for double-click (word), [`SelectionType::Lines`] for triple-click.
    /// See [`Self::mouse_move`] for the fractional coordinates.
    pub fn mouse_down(
        &self,
        row: f32,
        col: f32,
        button: TerminalMouseButton,
        selection_type: SelectionType,
    ) {
        self.set_pressed_button(Some(button));

        let mode = self.mode();
        if !self.is_shift_held() && mode.intersects(Mode::MOUSE_MODE) {
            let _ = self
                .write_raw(encode_mouse_press(row as usize, col as usize, button, mode).as_bytes());
        } else {
            self.start_selection(row, col, selection_type);
        }
    }

    /// Handle a mouse button release.
    pub fn mouse_up(&self, row: f32, col: f32, button: TerminalMouseButton) {
        self.set_pressed_button(None);

        let mode = self.mode();
        if !self.is_shift_held() && mode.intersects(Mode::MOUSE_MODE) {
            let _ = self.write_raw(
                encode_mouse_release(row as usize, col as usize, button, mode).as_bytes(),
            );
        }
    }

    /// Handle a mouse button release from outside the terminal viewport.
    pub fn release(&self) {
        self.set_pressed_button(None);
    }

    /// Route a wheel event to scrollback, backend mouse, or arrow-key sequences
    /// depending on the active mouse mode and alt-screen state (matches wezterm/kitty).
    pub fn wheel(&self, delta_y: f64, row: f32, col: f32) {
        // Lines per event from the OS delta, capped to keep flings sane.
        let lines = (delta_y.abs().ceil() as i32).clamp(1, 10);
        let scroll_delta = if delta_y > 0.0 { lines } else { -lines };

        let mode = self.mode();

        if self.term.borrow().display_offset() > 0 {
            self.scroll(scroll_delta);
        } else if mode.intersects(Mode::MOUSE_MODE) {
            let _ = self.write_raw(
                encode_wheel_event(row as usize, col as usize, delta_y, mode).as_bytes(),
            );
        } else if mode.contains(Mode::ALT_SCREEN) {
            let app_cursor = mode.contains(Mode::APP_CURSOR);
            let key = match (delta_y > 0.0, app_cursor) {
                (true, true) => "\x1bOA",
                (true, false) => "\x1b[A",
                (false, true) => "\x1bOB",
                (false, false) => "\x1b[B",
            };
            for _ in 0..lines {
                let _ = self.write_raw(key.as_bytes());
            }
        } else {
            self.scroll(scroll_delta);
        }
    }

    /// Borrow the underlying rio-vt `Crosswords` for direct read access.
    pub fn term(&self) -> std::cell::Ref<'_, Crosswords<EventProxy>> {
        self.term.borrow()
    }

    /// Future that completes each time new output is received from the backend.
    pub fn output_received(&self) -> impl std::future::Future<Output = ()> + '_ {
        self.output_notifier.notified()
    }

    /// Future that completes when the window title changes (OSC 0 / OSC 2).
    pub fn title_changed(&self) -> impl std::future::Future<Output = ()> + '_ {
        self.title_notifier.notified()
    }

    /// Future that completes when clipboard content changes (OSC 52).
    pub fn clipboard_changed(&self) -> impl std::future::Future<Output = ()> + '_ {
        self.clipboard_notifier.notified()
    }

    /// Future that completes when the terminal closes.
    pub fn closed(&self) -> impl std::future::Future<Output = ()> + '_ {
        self.closer_notifier.notified()
    }

    /// Unique identifier for this terminal instance.
    pub fn id(&self) -> TerminalId {
        self.id
    }

    /// Track whether shift is currently pressed.
    pub fn shift_pressed(&self, pressed: bool) {
        let mods = &mut self.inner.borrow_mut().modifiers;
        if pressed {
            mods.insert(Modifiers::SHIFT);
        } else {
            mods.remove(Modifiers::SHIFT);
        }
    }

    /// Start a new selection of `selection_type`. See [`Self::mouse_move`] for the fractional coordinates.
    pub fn start_selection(&self, row: f32, col: f32, selection_type: SelectionType) {
        let (point, side) = self.point_and_side_at(row, col);
        self.term.borrow_mut().selection = Some(Selection::new(selection_type, point, side));
        Platform::get().current_window().request_redraw();
    }

    /// Extend the in-progress selection, if any.
    pub fn update_selection(&self, row: f32, col: f32) {
        let (point, side) = self.point_and_side_at(row, col);
        if let Some(selection) = self.term.borrow_mut().selection.as_mut() {
            selection.update(point, side);
            Platform::get().current_window().request_redraw();
        }
    }

    /// Currently selected text, if any.
    pub fn get_selected_text(&self) -> Option<String> {
        self.term.borrow().selection_to_string()
    }

    /// URI at viewport `row`/`col` if the cell carries an OSC 8 hyperlink or
    /// sits inside a detected plain-text URL. See [`Self::mouse_move`] for the
    /// fractional coordinate convention.
    pub fn hyperlink_at(&self, row: f32, col: f32) -> Option<String> {
        let term = self.term.borrow();
        let viewport_row = (row.max(0.0) as usize).min(term.screen_lines().saturating_sub(1));
        let column = (col.max(0.0) as usize).min(term.columns().saturating_sub(1));
        let square =
            term.grid[Line(viewport_row as i32 - term.display_offset() as i32)][Column(column)];
        if !square.is_bg_only()
            && let Some(hyperlink) = square
                .extras_id()
                .and_then(|id| term.grid.extras_table.get(id))
                .and_then(|extras| extras.hyperlink.as_ref())
        {
            return Some(hyperlink.uri().to_owned());
        }

        let mut cells = Vec::new();
        snapshot_row(&term, viewport_row, &mut cells);
        url_at(&cells, column)
    }

    /// Grid point and cell half (left vs right) for a pointer at fractional cell coordinates.
    fn point_and_side_at(&self, row: f32, col: f32) -> (Pos, Side) {
        let term = self.term.borrow();
        let col = col.max(0.0);
        let row = (row.max(0.0) as usize).min(term.screen_lines().saturating_sub(1));
        let column = (col as usize).min(term.columns().saturating_sub(1));
        let line = row as i32 - term.display_offset() as i32;
        let side = if col.fract() < 0.5 {
            Side::Left
        } else {
            Side::Right
        };
        (Pos::new(Line(line), Column(column)), side)
    }
}