Skip to main content

libghostty_vt/
focus.rs

1//! Encoding focus gained/lost events into terminal escape sequences
2//! (CSI I / CSI O) for focus reporting mode (mode 1004).
3//!
4//! # Basic Usage
5//!
6//! Use [`Event::encode`] to encode a focus event into a caller-provided
7//! buffer. If the buffer is too small, the method returns
8//! `Err(Error::OutOfSpace { required })` where `required` is the required size.
9//!
10//! # Example
11//!
12//! ```rust
13//! use libghostty_vt::focus::Event;
14//! let mut buf = [0u8; 8];
15//! if let Ok(written) = Event::Gained.encode(&mut buf) {
16//!     println!("Encoded {written} bytes: {:?}", &buf[..written]);
17//! }
18//! ```
19
20use crate::{
21    error::{Result, from_result_with_len},
22    ffi,
23};
24
25/// Event type for focus reporting mode (mode 1004).
26#[derive(Clone, Copy, Debug, PartialEq, Eq)]
27pub enum Event {
28    /// Terminal window gained focus.
29    Gained,
30    /// Terminal window lost focus.
31    Lost,
32}
33
34impl Event {
35    /// Encode a focus event into a terminal escape sequence.
36    ///
37    /// Encodes a focus gained (CSI I) or focus lost (CSI O)
38    /// report into the provided buffer.
39    ///
40    /// If the buffer is too small, the method returns
41    /// `Err(Error::OutOfSpace { required })` where `required` is the required size.
42    /// The caller can then retry with a sufficiently sized buffer.
43    pub fn encode(self, buf: &mut [u8]) -> Result<usize> {
44        let mut written: usize = 0;
45        let result = unsafe {
46            ffi::ghostty_focus_encode(
47                self.into(),
48                buf.as_mut_ptr().cast(),
49                buf.len(),
50                &raw mut written,
51            )
52        };
53        from_result_with_len(result, written)
54    }
55}
56
57impl From<Event> for ffi::GhosttyFocusEvent {
58    fn from(value: Event) -> Self {
59        match value {
60            Event::Gained => ffi::GhosttyFocusEvent_GHOSTTY_FOCUS_GAINED,
61            Event::Lost => ffi::GhosttyFocusEvent_GHOSTTY_FOCUS_LOST,
62        }
63    }
64}