Skip to content

Instantly share code, notes, and snippets.

@tracker1
Created March 17, 2023 14:41
Show Gist options
  • Save tracker1/a66aa0fe10657d186b9ea88688b2e1e0 to your computer and use it in GitHub Desktop.
Save tracker1/a66aa0fe10657d186b9ea88688b2e1e0 to your computer and use it in GitHub Desktop.
Terminal Information
use std::io::{self, Read, Write};
use std::net::TcpStream;
fn get_remote_terminal_info(stream: &mut TcpStream) -> io::Result<(u16, u16, bool, bool, bool)> {
// Send the control code to query the size of the terminal
write!(stream, "\x1b[18t")?;
stream.flush()?;
// Read the response from the terminal
let mut buf = [0u8; 32];
let n = stream.read(&mut buf)?;
let response = std::str::from_utf8(&buf[..n]).unwrap_or_default();
// Extract the size of the terminal from the response
let (width, height) = response
.split(';')
.skip(1)
.take(2)
.filter_map(|s| s.parse::<u16>().ok())
.next()
.unwrap_or((80, 24));
// Send the control code to query the color range of the terminal
write!(stream, "\x1b[0;?q")?;
stream.flush()?;
// Read the response from the terminal
let mut buf = [0u8; 32];
let n = stream.read(&mut buf)?;
let response = std::str::from_utf8(&buf[..n]).unwrap_or_default();
// Check if the terminal supports 256 colors
let supports_256_colors = response.contains(";5;");
// Check if the terminal supports 24-bit color
let supports_24_bit_color = response.contains(";2;");
// Send the control code to query the UTF-8 support of the terminal
write!(stream, "\x1b[6n")?;
stream.flush()?;
// Read the response from the terminal
let mut buf = [0u8; 32];
let n = stream.read(&mut buf)?;
let response = std::str::from_utf8(&buf[..n]).unwrap_or_default();
// Check if the terminal supports UTF-8 encoding
let utf8_support = response.contains("[?1;2C");
Ok((width, height, supports_256_colors, supports_24_bit_color, utf8_support))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment