ratresume 0.1.0

A Rust library for reporting program-resume commands with OSC 7577
Documentation
use std::{
    env,
    io::Write,
    path::{Path, PathBuf},
};

use crate::{Error, TOKEN_ENV, protocol};

/// Sends resume and clear reports to the terminal that launched this process.
///
/// A reporter captures the terminal token once, so applications can keep one
/// value and use it each time their restorable state changes.
pub struct Reporter {
    token: String,
    last_report: Option<ResumeCommand>,
}

#[derive(PartialEq, Eq)]
struct ResumeCommand {
    argv: Vec<String>,
    cwd: Option<PathBuf>,
}

impl Reporter {
    /// Create a reporter if the terminal provided [`TOKEN_ENV`].
    ///
    /// Returns `Ok(None)` when the variable is absent. A present but invalid
    /// token returns an error.
    pub fn from_env() -> Result<Option<Self>, Error> {
        let Some(token) = env::var_os(TOKEN_ENV) else {
            return Ok(None);
        };
        let token = token.to_str().ok_or(Error::InvalidToken)?;
        Self::new(token).map(Some)
    }

    /// Create a reporter with an explicit terminal token.
    pub fn new(token: impl Into<String>) -> Result<Self, Error> {
        let token = token.into();
        protocol::validate_token(&token)?;
        Ok(Self {
            token,
            last_report: None,
        })
    }

    /// Report how to restore this program, unless the command is unchanged.
    ///
    /// The resume command consists of:
    /// - `argv`: The executable and its arguments. `argv[0]` must be a bare
    ///   executable name or an absolute path. Arguments are passed individually,
    ///   not through a shell.
    /// - `cwd`: The optional absolute UTF-8 working directory.
    ///
    /// On Unix, the report is written to the controlling terminal. On Windows,
    /// it is written to standard output.
    pub fn report(&mut self, argv: &[String], cwd: Option<&Path>) -> Result<(), Error> {
        let mut terminal = terminal_writer()?;
        self.report_to(&mut terminal, argv, cwd)
    }

    /// Re-send the current resume command after regaining the terminal.
    ///
    /// Call this after returning from a child process or a terminal suspend.
    ///
    /// Returns `Ok(())` when no command has been reported yet.
    pub fn refresh(&self) -> Result<(), Error> {
        if self.last_report.is_none() {
            return Ok(());
        }
        let mut terminal = terminal_writer()?;
        self.refresh_to(&mut terminal)
    }

    /// Clear this process's resume record.
    ///
    /// Call this when the user intentionally exits and no longer wants the
    /// program restored. Do not call it because the terminal is closing or has
    /// been lost.
    pub fn clear(&mut self) -> Result<(), Error> {
        let mut terminal = terminal_writer()?;
        self.clear_to(&mut terminal)
    }

    /// Report to a caller-provided writer, unless the command is unchanged.
    ///
    /// This is useful when the application manages terminal output itself and
    /// for testing the encoded protocol message.
    pub fn report_to<W: Write>(
        &mut self,
        writer: &mut W,
        argv: &[String],
        cwd: Option<&Path>,
    ) -> Result<(), Error> {
        let command = ResumeCommand {
            argv: argv.to_vec(),
            cwd: cwd.map(Path::to_path_buf),
        };
        if self.last_report.as_ref() == Some(&command) {
            return Ok(());
        }

        // Encode first so invalid commands do not leave a partial report. If
        // the command changed to an invalid one, clear any stale terminal record.
        let mut report = Vec::new();
        if let Err(error) = protocol::write_report(&mut report, argv, cwd, &self.token) {
            if matches!(&error, Error::InvalidReport(_)) {
                self.clear_to(writer)?;
            }
            return Err(error);
        }
        writer.write_all(&report)?;
        writer.flush()?;
        self.last_report = Some(command);
        Ok(())
    }

    /// Re-send the current resume command to a caller-provided writer.
    pub fn refresh_to<W: Write>(&self, writer: &mut W) -> Result<(), Error> {
        let Some(command) = self.last_report.as_ref() else {
            return Ok(());
        };
        let argv = command.argv.clone();
        let cwd = command.cwd.clone();
        protocol::write_report(writer, &argv, cwd.as_deref(), &self.token)
    }

    /// Write a clear report to a caller-provided writer.
    pub fn clear_to<W: Write>(&mut self, writer: &mut W) -> Result<(), Error> {
        protocol::write_clear(writer, &self.token)?;
        self.last_report = None;
        Ok(())
    }
}

#[cfg(unix)]
fn terminal_writer() -> Result<Box<dyn Write>, Error> {
    use std::fs::OpenOptions;
    Ok(Box::new(OpenOptions::new().write(true).open("/dev/tty")?))
}

#[cfg(windows)]
fn terminal_writer() -> Result<Box<dyn Write>, Error> {
    Ok(Box::new(std::io::stdout()))
}

#[cfg(not(any(unix, windows)))]
fn terminal_writer() -> Result<Box<dyn Write>, Error> {
    Err(Error::UnsupportedPlatform)
}