xterm-query-0.5.0/.cargo_vcs_info.json0000644000000001360000000000100133400ustar { "git": { "sha1": "0f8a0b66edb484c9053132a5c7f84397255474ad" }, "path_in_vcs": "" }xterm-query-0.5.0/.gitignore000064400000000000000000000000221046102023000141120ustar 00000000000000Cargo.lock target xterm-query-0.5.0/Cargo.lock0000644000000165400000000000100113210ustar # This file is automatically @generated by Cargo. # It is not intended for manual editing. version = 3 [[package]] name = "autocfg" version = "1.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d468802bab17cbc0cc575e9b053f41e72aa36bfa6b7f55e3529ffa43161b97fa" [[package]] name = "bitflags" version = "1.3.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "bef38d45163c2f1dde094a7dfd33ccf595c92905c8f8f4fdc18d06fb1037718a" [[package]] name = "bitflags" version = "2.4.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ed570934406eb16438a4e976b1b4500774099c13b8cb96eec99f620f05090ddf" [[package]] name = "cfg-if" version = "1.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "baf1de4339761588bc0619e3cbc0120ee582ebb74b53b4efbf79117bd2da40fd" [[package]] name = "cfg_aliases" version = "0.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "613afe47fcd5fac7ccf1db93babcb082c5994d996f20b8b159f2ad1658eb5724" [[package]] name = "crossterm" version = "0.21.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "486d44227f71a1ef39554c0dc47e44b9f4139927c75043312690c3f476d1d788" dependencies = [ "bitflags 1.3.2", "crossterm_winapi", "libc", "mio", "parking_lot", "signal-hook", "signal-hook-mio", "winapi", ] [[package]] name = "crossterm_winapi" version = "0.8.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3a6966607622438301997d3dac0d2f6e9a90c68bb6bc1785ea98456ab93c0507" dependencies = [ "winapi", ] [[package]] name = "instant" version = "0.1.12" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7a5bbe824c507c5da5956355e86a746d82e0e1464f65d862cc5e71da70e94b2c" dependencies = [ "cfg-if", ] [[package]] name = "libc" version = "0.2.159" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "561d97a539a36e26a9a5fad1ea11a3039a67714694aaa379433e580854bc3dc5" [[package]] name = "lock_api" version = "0.4.11" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3c168f8615b12bc01f9c17e2eb0cc07dcae1940121185446edc3744920e8ef45" dependencies = [ "autocfg", "scopeguard", ] [[package]] name = "log" version = "0.4.21" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "90ed8c1e510134f979dbc4f070f87d4313098b704861a105fe34231c70a3901c" [[package]] name = "mio" version = "0.7.14" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8067b404fe97c70829f082dec8bcf4f71225d7eaea1d8645349cb76fa06205cc" dependencies = [ "libc", "log", "miow", "ntapi", "winapi", ] [[package]] name = "miow" version = "0.3.7" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b9f1c5b025cda876f66ef43a113f91ebc9f4ccef34843000e0adf6ebbab84e21" dependencies = [ "winapi", ] [[package]] name = "nix" version = "0.29.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "71e2746dc3a24dd78b3cfcb7be93368c6de9963d30f43a6a73998a9cf4b17b46" dependencies = [ "bitflags 2.4.2", "cfg-if", "cfg_aliases", "libc", ] [[package]] name = "ntapi" version = "0.3.7" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c28774a7fd2fbb4f0babd8237ce554b73af68021b5f695a3cebd6c59bac0980f" dependencies = [ "winapi", ] [[package]] name = "parking_lot" version = "0.11.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7d17b78036a60663b797adeaee46f5c9dfebb86948d1255007a1d6be0271ff99" dependencies = [ "instant", "lock_api", "parking_lot_core", ] [[package]] name = "parking_lot_core" version = "0.8.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "60a2cfe6f0ad2bfc16aefa463b497d5c7a5ecd44a23efa72aa342d90177356dc" dependencies = [ "cfg-if", "instant", "libc", "redox_syscall", "smallvec", "winapi", ] [[package]] name = "proc-macro2" version = "1.0.78" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e2422ad645d89c99f8f3e6b88a9fdeca7fabeac836b1002371c4367c8f984aae" dependencies = [ "unicode-ident", ] [[package]] name = "quote" version = "1.0.35" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "291ec9ab5efd934aaf503a6466c5d5251535d108ee747472c3977cc5acc868ef" dependencies = [ "proc-macro2", ] [[package]] name = "redox_syscall" version = "0.2.16" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "fb5a58c1855b4b6819d59012155603f0b22ad30cad752600aadfcb695265519a" dependencies = [ "bitflags 1.3.2", ] [[package]] name = "scopeguard" version = "1.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49" [[package]] name = "signal-hook" version = "0.3.17" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8621587d4798caf8eb44879d42e56b9a93ea5dcd315a6487c357130095b62801" dependencies = [ "libc", "signal-hook-registry", ] [[package]] name = "signal-hook-mio" version = "0.2.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "29ad2e15f37ec9a6cc544097b78a1ec90001e9f71b81338ca39f430adaca99af" dependencies = [ "libc", "mio", "signal-hook", ] [[package]] name = "signal-hook-registry" version = "1.4.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d8229b473baa5980ac72ef434c4415e70c4b5e71b423043adb4ba059f89c99a1" dependencies = [ "libc", ] [[package]] name = "smallvec" version = "1.13.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e6ecd384b10a64542d77071bd64bd7b231f4ed5940fba55e98c3de13824cf3d7" [[package]] name = "syn" version = "2.0.52" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b699d15b36d1f02c3e7c69f8ffef53de37aefae075d8488d4ba1a7788d574a07" dependencies = [ "proc-macro2", "quote", "unicode-ident", ] [[package]] name = "thiserror" version = "1.0.57" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1e45bcbe8ed29775f228095caf2cd67af7a4ccf756ebff23a306bf3e8b47b24b" dependencies = [ "thiserror-impl", ] [[package]] name = "thiserror-impl" version = "1.0.57" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a953cb265bef375dae3de6663da4d3804eee9682ea80d8e2542529b73c531c81" dependencies = [ "proc-macro2", "quote", "syn", ] [[package]] name = "unicode-ident" version = "1.0.12" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3354b9ac3fae1ff6755cb6db53683adb661634f67557942dea4facebec0fee4b" [[package]] name = "winapi" version = "0.3.9" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "5c839a674fcd7a98952e593242ea400abe93992746761e38641405d28b00f419" dependencies = [ "winapi-i686-pc-windows-gnu", "winapi-x86_64-pc-windows-gnu", ] [[package]] name = "winapi-i686-pc-windows-gnu" version = "0.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ac3b87c63620426dd9b991e5ce0329eff545bccbbb34f3be09ff6fb6ab51b7b6" [[package]] name = "winapi-x86_64-pc-windows-gnu" version = "0.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f" [[package]] name = "xterm-query" version = "0.5.0" dependencies = [ "crossterm", "nix", "thiserror", ] xterm-query-0.5.0/Cargo.toml0000644000000022320000000000100113350ustar # THIS FILE IS AUTOMATICALLY GENERATED BY CARGO # # When uploading crates to the registry Cargo will automatically # "normalize" Cargo.toml files for maximal compatibility # with all versions of Cargo and also rewrite `path` dependencies # to registry (e.g., crates.io) dependencies. # # If you are reading this file be aware that the original Cargo.toml # will likely look very different (and much more reasonable). # See Cargo.toml.orig for the original contents. [package] edition = "2021" name = "xterm-query" version = "0.5.0" authors = ["dystroy "] build = false autobins = false autoexamples = false autotests = false autobenches = false description = "query your terminal" readme = "README.md" keywords = [ "terminal", "xterm", "query", "unix", ] categories = ["command-line-interface"] license = "MIT" repository = "https://github.com/Canop/xterm-query" [lib] name = "xterm_query" path = "src/lib.rs" [[example]] name = "kitty" path = "examples/kitty/main.rs" [dependencies.thiserror] version = "1.0" [dev-dependencies.crossterm] version = "0.21" [target."cfg(unix)".dependencies.nix] version = "0.29" features = ["poll"] xterm-query-0.5.0/Cargo.toml.orig000064400000000000000000000007451046102023000150250ustar 00000000000000[package] name = "xterm-query" version = "0.5.0" edition = "2021" authors = ["dystroy "] repository = "https://github.com/Canop/xterm-query" description = "query your terminal" keywords = ["terminal", "xterm", "query", "unix"] license = "MIT" categories = ["command-line-interface"] readme = "README.md" [dependencies] thiserror = "1.0" [target.'cfg(unix)'.dependencies] nix = { version = "0.29", features = ["poll"] } [dev-dependencies] crossterm = "0.21" xterm-query-0.5.0/LICENSE000064400000000000000000000020461046102023000131370ustar 00000000000000MIT License Copyright (c) 2021 Canop Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. xterm-query-0.5.0/README.md000064400000000000000000000021501046102023000134050ustar 00000000000000[![MIT][s2]][l2] [![Latest Version][s1]][l1] [![docs][s3]][l3] [![Chat on Miaou][s4]][l4] [s1]: https://img.shields.io/crates/v/xterm-query.svg [l1]: https://crates.io/crates/xterm-query [s2]: https://img.shields.io/badge/license-MIT-blue.svg [l2]: LICENSE [s3]: https://docs.rs/xterm-query/badge.svg [l3]: https://docs.rs/xterm-query/ [s4]: https://miaou.dystroy.org/static/shields/room.svg [l4]: https://miaou.dystroy.org/3 Low level library to query the terminal with a CSI sequence and get the result as a string. Notes: - the terminal must already be in raw mode - there's no Windows support (it should be possible with [WSAPoll](https://learn.microsoft.com/en-us/windows/win32/api/winsock2/nf-winsock2-wsapoll) but I don't have any Windows computer to test so a PR would be welcome) The provided example in examples/kitty demonstrates querying the terminal to know whether the [Kitty graphics protocol](https://sw.kovidgoyal.net/kitty/graphics-protocol/) is supported, and manages entering and leaving raw mode. If you think you might use this crate but are unsure, don't hesitate to come to Miaou: [![s4]][s4] xterm-query-0.5.0/examples/kitty/main.rs000064400000000000000000000021611046102023000164040ustar 00000000000000/// In order to query, go to raw mode, query the terminal, then leave raw mode. /// /// This example uses crossterm because I'm used to it but you may use other /// crates to manage raw mode. fn query(query: &str, timeout_ms: u64) -> Result { use crossterm::terminal::*; enable_raw_mode()?; let res = xterm_query::query_osc(query, timeout_ms); disable_raw_mode()?; res } /// Ask the terminal whether the Kitty image protocol is supported pub fn main() { let start = std::time::Instant::now(); match query("\x1b_Gi=31,s=1,v=1,a=q,t=d,f=24;AAAA\x1b\\\x1b[c", 50) { Err(e) => { eprintln!("Error: {}", e); println!("(we should assume the Kitty image protocol isn't available)"); } Ok(response) => { let kitty_support = response.starts_with("_Gi=31;OK"); if kitty_support { println!("Kitty image protocol IS supported"); } else { println!("Kitty image protocol is NOT supported"); } } } println!("Operation took {:?}", start.elapsed()); } xterm-query-0.5.0/src/error.rs000064400000000000000000000012341046102023000144160ustar 00000000000000/// xterm-query error type #[derive(thiserror::Error, Debug)] pub enum XQError { #[error("IO error: {0}")] IO(#[from] std::io::Error), #[error("UTF8 error: {0}")] Utf8(#[from] std::str::Utf8Error), #[error("Wrong answer format: {0}")] WrongFormat(String), #[error("Timeout waiting for xterm")] Timeout, #[error("Terminal error code: {0}")] TerminalError(i64), #[error("Nix error: {0}")] #[cfg(unix)] NixError(#[from] nix::errno::Errno), #[error("Not an OSC response")] NotAnOSCResponse, #[error("Provided buffer is too small")] BufferOverflow, #[error("Unsupported platform")] Unsupported, } xterm-query-0.5.0/src/lib.rs000064400000000000000000000136271046102023000140440ustar 00000000000000mod error; use {nix::errno::Errno, std::os::fd::BorrowedFd}; pub use error::*; /// Query the xterm interface, assuming the terminal is in raw mode /// (or we would block waiting for a newline). pub fn query>(query: &str, timeout_ms: MS) -> Result { // I'll use when default values for const generics // are stabilized for enough rustc versions // See https://github.com/rust-lang/rust/issues/44580 const N: usize = 100; let mut response = [0; N]; let n = query_buffer(query, &mut response, timeout_ms.into())?; let s = std::str::from_utf8(&response[..n])?; Ok(s.to_string()) } /// Query the xterm interface for an OSC sequence, assuming the terminal is in raw mode /// (or we would block waiting for a newline). /// /// The query should be a proper OSC sequence (ie already wrapped, eg "\x1b]11;?\x07") /// as you want it to be sent to stdout but the answer is only the part after the C0 (ESC) /// and before the OSC terminator (BEL or ESC). pub fn query_osc>(query: &str, timeout_ms: MS) -> Result { // I'll use when default values for const generics // are stabilized for enough rustc versions // See https://github.com/rust-lang/rust/issues/44580 const N: usize = 100; let mut response = [0; N]; let resp = query_osc_buffer(query, &mut response, timeout_ms.into())?; let s = std::str::from_utf8(resp)?; Ok(s.to_string()) } /// Query the xterm interface, assuming the terminal is in raw mode /// (or we would block waiting for a newline). /// /// Return the number of bytes read. #[cfg(unix)] pub fn query_buffer>( query: &str, buffer: &mut [u8], timeout_ms: MS, ) -> Result { use std::{ fs::File, io::{self, Read, Write}, os::fd::AsFd, }; let stdout = io::stdout(); let mut stdout = stdout.lock(); write!(stdout, "{}", query)?; stdout.flush()?; let mut stdin = File::open("/dev/tty")?; let stdin_fd = stdin.as_fd(); match wait_for_input(stdin_fd, timeout_ms) { Ok(0) => Err(XQError::Timeout), Ok(_) => { let bytes_written = stdin.read(buffer)?; Ok(bytes_written) } Err(e) => Err(XQError::IO(e.into())), } } /// Query the xterm interface for an OSC response, assuming the terminal is in raw mode /// (or we would block waiting for a newline). /// /// The provided query should be a proper OSC sequence (ie already wrapped, eg "\x1b]11;?\x07") /// /// Return a slice of the buffer containing the response. This slice excludes /// - the response start (ESC) and everything before /// - the response end (ESC or BEL) and everything after /// /// OSC sequence: /// #[cfg(unix)] pub fn query_osc_buffer<'b, MS: Into + Copy>( query: &str, buffer: &'b mut [u8], timeout_ms: MS, ) -> Result<&'b [u8], XQError> { use std::{ fs::File, io::{self, Read, Write}, os::fd::AsFd, }; let stdout = io::stdout(); let mut stdout = stdout.lock(); write!(stdout, "{}", query)?; stdout.flush()?; let mut stdin = File::open("/dev/tty")?; let mut osc_start_idx = None; let mut bytes_written = 0; while bytes_written < buffer.len() { let stdin_fd = stdin.as_fd(); match wait_for_input(stdin_fd, timeout_ms) { Ok(0) => { return Err(XQError::Timeout); } Ok(_) => { let bytes_read = stdin.read(&mut buffer[bytes_written..])?; if bytes_read == 0 { return Err(XQError::NotAnOSCResponse); // EOF } // the sequence must start with a ESC (27) and end either with a ESC or BEL (7) for i in bytes_written..bytes_written + bytes_read { let b = buffer[i]; match osc_start_idx { None => { if b == 27 { osc_start_idx = Some(i); } } Some(start_idx) => { if b == 27 || b == 7 { return Ok(&buffer[start_idx + 1..=i]); } } } } bytes_written += bytes_read; } Err(e) => { return Err(XQError::IO(e.into())); } } } Err(XQError::BufferOverflow) } #[cfg(not(unix))] pub fn query_buffer(_query: &str, _buffer: &mut [u8], _timeout_ms: u64) -> Result { Err(XQError::Unsupported) } #[cfg(not(target_os = "macos"))] fn wait_for_input>(fd: BorrowedFd<'_>, timeout_ms: MS) -> Result { use nix::poll::{poll, PollFd, PollFlags, PollTimeout}; let poll_fd = PollFd::new(fd, PollFlags::POLLIN); let timeout = PollTimeout::try_from(timeout_ms.into()).map_err(|_| Errno::EOVERFLOW)?; poll(&mut [poll_fd], timeout) } // On MacOS, we need to use the `select` instead of `poll` because it doesn't support poll with tty: // // https://github.com/tokio-rs/mio/issues/1377 #[cfg(target_os = "macos")] fn wait_for_input>(fd: BorrowedFd<'_>, timeout_ms: MS) -> Result { use { nix::sys::{ select::{select, FdSet}, time::TimeVal, }, std::{os::fd::AsRawFd, time::Duration}, }; let mut fd_set = FdSet::new(); fd_set.insert(fd); let timeout_us = Duration::from_millis(timeout_ms.into()) .as_micros() .try_into() .map_err(|_| Errno::EOVERFLOW)?; let mut tv = TimeVal::new(0, timeout_us); select( fd.as_raw_fd() + 1, Some(&mut fd_set), None, None, Some(&mut tv), ) }