use std::borrow::Cow;
use std::str::FromStr;
use cursor_icon::CursorIcon;
use crate::ansi::CursorShape;
use crate::config::colors::{ColorRgb, NamedColor};
use crate::crosswords::square::Hyperlink;
use crate::event::{
BlockedKind, ProgramState, ProgramStatus, ProgressReport, ProgressState,
};
use crate::simd_utf8;
pub(super) enum ColorSpec {
Set(ColorRgb),
Query,
}
pub(super) struct PaletteEntry {
pub index: u8,
pub spec: ColorSpec,
}
pub(super) struct DynamicColorEntry {
pub index: NamedColor,
pub dynamic_code: u16,
pub spec: ColorSpec,
}
pub(super) enum ClipboardOp<'a> {
Load { kind: u8 },
Store { kind: u8, payload: &'a [u8] },
}
pub(super) enum PaletteReset {
All,
Indices(Vec<u8>),
}
pub(super) fn parse_semantic_prompt(
params: &[&[u8]],
) -> Option<crate::crosswords::grid::row::SemanticPrompt> {
use crate::crosswords::grid::row::SemanticPrompt;
let subcommand = *params.get(1)?.first()?;
match subcommand {
b'A' => Some(SemanticPrompt::Prompt),
b'P' => {
for option in ¶ms[2..] {
if let Some(kind) = option.strip_prefix(b"k=") {
if kind == b"c" || kind == b"s" {
return Some(SemanticPrompt::PromptContinuation);
}
}
}
Some(SemanticPrompt::Prompt)
}
_ => None,
}
}
pub(super) fn parse_exit_status(option: Option<&[u8]>) -> Option<i32> {
let raw = option?;
let (negative, digits) = match raw.split_first()? {
(b'-', digits) => (true, digits),
(b'+', digits) => (false, digits),
_ => (false, raw),
};
let magnitude = parse_digits(digits)?;
Some(if negative {
i32::try_from(magnitude).map_or(i32::MIN, |m| -m)
} else {
i32::try_from(magnitude).unwrap_or(i32::MAX)
})
}
pub(super) fn xparse_color(color: &[u8]) -> Option<ColorRgb> {
if !color.is_empty() && color[0] == b'#' {
parse_legacy_color(&color[1..])
} else if color.len() >= 4 && &color[..4] == b"rgb:" {
parse_rgb_color(&color[4..])
} else {
None
}
}
fn parse_rgb_color(color: &[u8]) -> Option<ColorRgb> {
let colors = simd_utf8::from_utf8_fast(color)
.ok()?
.split('/')
.collect::<Vec<_>>();
if colors.len() != 3 {
return None;
}
let scale = |input: &str| {
if input.len() > 4 {
None
} else {
let max = u32::pow(16, input.len() as u32) - 1;
let value = u32::from_str_radix(input, 16).ok()?;
Some((255 * value / max) as u8)
}
};
Some(ColorRgb {
r: scale(colors[0])?,
g: scale(colors[1])?,
b: scale(colors[2])?,
})
}
fn parse_legacy_color(color: &[u8]) -> Option<ColorRgb> {
let item_len = color.len() / 3;
let color_from_slice = |slice: &[u8]| {
let col =
usize::from_str_radix(simd_utf8::from_utf8_fast(slice).ok()?, 16).ok()? << 4;
Some((col >> (4 * slice.len().saturating_sub(1))) as u8)
};
Some(ColorRgb {
r: color_from_slice(&color[0..item_len])?,
g: color_from_slice(&color[item_len..item_len * 2])?,
b: color_from_slice(&color[item_len * 2..])?,
})
}
pub(super) fn parse_number(input: &[u8]) -> Option<u8> {
u8::try_from(parse_digits(input)?).ok()
}
fn parse_digits(digits: &[u8]) -> Option<u32> {
if digits.is_empty() || !digits.iter().all(u8::is_ascii_digit) {
return None;
}
Some(digits.iter().fold(0u32, |acc, digit| {
acc.saturating_mul(10)
.saturating_add(u32::from(digit - b'0'))
}))
}
pub(super) fn text_lossy(bytes: &[u8]) -> Cow<'_, str> {
match simd_utf8::from_utf8_fast(bytes) {
Ok(text) => Cow::Borrowed(text),
Err(_) => String::from_utf8_lossy(bytes),
}
}
pub(super) const MAX_TITLE_BYTES: usize = 255;
pub(super) fn parse_title(params: &[&[u8]]) -> Option<String> {
let Some(title) = params.get(1).copied() else {
tracing::warn!("ignoring OSC title without a payload");
return None;
};
if title.len() > MAX_TITLE_BYTES {
tracing::warn!(
"ignoring OSC title of {} bytes (limit {MAX_TITLE_BYTES})",
title.len()
);
return None;
}
match simd_utf8::from_utf8_fast(title) {
Ok(title) => Some(title.to_owned()),
Err(_) => {
tracing::warn!("ignoring OSC title with invalid UTF-8");
None
}
}
}
pub(super) fn parse_palette_entries(params: &[&[u8]]) -> Option<Vec<PaletteEntry>> {
if params.len() <= 1 || params.len().is_multiple_of(2) {
return None;
}
let mut out = Vec::with_capacity(params.len() / 2);
for chunk in params[1..].chunks(2) {
let index = parse_number(chunk[0])?;
let spec = if chunk[1] == b"?" {
ColorSpec::Query
} else {
ColorSpec::Set(xparse_color(chunk[1])?)
};
out.push(PaletteEntry { index, spec });
}
Some(out)
}
const FILE_SCHEME: &str = "file://";
const KITTY_SHELL_CWD_SCHEME: &str = "kitty-shell-cwd://";
fn strip_scheme<'a>(s: &'a str, scheme: &str) -> Option<&'a str> {
s.get(..scheme.len())
.filter(|prefix| prefix.eq_ignore_ascii_case(scheme))
.map(|_| &s[scheme.len()..])
}
pub(super) fn parse_current_directory(param: &[u8]) -> Option<Option<String>> {
if param.is_empty() {
return Some(None);
}
let dir = parse_directory_url(param);
if dir.is_none() {
tracing::debug!("ignoring malformed OSC 7 payload {:?}", text_lossy(param));
}
dir.map(Some)
}
fn parse_directory_url(param: &[u8]) -> Option<String> {
let s = simd_utf8::from_utf8_fast(param).ok()?;
let (after_scheme, percent_encoded) = match strip_scheme(s, FILE_SCHEME) {
Some(rest) => (rest, true),
None => (strip_scheme(s, KITTY_SHELL_CWD_SCHEME)?, false),
};
let path_start = after_scheme.find('/')?;
let host = &after_scheme[..path_start];
let path = &after_scheme[path_start..];
if !host_is_local(host) {
tracing::warn!("ignoring OSC 7 for non-local host {host:?}");
return None;
}
#[cfg(windows)]
let path = path.strip_prefix('/').unwrap_or(path);
if !percent_encoded {
return Some(path.to_string());
}
let path = &path[..path.find(['?', '#']).unwrap_or(path.len())];
percent_decode(path)
}
fn host_is_local(host: &str) -> bool {
let host = host.strip_suffix('.').unwrap_or(host);
if host.is_empty() || host.eq_ignore_ascii_case("localhost") {
return true;
}
match local_hostname() {
Some(local) => host.eq_ignore_ascii_case(&local),
None => true,
}
}
fn local_hostname() -> Option<String> {
read_hostname()
}
#[cfg(unix)]
fn read_hostname() -> Option<String> {
let mut buffer = [0_u8; 256];
let result = unsafe {
libc::gethostname(buffer.as_mut_ptr() as *mut libc::c_char, buffer.len())
};
if result != 0 {
return None;
}
let end = buffer.iter().position(|byte| *byte == 0)?;
std::str::from_utf8(&buffer[..end])
.ok()
.filter(|hostname| !hostname.is_empty())
.map(str::to_owned)
}
#[cfg(not(unix))]
fn read_hostname() -> Option<String> {
None
}
fn percent_decode(path: &str) -> Option<String> {
if !path.contains('%') {
return Some(path.to_owned());
}
let bytes = path.as_bytes();
let mut out = Vec::with_capacity(bytes.len());
let mut index = 0;
while index < bytes.len() {
let escape = (bytes[index] == b'%')
.then(|| {
let hex = bytes.get(index + 1..index + 3)?;
let high = (hex[0] as char).to_digit(16)?;
let low = (hex[1] as char).to_digit(16)?;
Some((high * 16 + low) as u8)
})
.flatten();
match escape {
Some(byte) => {
out.push(byte);
index += 3;
}
None => {
out.push(bytes[index]);
index += 1;
}
}
}
String::from_utf8(out).ok()
}
fn hyperlink_id_bytes(link_params: &[u8]) -> Option<&[u8]> {
link_params
.split(|&b| b == b':')
.rev()
.filter_map(|kv| kv.strip_prefix(b"id="))
.find(|id| !id.is_empty())
}
pub(super) fn parse_hyperlink_id(link_params: &[u8]) -> Option<Cow<'_, str>> {
hyperlink_id_bytes(link_params).map(text_lossy)
}
pub(crate) const MAX_HYPERLINK_BYTES: usize = 2047;
pub(super) fn parse_hyperlink(
link_params: &[u8],
uri: &[u8],
) -> Option<Option<Hyperlink>> {
let len = link_params.len() + 1 + uri.len();
if len > MAX_HYPERLINK_BYTES {
tracing::debug!("ignoring OSC 8 of {len} bytes (limit {MAX_HYPERLINK_BYTES})");
return None;
}
if uri.is_empty() {
let id_sent = hyperlink_id_bytes(link_params).is_some();
if id_sent {
tracing::debug!("ignoring OSC 8 with an id and no URI");
}
return (!id_sent).then_some(None);
}
let id = parse_hyperlink_id(link_params);
Some(Some(Hyperlink::new(id.as_deref(), &*text_lossy(uri))))
}
pub(super) fn parse_notification_body(params: &[&[u8]]) -> String {
params[1..]
.iter()
.map(|part| text_lossy(part))
.collect::<Vec<_>>()
.join(";")
}
pub(super) fn parse_progress_report(params: &[&[u8]]) -> Option<ProgressReport> {
if params.len() < 3 || params[1] != b"4" {
return None;
}
let state = match params[2] {
b"0" => ProgressState::Remove,
b"1" => ProgressState::Set,
b"2" => ProgressState::Error,
b"3" => ProgressState::Indeterminate,
b"4" => ProgressState::Pause,
_ => return None,
};
let progress = if params.len() >= 4 {
parse_number(params[3]).map(|p| p.min(100))
} else {
None
};
Some(ProgressReport { state, progress })
}
#[derive(Debug, PartialEq, Eq)]
pub(super) enum ProgramStatusRequest {
Query,
Report(ProgramStatus),
}
const PROGRAM_STATUS_MAX_SEQUENCE: usize = 4096;
const PROGRAM_STATUS_MAX_KEY: usize = 16;
const PROGRAM_STATUS_MAX_APP: usize = 32;
const PROGRAM_STATUS_MAX_MSG: (usize, usize) = (2732, 2048);
const PROGRAM_STATUS_MAX_TITLE: (usize, usize) = (256, 192);
const PROGRAM_STATUS_MAX_ID: usize = 128;
const PROGRAM_STATUS_MAX_SEGMENT: usize = 32;
const PROGRAM_STATUS_MAX_DEPTH: usize = 8;
pub(super) fn parse_program_status(
params: &[&[u8]],
terminator_len: usize,
) -> Option<ProgramStatusRequest> {
let body: Cow<str> = match params {
[_, body] => simd_utf8::from_utf8_fast(body).ok()?.into(),
_ => params
.get(1..)?
.iter()
.map(|param| simd_utf8::from_utf8_fast(param).ok())
.collect::<Option<Vec<_>>>()?
.join(";")
.into(),
};
if body.len() + 7 + terminator_len > PROGRAM_STATUS_MAX_SEQUENCE {
return None;
}
if body.trim() == "?" {
return Some(ProgramStatusRequest::Query);
}
let mut state: Option<Option<ProgramState>> = None;
let mut id: Option<Option<String>> = None;
let mut kind = None;
let mut app = None;
let mut msg = None;
let mut title = None;
let mut progress = None;
for pair in body.split(':') {
let Some((key, value)) = pair.split_once('=') else {
continue;
};
let (key, value) = (key.trim(), value.trim());
if key.len() > PROGRAM_STATUS_MAX_KEY {
return None;
}
let well_formed =
!value.is_empty() && value.bytes().all(is_program_status_value_byte);
match key {
"id" => {
if value.len() > PROGRAM_STATUS_MAX_ID {
return None;
}
id = Some(
(well_formed && is_valid_program_status_id(value))
.then(|| value.to_string()),
);
}
_ if !well_formed => continue,
"state" => {
state = Some(match value {
"idle" => Some(ProgramState::Idle),
"working" => Some(ProgramState::Working),
"done" => Some(ProgramState::Done),
"blocked" => Some(ProgramState::Blocked),
"error" => Some(ProgramState::Error),
"clear" => Some(ProgramState::Clear),
_ => None,
})
}
"kind" => {
kind = match value {
"permission" => Some(BlockedKind::Permission),
"question" => Some(BlockedKind::Question),
"auth" => Some(BlockedKind::Auth),
_ => None,
}
}
"app" => {
if value.len() > PROGRAM_STATUS_MAX_APP {
return None;
}
app = Some(value.to_string());
}
"msg" => {
msg = Some(decode_program_status_text(value, PROGRAM_STATUS_MAX_MSG)?)
}
"title" => {
title = Some(decode_program_status_text(value, PROGRAM_STATUS_MAX_TITLE)?)
}
"progress" => {
if let Some(p) = value.parse::<u8>().ok().filter(|p| *p <= 100) {
progress = Some(p);
}
}
_ => {}
}
}
let state = state??;
let id = match id {
None => None,
Some(valid) => Some(valid?),
};
Some(ProgramStatusRequest::Report(ProgramStatus {
state,
kind: kind.filter(|_| state == ProgramState::Blocked),
app,
msg,
title,
progress: progress
.filter(|_| matches!(state, ProgramState::Working | ProgramState::Blocked)),
id,
}))
}
fn is_program_status_value_byte(byte: u8) -> bool {
byte.is_ascii_alphanumeric() || b"_.,+/=-".contains(&byte)
}
fn decode_program_status_text(
value: &str,
(encoded, decoded): (usize, usize),
) -> Option<String> {
if value.len() > encoded {
return None;
}
let bytes = crate::simd_base64::decode(value.as_bytes())?;
if bytes.len() > decoded {
return None;
}
let text = String::from_utf8(bytes).ok()?;
if text.chars().any(char::is_control) {
return None;
}
Some(text)
}
fn is_valid_program_status_id(id: &str) -> bool {
id.split('/').count() <= PROGRAM_STATUS_MAX_DEPTH
&& id.split('/').all(|segment| {
(1..=PROGRAM_STATUS_MAX_SEGMENT).contains(&segment.len())
&& segment
.bytes()
.all(|b| b.is_ascii_alphanumeric() || b"_.+-".contains(&b))
})
}
pub(super) fn parse_conemu_working_directory(params: &[&[u8]]) -> Option<Option<String>> {
if params.len() < 3 || params[1] != b"9" {
return None;
}
let path = simd_utf8::from_utf8_fast(params[2]).ok()?;
let path = path
.strip_prefix('"')
.and_then(|p| p.strip_suffix('"'))
.unwrap_or(path);
if path.is_empty() {
return Some(None);
}
if !is_absolute_path(path) {
tracing::debug!("ignoring OSC 9;9 with non-absolute path {path:?}");
return None;
}
Some(Some(path.to_string()))
}
pub(super) fn is_conemu_subcommand(sub: &[u8]) -> bool {
matches!(
sub,
b"1" | b"2"
| b"3"
| b"4"
| b"5"
| b"6"
| b"7"
| b"8"
| b"9"
| b"10"
| b"11"
| b"12"
)
}
fn is_absolute_path(path: &str) -> bool {
if path.starts_with('/') {
return true;
}
let bytes = path.as_bytes();
bytes.len() >= 3
&& bytes[0].is_ascii_alphabetic()
&& bytes[1] == b':'
&& (bytes[2] == b'\\' || bytes[2] == b'/')
}
pub(super) fn parse_dynamic_colors(params: &[&[u8]]) -> Option<Vec<DynamicColorEntry>> {
if params.len() < 2 {
return None;
}
let base_code = parse_number(params[0])? as u16;
let mut out = Vec::with_capacity(params.len() - 1);
for (dynamic_code, param) in (base_code..).zip(params[1..].iter()) {
let offset = (dynamic_code as usize).checked_sub(10)?;
let index_usize = NamedColor::Foreground as usize + offset;
if index_usize > NamedColor::Cursor as usize {
return None;
}
let index = match offset {
0 => NamedColor::Foreground,
1 => NamedColor::Background,
2 => NamedColor::Cursor,
_ => return None,
};
let spec = if *param == b"?" {
ColorSpec::Query
} else {
let c = xparse_color(param)?;
ColorSpec::Set(c)
};
out.push(DynamicColorEntry {
index,
dynamic_code,
spec,
});
}
Some(out)
}
pub(super) fn parse_mouse_cursor_icon(param: &[u8]) -> Option<CursorIcon> {
let shape = simd_utf8::from_utf8_lossy_fast(param);
CursorIcon::from_str(&shape).ok()
}
pub(super) fn parse_cursor_shape(params: &[&[u8]]) -> Option<CursorShape> {
if params.len() < 2 || params[1].len() < 13 || params[1][0..12] != *b"CursorShape=" {
return None;
}
match params[1][12] as char {
'0' => Some(CursorShape::Block),
'1' => Some(CursorShape::Beam),
'2' => Some(CursorShape::Underline),
_ => None,
}
}
pub(super) fn parse_clipboard<'a>(params: &[&'a [u8]]) -> Option<ClipboardOp<'a>> {
if params.len() < 3 {
return None;
}
let kind = *params[1].first().unwrap_or(&b'c');
Some(if params[2] == b"?" {
ClipboardOp::Load { kind }
} else {
ClipboardOp::Store {
kind,
payload: params[2],
}
})
}
pub(super) fn parse_palette_reset(params: &[&[u8]]) -> PaletteReset {
if params.len() == 1 || params[1].is_empty() {
return PaletteReset::All;
}
let indices = params[1..].iter().filter_map(|p| parse_number(p)).collect();
PaletteReset::Indices(indices)
}
#[cfg(test)]
mod tests {
use super::*;
fn status(body: &str) -> Option<ProgramStatusRequest> {
let params: Vec<&[u8]> = vec![b"7501", body.as_bytes()];
parse_program_status(¶ms, 2)
}
fn report(body: &str) -> ProgramStatus {
match status(body) {
Some(ProgramStatusRequest::Report(report)) => report,
other => panic!("expected a report for {body:?}, got {other:?}"),
}
}
#[test]
fn program_status_full_report() {
let r = report("state=blocked:kind=permission:app=terraform:msg=QXBwbHkgcGxhbj8=:title=dGY=:id=plan/apply:progress=40");
assert_eq!(r.state, ProgramState::Blocked);
assert_eq!(r.kind, Some(BlockedKind::Permission));
assert_eq!(r.app.as_deref(), Some("terraform"));
assert_eq!(r.msg.as_deref(), Some("Apply plan?"));
assert_eq!(r.title.as_deref(), Some("tf"));
assert_eq!(r.id.as_deref(), Some("plan/apply"));
assert_eq!(r.progress, Some(40));
}
#[test]
fn program_status_minimal_and_query() {
let r = report("state=idle");
assert_eq!(r.state, ProgramState::Idle);
assert_eq!(
(r.kind, r.app, r.msg, r.id, r.progress),
(None, None, None, None, None)
);
assert_eq!(status("?"), Some(ProgramStatusRequest::Query));
assert_eq!(report("state=clear").state, ProgramState::Clear);
}
#[test]
fn program_status_lenient_parts() {
let r = report(" state = working : junk : future=1 : app=a : app=b ");
assert_eq!(r.state, ProgramState::Working);
assert_eq!(r.app.as_deref(), Some("b"));
assert_eq!(report("state=blocked:kind=telepathy").kind, None);
assert_eq!(report("state=idle:kind=question").kind, None);
assert_eq!(report("state=done:progress=50").progress, None);
assert_eq!(report("state=working:progress=101").progress, None);
}
#[test]
fn program_status_discards_whole_report() {
let long_app = format!("state=idle:app={}", "a".repeat(33));
let long_body = format!("state=idle:pad={}", "a".repeat(4096));
for body in [
"",
"app=cargo", "state=sleeping", "state=idle:msg=A", "state=idle:msg=G1sybQ==", "state=idle:id=a//b", "state=idle:id=a/b c", "state=idle:id=1/2/3/4/5/6/7/8/9", "state=idle:averyveryverylongkey=1", &long_app,
&long_body,
] {
assert_eq!(status(body), None, "{body}");
}
}
#[test]
fn program_status_last_repeat_wins() {
assert_eq!(report("state=bogus:state=idle").state, ProgramState::Idle);
assert_eq!(report("state=idle:state=").state, ProgramState::Idle);
assert_eq!(report("state=idle:state=!").state, ProgramState::Idle);
assert_eq!(status("state=idle:state=bogus"), None);
assert_eq!(report("state=idle:id=a//b:id=ok").id.as_deref(), Some("ok"));
assert_eq!(status("state=idle:id=ok:id=a//b"), None);
assert_eq!(
report("state=working:progress=40:progress=abc").progress,
Some(40)
);
assert_eq!(
report("state=working:progress=40:progress=101").progress,
Some(40)
);
}
#[test]
fn program_status_sequence_cap_counts_the_terminator() {
let fill = |len: usize| format!("state=idle:p={}", "a".repeat(len - 13));
let bel_max = fill(4096 - 7 - 1);
let params: Vec<&[u8]> = vec![b"7501", bel_max.as_bytes()];
assert!(parse_program_status(¶ms, 1).is_some());
assert!(parse_program_status(¶ms, 2).is_none());
}
#[test]
fn program_status_skips_malformed_pairs() {
let r = report("state=working:msg=!!!:app=cargo");
assert_eq!((r.msg, r.app.as_deref()), (None, Some("cargo")));
}
fn cwd(payload: &str) -> Option<String> {
parse_current_directory(payload.as_bytes()).flatten()
}
#[test]
fn current_directory_empty_payload_clears() {
assert_eq!(parse_current_directory(b""), Some(None));
assert_eq!(parse_current_directory(b"not-a-url"), None);
}
#[cfg(not(windows))]
#[test]
fn current_directory_from_file_url() {
assert_eq!(cwd("file:///home/user"), Some("/home/user".into()));
assert_eq!(cwd("file://localhost/home/user"), Some("/home/user".into()));
assert_eq!(cwd("file:///"), Some("/".into()));
assert_eq!(cwd("FILE:///home/user"), Some("/home/user".into()));
}
#[cfg(windows)]
#[test]
fn current_directory_strips_windows_leading_slash() {
assert_eq!(cwd("file:///C:/Users/user"), Some("C:/Users/user".into()));
}
#[cfg(unix)]
#[test]
fn current_directory_accepts_local_hosts() {
assert_eq!(cwd("file:///tmp"), Some("/tmp".into()));
assert_eq!(cwd("file://localhost/tmp"), Some("/tmp".into()));
assert_eq!(cwd("file://LOCALHOST/tmp"), Some("/tmp".into()));
let local = local_hostname().expect("hostname");
assert_eq!(cwd(&format!("file://{local}/tmp")), Some("/tmp".into()));
assert_eq!(
cwd(&format!("file://{}/tmp", local.to_uppercase())),
Some("/tmp".into())
);
assert_eq!(cwd(&format!("file://{local}./tmp")), Some("/tmp".into()));
}
#[cfg(unix)]
#[test]
fn current_directory_rejects_remote_hosts() {
assert_eq!(cwd("file://not-this-machine.invalid/tmp"), None);
}
#[test]
fn current_directory_rejects_non_file_payloads() {
assert_eq!(cwd("http://example.com/home/user"), None);
assert_eq!(cwd("/home/user"), None);
assert_eq!(cwd(""), None);
assert_eq!(cwd("file://localhost"), None);
assert_eq!(cwd("kitty-shell-cwd://localhost"), None);
}
#[test]
fn conemu_working_directory() {
let parse = parse_conemu_working_directory;
assert_eq!(
parse(&[b"9", b"9", b"C:\\Users\\rapha"]),
Some(Some("C:\\Users\\rapha".into()))
);
assert_eq!(
parse(&[b"9", b"9", b"\"C:\\Program Files\""]),
Some(Some("C:\\Program Files".into()))
);
assert_eq!(
parse(&[b"9", b"9", b"C:\\a;b"]),
Some(Some("C:\\a;b".into()))
);
assert_eq!(parse(&[b"9", b"4", b"1", b"50"]), None);
assert_eq!(parse(&[b"9", b"hello"]), None);
assert_eq!(parse(&[b"9", b"9"]), None);
assert_eq!(parse(&[b"9", b"9", b""]), Some(None));
assert_eq!(parse(&[b"9", b"9", b"\"\""]), Some(None));
assert_eq!(parse(&[b"9", b"9", b"Meeting at 5"]), None);
assert_eq!(parse(&[b"9", b"9", b"..\\up"]), None);
assert_eq!(parse(&[b"9", b"9", b"\\\\server\\share"]), None);
assert_eq!(
parse(&[b"9", b"9", b"/home/user"]),
Some(Some("/home/user".into()))
);
}
#[cfg(not(windows))]
#[test]
fn current_directory_accepts_kitty_shell_cwd() {
assert_eq!(
cwd("kitty-shell-cwd:///home/user"),
Some("/home/user".into())
);
assert_eq!(
cwd("kitty-shell-cwd://localhost/home/user"),
Some("/home/user".into())
);
assert_eq!(
cwd("KITTY-SHELL-CWD:///home/user"),
Some("/home/user".into())
);
}
#[cfg(not(windows))]
#[test]
fn kitty_shell_cwd_keeps_semicolons() {
assert_eq!(cwd("kitty-shell-cwd:///tmp/a;b"), Some("/tmp/a;b".into()));
}
#[cfg(not(windows))]
#[test]
fn kitty_shell_cwd_is_verbatim() {
assert_eq!(cwd("kitty-shell-cwd:///tmp/a b"), Some("/tmp/a b".into()));
assert_eq!(
cwd("kitty-shell-cwd:///tmp/50%25 off?really"),
Some("/tmp/50%25 off?really".into())
);
}
#[cfg(windows)]
#[test]
fn kitty_shell_cwd_strips_windows_leading_slash() {
assert_eq!(
cwd("kitty-shell-cwd:///C:\\Users\\a b"),
Some("C:\\Users\\a b".into())
);
assert_eq!(
cwd("kitty-shell-cwd://localhost/C:\\projects\\c#"),
Some("C:\\projects\\c#".into())
);
}
#[cfg(unix)]
#[test]
fn kitty_shell_cwd_rejects_remote_hosts() {
assert_eq!(
cwd("kitty-shell-cwd://other-machine.example/home/user"),
None
);
}
#[cfg(not(windows))]
#[test]
fn current_directory_percent_decodes() {
assert_eq!(
cwd("file:///home/My%20Files"),
Some("/home/My Files".into())
);
assert_eq!(
cwd("file:///home/%E1%BF%AC%CF%8C%CE%B4%CE%BF%CF%82"),
Some("/home/Ῥόδος".into())
);
}
#[cfg(not(windows))]
#[test]
fn current_directory_keeps_malformed_escapes() {
assert_eq!(cwd("file:///home/100%"), Some("/home/100%".into()));
assert_eq!(cwd("file:///home/a%zz"), Some("/home/a%zz".into()));
assert_eq!(cwd("file:///home/a%2"), Some("/home/a%2".into()));
}
#[cfg(not(windows))]
#[test]
fn current_directory_ignores_query_and_fragment() {
assert_eq!(cwd("file:///home/user?x=1"), Some("/home/user".into()));
assert_eq!(cwd("file:///home/user#frag"), Some("/home/user".into()));
}
#[cfg(not(windows))]
#[test]
fn current_directory_rejects_non_hex_escapes() {
assert_eq!(cwd("file:///home/a%+A"), Some("/home/a%+A".into()));
assert_eq!(cwd("file:///home/a% 1"), Some("/home/a% 1".into()));
}
#[test]
fn current_directory_rejects_invalid_utf8_escapes() {
assert_eq!(cwd("file:///home/%FF%FE"), None);
}
#[cfg(not(windows))]
#[test]
fn osc7_sets_current_directory_end_to_end() {
use crate::ansi::CursorShape;
use crate::crosswords::{Crosswords, CrosswordsSize};
use crate::event::{VoidListener, WindowId};
use crate::performer::handler::Processor;
let mut term = Crosswords::new(
CrosswordsSize::new(20, 5),
CursorShape::Block,
VoidListener,
WindowId::from(0),
0,
10,
);
let mut processor = Processor::default();
processor.advance(&mut term, b"\x1b]7;file:///home/My%20Files\x1b\\");
assert_eq!(
term.current_directory.as_deref(),
Some(std::path::Path::new("/home/My Files"))
);
processor.advance(
&mut term,
b"\x1b]7;file://not-this-machine.invalid/tmp\x1b\\",
);
assert_eq!(
term.current_directory.as_deref(),
Some(std::path::Path::new("/home/My Files"))
);
processor.advance(&mut term, b"\x1b]7;not-a-url\x1b\\");
assert_eq!(
term.current_directory.as_deref(),
Some(std::path::Path::new("/home/My Files"))
);
processor.advance(&mut term, b"\x1b]7;\x1b\\");
assert_eq!(term.current_directory, None);
processor.advance(&mut term, b"\x1b]9;9;/tmp/x\x07");
assert_eq!(
term.current_directory.as_deref(),
Some(std::path::Path::new("/tmp/x"))
);
processor.advance(&mut term, b"\x1b]9;9;\x07");
assert_eq!(term.current_directory, None);
processor.advance(&mut term, b"\x1b]9;9;/tmp/y\x07");
processor.advance(&mut term, b"\x1b]9;9;\"\"\x07");
assert_eq!(term.current_directory, None);
}
#[test]
fn hyperlink_follows_empty_uri_rules() {
let open = parse_hyperlink(b"id=a", b"https://x.dev/a;b")
.unwrap()
.unwrap();
assert_eq!(open.uri(), "https://x.dev/a;b");
assert_eq!(parse_hyperlink(b"", b""), Some(None));
assert_eq!(parse_hyperlink(b"id=", b""), Some(None));
assert_eq!(parse_hyperlink(b"id=a", b""), None);
let open = parse_hyperlink(b"id=a:id=b", b"https://x.dev")
.unwrap()
.unwrap();
assert_eq!(open.id(), "b");
let open = parse_hyperlink(b"id=a:id=", b"https://x.dev")
.unwrap()
.unwrap();
assert_eq!(open.id(), "a");
assert_eq!(parse_hyperlink(b"id=:id=a", b""), None);
assert_eq!(parse_hyperlink(b"id=:other=x", b""), Some(None));
assert_eq!(parse_hyperlink(b"id=caf\xe9", b""), None);
let open = parse_hyperlink(b"id=caf\xe9", b"https://x.dev")
.unwrap()
.unwrap();
assert_eq!(open.id(), "caf\u{FFFD}");
}
#[test]
fn hyperlink_payload_is_bounded() {
const URI: &str = "https://x.dev";
let room = MAX_HYPERLINK_BYTES - 1;
let uri = format!("{URI}/{}", "a".repeat(room - URI.len() - 1));
assert_eq!(1 + uri.len(), MAX_HYPERLINK_BYTES);
let open = parse_hyperlink(b"", uri.as_bytes()).unwrap().unwrap();
assert_eq!(open.uri(), uri);
assert_eq!(parse_hyperlink(b"", format!("{uri}a").as_bytes()), None);
assert_eq!(parse_hyperlink(b"a", uri.as_bytes()), None);
let id_len = room - URI.len() - "id=".len();
let id = format!("id={}", "i".repeat(id_len));
assert_eq!(id.len() + 1 + URI.len(), MAX_HYPERLINK_BYTES);
let open = parse_hyperlink(id.as_bytes(), URI.as_bytes())
.unwrap()
.unwrap();
assert_eq!(open.id().len(), id_len);
assert_eq!(
parse_hyperlink(format!("{id}i").as_bytes(), URI.as_bytes()),
None
);
let mut raw = b"id=".to_vec();
raw.extend(std::iter::repeat_n(0xFF, id_len));
let open = parse_hyperlink(&raw, URI.as_bytes()).unwrap().unwrap();
assert_eq!(open.id().chars().count(), id_len);
raw.push(0xFF);
assert_eq!(parse_hyperlink(&raw, URI.as_bytes()), None);
let params = "a".repeat(MAX_HYPERLINK_BYTES);
assert_eq!(parse_hyperlink(params.as_bytes(), b""), None);
assert_eq!(parse_hyperlink(¶ms.as_bytes()[1..], b""), Some(None));
}
#[test]
fn conemu_subcommands() {
for sub in [b"1" as &[u8], b"4", b"9", b"10", b"12"] {
assert!(is_conemu_subcommand(sub), "{sub:?}");
}
for sub in [b"" as &[u8], b"0", b"13", b"01", b"hello", b"4x"] {
assert!(!is_conemu_subcommand(sub), "{sub:?}");
}
}
#[test]
fn notification_body_is_everything_after_nine() {
assert_eq!(
parse_notification_body(&[b"9", b"done", b" 3 warnings"]),
"done; 3 warnings"
);
assert_eq!(parse_notification_body(&[b"9", b"caf\xe9"]), "caf\u{FFFD}");
}
#[test]
fn title_is_verbatim() {
assert_eq!(parse_title(&[b"2", b" a;b "]), Some(" a;b ".into()));
assert_eq!(parse_title(&[b"2", b""]), Some(String::new()));
assert_eq!(parse_title(&[b"2"]), None);
}
#[test]
fn title_rejects_invalid_utf8_and_oversize() {
assert_eq!(parse_title(&[b"0", b"caf\xe9"]), None);
let at_limit = "a".repeat(MAX_TITLE_BYTES);
assert_eq!(
parse_title(&[b"0", at_limit.as_bytes()]),
Some(at_limit.clone())
);
let over = "a".repeat(MAX_TITLE_BYTES + 1);
assert_eq!(parse_title(&[b"0", over.as_bytes()]), None);
let wide = "é".repeat(MAX_TITLE_BYTES / 2); assert_eq!(parse_title(&[b"0", wide.as_bytes()]), Some(wide));
let wide_over = "é".repeat(MAX_TITLE_BYTES / 2 + 1); assert_eq!(parse_title(&[b"0", wide_over.as_bytes()]), None);
}
}