Debian Codegraph @

Xtermina/src/escape/osc.rs

raw symbols SCIP
1 //! Operating System Command (OSC) escape sequences.
2 //!
3 //! OSC sequences carry string-style terminal integration commands such as window titles, clipboard
4 //! access, and dynamic color queries. Termina stores string payloads by borrowing where possible
5 //! so callers can format an OSC command without first allocating an owned [`String`].
6 //!
7 //! # Examples
8 //!
9 //! ```
10 //! use termina::escape::osc::Osc;
11 //!
12 //! assert_eq!(Osc::SetWindowTitle("demo").to_string(), "\x1b]2;demo\x1b\\");
13 //! ```
14 //!
15 //! OSC 52 selection payloads are base64-encoded when formatted:
16 //!
17 //! ```
18 //! use termina::escape::osc::{Osc, Selection};
19 //!
20 //! let command = Osc::SetSelection(Selection::CLIPBOARD, "copied text");
21 //! assert_eq!(command.to_string(), "\x1b]52;c;Y29waWVkIHRleHQ=\x1b\\");
22 //! ```
23 //!
24 //! # Implementation Notes
25 //!
26 //! This is intentionally a shallow copy of [termwiz's OSC support]. Termina removes the
27 //! macro-heavy parts, replaces the base64 implementation, and changes command payloads to borrow
28 //! `str` values instead of owning [`String`] values.
29 //!
30 //! [termwiz's OSC support]: https://docs.rs/termwiz/latest/termwiz/escape/struct.Osc.html
31
32 use std::fmt::{self, Display};
33
34 use crate::{base64, style::RgbColor};
35
36 /// An Operating System Command string control.
37 ///
38 /// Formatting writes the OSC introducer, a command number or command letter, the command payload,
39 /// and the string terminator. The numbered variants use common xterm-compatible assignments: OSC
40 /// 2 sets the window title, OSC 52 manages selections, and OSC 10-19 manage dynamic colors.
41 #[derive(Debug, Clone, PartialEq, Eq)]
42 pub enum Osc<'a> {
43 /// OSC 0: set both the icon name and window title.
44 SetIconNameAndWindowTitle(&'a str),
45
46 /// OSC 2: set the window title.
47 SetWindowTitle(&'a str),
48
49 /// Sun terminal form: set the window title with `OSC l`.
50 SetWindowTitleSun(&'a str),
51
52 /// OSC 1: set the icon name.
53 SetIconName(&'a str),
54
55 /// Sun terminal form: set the icon name with `OSC L`.
56 SetIconNameSun(&'a str),
57
58 /// OSC 52: clear one or more terminal selections described by [`Selection`].
59 ///
60 /// Terminals use OSC 52 to expose clipboard-like selections. Clearing sends a selection target
61 /// without content.
62 ClearSelection(Selection),
63
64 /// OSC 52: query one or more terminal selections described by [`Selection`].
65 ///
66 /// Querying sends `?` as the content payload and lets a cooperating terminal report the
67 /// selection contents.
68 QuerySelection(Selection),
69
70 /// OSC 52: set one or more terminal selections described by [`Selection`].
71 ///
72 /// The string payload is base64-encoded when formatted, as required by OSC 52.
73 SetSelection(Selection, &'a str),
74
75 /// OSC 10-19: change or query dynamic terminal colors.
76 ///
77 /// Each [`DynamicColorNumber`] identifies the color slot. [`ColorOrQuery::Query`] formats as
78 /// `?`, asking the terminal to report its current value; [`ColorOrQuery::Color`] carries the
79 /// [`RgbColor`] to set.
80 ChangeDynamicColors(DynamicColorNumber, Vec<ColorOrQuery>),
81
82 /// OSC 110-119: reset a [`DynamicColorNumber`] slot to its default value.
83 ///
84 /// xterm defines reset commands by adding 100 to the dynamic color number.
85 ResetDynamicColor(DynamicColorNumber),
86 // TODO: I didn't copy many available commands yet...
87 }
88
89 impl Display for Osc<'_> {
90 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
91 f.write_str(super::OSC)?;
92 match self {
93 Self::SetIconNameAndWindowTitle(s) => write!(f, "0;{s}")?,
94 Self::SetWindowTitle(s) => write!(f, "2;{s}")?,
95 Self::SetWindowTitleSun(s) => write!(f, "l{s}")?,
96 Self::SetIconName(s) => write!(f, "1;{s}")?,
97 Self::SetIconNameSun(s) => write!(f, "L{s}")?,
98 Self::ClearSelection(selection) => write!(f, "52;{selection}")?,
99 Self::QuerySelection(selection) => write!(f, "52;{selection};?")?,
100 Self::SetSelection(selection, content) => {
101 // TODO: it'd be nice to avoid allocating a string to base64 encode.
102 write!(f, "52;{selection};{}", base64::encode(content.as_bytes()))?
103 }
104 Self::ChangeDynamicColors(color, colors) => {
105 write!(f, "{}", *color as u8)?;
106 for color in colors {
107 write!(f, ";{color}")?
108 }
109 }
110 Self::ResetDynamicColor(color) => write!(f, "{}", 100 + *color as u8)?,
111 }
112 f.write_str(super::ST)?;
113 Ok(())
114 }
115 }
116
117 bitflags::bitflags! {
118 /// OSC 52 selection targets.
119 ///
120 /// Multiple targets can be combined. Formatting concatenates the target letters/numbers in the
121 /// order expected by xterm-compatible terminals.
122 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
123 pub struct Selection : u16 {
124 /// No OSC 52 selection target.
125 const NONE = 0;
126
127 /// OSC 52 selection target `c`: the clipboard selection.
128 const CLIPBOARD = 1<<1;
129
130 /// OSC 52 selection target `p`: the primary selection.
131 const PRIMARY=1<<2;
132
133 /// OSC 52 selection target `s`: the select selection.
134 const SELECT=1<<3;
135
136 /// OSC 52 selection target `0`: cut buffer 0.
137 const CUT0=1<<4;
138
139 /// OSC 52 selection target `1`: cut buffer 1.
140 const CUT1=1<<5;
141
142 /// OSC 52 selection target `2`: cut buffer 2.
143 const CUT2=1<<6;
144
145 /// OSC 52 selection target `3`: cut buffer 3.
146 const CUT3=1<<7;
147
148 /// OSC 52 selection target `4`: cut buffer 4.
149 const CUT4=1<<8;
150
151 /// OSC 52 selection target `5`: cut buffer 5.
152 const CUT5=1<<9;
153
154 /// OSC 52 selection target `6`: cut buffer 6.
155 const CUT6=1<<10;
156
157 /// OSC 52 selection target `7`: cut buffer 7.
158 const CUT7=1<<11;
159
160 /// OSC 52 selection target `8`: cut buffer 8.
161 const CUT8=1<<12;
162
163 /// OSC 52 selection target `9`: cut buffer 9.
164 const CUT9=1<<13;
165 }
166 }
167
168 impl Display for Selection {
169 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
170 if self.contains(Self::CLIPBOARD) {
171 write!(f, "c")?;
172 }
173 if self.contains(Self::PRIMARY) {
174 write!(f, "p")?;
175 }
176 if self.contains(Self::SELECT) {
177 write!(f, "s")?;
178 }
179 if self.contains(Self::CUT0) {
180 write!(f, "0")?;
181 }
182 if self.contains(Self::CUT1) {
183 write!(f, "1")?;
184 }
185 if self.contains(Self::CUT2) {
186 write!(f, "2")?;
187 }
188 if self.contains(Self::CUT3) {
189 write!(f, "3")?;
190 }
191 if self.contains(Self::CUT4) {
192 write!(f, "4")?;
193 }
194 if self.contains(Self::CUT5) {
195 write!(f, "5")?;
196 }
197 if self.contains(Self::CUT6) {
198 write!(f, "6")?;
199 }
200 if self.contains(Self::CUT7) {
201 write!(f, "7")?;
202 }
203 if self.contains(Self::CUT8) {
204 write!(f, "8")?;
205 }
206 if self.contains(Self::CUT9) {
207 write!(f, "9")?;
208 }
209 Ok(())
210 }
211 }
212
213 /// Dynamic color slots addressed by OSC 10-19.
214 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
215 #[repr(u8)]
216 pub enum DynamicColorNumber {
217 /// OSC 10: the default text foreground color used for normal cells.
218 TextForegroundColor = 10,
219 /// OSC 11: the default text background color used for normal cells.
220 TextBackgroundColor = 11,
221 /// OSC 12: the text cursor color.
222 TextCursorColor = 12,
223 /// OSC 13: the pointer foreground color used by xterm-compatible terminals.
224 MouseForegroundColor = 13,
225 /// OSC 14: the pointer background color used by xterm-compatible terminals.
226 MouseBackgroundColor = 14,
227 /// OSC 15: the Tektronix foreground color.
228 TektronixForegroundColor = 15,
229 /// OSC 16: the Tektronix background color.
230 TektronixBackgroundColor = 16,
231 /// OSC 17: the selection highlight background color.
232 HighlightBackgroundColor = 17,
233 /// OSC 18: the Tektronix cursor color.
234 TektronixCursorColor = 18,
235 /// OSC 19: the selection highlight foreground color.
236 HighlightForegroundColor = 19,
237 }
238
239 impl DynamicColorNumber {
240 pub(crate) fn from_index(index: u8) -> Option<Self> {
241 match index {
242 10 => Some(Self::TextForegroundColor),
243 11 => Some(Self::TextBackgroundColor),
244 12 => Some(Self::TextCursorColor),
245 13 => Some(Self::MouseForegroundColor),
246 14 => Some(Self::MouseBackgroundColor),
247 15 => Some(Self::TektronixForegroundColor),
248 16 => Some(Self::TektronixBackgroundColor),
249 17 => Some(Self::HighlightBackgroundColor),
250 18 => Some(Self::TektronixCursorColor),
251 19 => Some(Self::HighlightForegroundColor),
252 _ => None,
253 }
254 }
255 }
256
257 /// A dynamic color value or query marker for OSC color commands.
258 ///
259 /// Use [`Self::Query`] to ask the terminal for a slot's current value, or [`Self::Color`] to set a
260 /// new RGB value:
261 ///
262 /// ```
263 /// use termina::{
264 /// escape::osc::{ColorOrQuery, DynamicColorNumber, Osc},
265 /// style::RgbColor,
266 /// };
267 ///
268 /// let query = Osc::ChangeDynamicColors(
269 /// DynamicColorNumber::TextBackgroundColor,
270 /// vec![ColorOrQuery::Query],
271 /// );
272 /// assert_eq!(query.to_string(), "\x1b]11;?\x1b\\");
273 ///
274 /// let set = Osc::ChangeDynamicColors(
275 /// DynamicColorNumber::TextForegroundColor,
276 /// vec![RgbColor::new(40, 40, 40).into()],
277 /// );
278 /// assert_eq!(set.to_string(), "\x1b]10;rgb:2828/2828/2828\x1b\\");
279 /// ```
280 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
281 pub enum ColorOrQuery {
282 /// Set the dynamic color to an RGB value.
283 ///
284 /// Formatting emits the `rgb:RRRR/GGGG/BBBB` form used by xterm OSC color controls.
285 Color(RgbColor),
286
287 /// Query the current dynamic color value.
288 ///
289 /// Formatting emits `?`, which asks the terminal to report the current value for that slot.
290 Query,
291 }
292
293 impl Display for ColorOrQuery {
294 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
295 match self {
296 ColorOrQuery::Query => write!(f, "?"),
297 ColorOrQuery::Color(c) => {
298 // rgb:RRRR/GGGG/BBBB
299 write!(
300 f,
301 "rgb:{red:02x}{red:02x}/{green:02x}{green:02x}/{blue:02x}{blue:02x}",
302 red = c.red,
303 green = c.green,
304 blue = c.blue
305 )
306 }
307 }
308 }
309 }
310
311 impl From<RgbColor> for ColorOrQuery {
312 fn from(color: RgbColor) -> Self {
313 Self::Color(color)
314 }
315 }
316
317 #[cfg(test)]
318 mod test {
319 use super::*;
320
321 #[test]
322 fn encoding() {
323 // OSC 11 query, asks the terminal for the background color.
324 // <https://terminalguide.namepad.de/seq/osc-11/>
325 // <https://terminalguide.namepad.de/seq/osc-4/>
326 assert_eq!(
327 "\x1b]11;?\x1b\\",
328 Osc::ChangeDynamicColors(
329 DynamicColorNumber::TextBackgroundColor,
330 vec![ColorOrQuery::Query]
331 )
332 .to_string()
333 );
334
335 assert_eq!(
336 "\x1b]11;rgb:2828/2828/2828\x1b\\",
337 Osc::ChangeDynamicColors(
338 DynamicColorNumber::TextBackgroundColor,
339 vec![RgbColor::new(40, 40, 40).into()]
340 )
341 .to_string()
342 );
343 }
344 }