rho-coding-agent 3.10.0

A fast Rust agent harness with a small footprint and opinionated defaults
Documentation
//! OSC 8 hyperlinks over drawn cells.
//!
//! Ratatui cells carry no link, so a frame's painter hands its links to the
//! backend through [`FrameHyperlinks`], and the backend wraps each run of
//! linked cells it writes in OSC 8. A painter marks linked cells
//! `CellDiffOption::AlwaysUpdate`, so every frame writes them again: a cell
//! that keeps its text and style while its link comes or goes is still
//! rewritten with the right link. Terminals without OSC 8 ignore the
//! sequence and show the text alone.

use std::{
    io::{self, Write},
    ops::Range,
    sync::{Arc, Mutex, PoisonError},
};

use crossterm::{cursor::MoveTo, queue};
use ratatui::{backend::Backend, buffer::Cell};

#[cfg(test)]
#[path = "hyperlinks_tests.rs"]
mod tests;

/// A hyperlink over columns `x` of screen row `y`.
#[derive(Clone, Debug, PartialEq, Eq)]
pub(crate) struct ScreenLink {
    pub(crate) y: u16,
    pub(crate) x: Range<u16>,
    pub(crate) url: Arc<str>,
}

/// The links of the next frame, set by its painter while ratatui draws it
/// and taken by the backend when that frame's cells are written. A frame
/// whose painter sets none, such as a picker's, writes no links.
#[derive(Clone, Debug, Default)]
pub(crate) struct FrameHyperlinks(Arc<Mutex<Vec<ScreenLink>>>);

impl FrameHyperlinks {
    pub(crate) fn set(&self, links: Vec<ScreenLink>) {
        *self.0.lock().unwrap_or_else(PoisonError::into_inner) = links;
    }

    pub(super) fn take(&self) -> Vec<ScreenLink> {
        std::mem::take(&mut *self.0.lock().unwrap_or_else(PoisonError::into_inner))
    }
}

/// Draws `cells` through `inner`, wrapping each run of cells inside one of
/// `links` in OSC 8. A URL holding a control character, which could end the
/// sequence early, is written as no link.
pub(super) fn draw_linked<B>(
    inner: &mut B,
    cells: Vec<(u16, u16, &Cell)>,
    links: &[ScreenLink],
) -> io::Result<()>
where
    B: Backend<Error = io::Error> + Write,
{
    let links: Vec<&ScreenLink> = links
        .iter()
        .filter(|link| !link.url.chars().any(char::is_control))
        .collect();
    let link_at = |&(x, y, _): &(u16, u16, &Cell)| {
        links
            .iter()
            .position(|link| link.y == y && link.x.contains(&x))
    };
    let mut cells = cells.into_iter().peekable();
    while let Some(first) = cells.next() {
        let link = link_at(&first);
        let mut run = vec![first];
        while let Some(next) = cells.next_if(|cell| link_at(cell) == link) {
            run.push(next);
        }
        match link {
            Some(index) => {
                // Open the link where its first cell is, so the terminal
                // (and a reader of the stream) sees where it starts.
                queue!(inner, MoveTo(first.0, first.1))?;
                write!(inner, "\x1b]8;;{}\x1b\\", links[index].url)?;
                let drawn = inner.draw(run.into_iter());
                // Close the link even when the draw failed, so it cannot
                // swallow later output; the draw's error wins.
                let closed = write!(inner, "\x1b]8;;\x1b\\");
                drawn.and(closed)?;
            }
            None => inner.draw(run.into_iter())?,
        }
    }
    Ok(())
}