Initial GPUI Wayland terminal with Alacritty core
This commit is contained in:
+197
@@ -0,0 +1,197 @@
|
||||
//! The default palette and the terminal's runtime (OSC) color overrides.
|
||||
|
||||
use alacritty_terminal::{
|
||||
term::{
|
||||
cell::{Cell, Flags},
|
||||
color::{COUNT, Colors},
|
||||
},
|
||||
vte::ansi::{Color, NamedColor, Rgb},
|
||||
};
|
||||
use gpui::Hsla;
|
||||
|
||||
pub const BACKGROUND: u32 = 0x181a1f;
|
||||
pub const FOREGROUND: u32 = 0xd8dee9;
|
||||
|
||||
const ANSI: [u32; 16] = [
|
||||
0x282c34, 0xe06c75, 0x98c379, 0xe5c07b, 0x61afef, 0xc678dd, 0x56b6c2, 0xabb2bf, 0x5c6370,
|
||||
0xff7a85, 0xb5e890, 0xffdb95, 0x82c7ff, 0xe59cff, 0x78dce8, 0xffffff,
|
||||
];
|
||||
|
||||
fn rgb(value: u32) -> Rgb {
|
||||
Rgb {
|
||||
r: (value >> 16) as u8,
|
||||
g: (value >> 8) as u8,
|
||||
b: value as u8,
|
||||
}
|
||||
}
|
||||
|
||||
fn dim(color: Rgb) -> Rgb {
|
||||
Rgb {
|
||||
r: (color.r as f32 * 0.66) as u8,
|
||||
g: (color.g as f32 * 0.66) as u8,
|
||||
b: (color.b as f32 * 0.66) as u8,
|
||||
}
|
||||
}
|
||||
|
||||
fn hsla(color: Rgb) -> Hsla {
|
||||
gpui::rgb((u32::from(color.r) << 16) | (u32::from(color.g) << 8) | u32::from(color.b)).into()
|
||||
}
|
||||
|
||||
/// Resolve a default palette entry, including Alacritty's extended named colors.
|
||||
pub fn palette(index: usize) -> Rgb {
|
||||
match index {
|
||||
0..=15 => rgb(ANSI[index]),
|
||||
16..=231 => {
|
||||
let cube = index - 16;
|
||||
let level = |value: usize| if value == 0 { 0 } else { 55 + value as u8 * 40 };
|
||||
Rgb {
|
||||
r: level(cube / 36),
|
||||
g: level(cube / 6 % 6),
|
||||
b: level(cube % 6),
|
||||
}
|
||||
}
|
||||
232..=255 => {
|
||||
let value = 8 + (index - 232) as u8 * 10;
|
||||
Rgb {
|
||||
r: value,
|
||||
g: value,
|
||||
b: value,
|
||||
}
|
||||
}
|
||||
257 => rgb(BACKGROUND),
|
||||
259..=266 => dim(rgb(ANSI[index - 259])),
|
||||
268 => dim(rgb(FOREGROUND)),
|
||||
// Foreground (256), cursor (258), and bright foreground (267).
|
||||
_ => rgb(FOREGROUND),
|
||||
}
|
||||
}
|
||||
|
||||
fn indexed(index: usize, colors: &Colors) -> Rgb {
|
||||
if index < COUNT {
|
||||
colors[index].unwrap_or_else(|| palette(index))
|
||||
} else {
|
||||
palette(index)
|
||||
}
|
||||
}
|
||||
|
||||
fn resolve_rgb(color: Color, colors: &Colors) -> Rgb {
|
||||
match color {
|
||||
Color::Named(color) => indexed(color as usize, colors),
|
||||
Color::Indexed(index) => indexed(index as usize, colors),
|
||||
Color::Spec(color) => color,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn resolve(color: Color, colors: &Colors) -> Hsla {
|
||||
hsla(resolve_rgb(color, colors))
|
||||
}
|
||||
|
||||
/// Return foreground/background after applying SGR intensity and reverse video.
|
||||
pub fn cell_colors(cell: &Cell, colors: &Colors) -> (Hsla, Hsla) {
|
||||
let intensity = cell.flags & Flags::DIM_BOLD;
|
||||
let mut fg = match cell.fg {
|
||||
Color::Named(color) => {
|
||||
let color = match intensity {
|
||||
Flags::BOLD => color.to_bright(),
|
||||
Flags::DIM => color.to_dim(),
|
||||
Flags::DIM_BOLD if color == NamedColor::Foreground => NamedColor::DimForeground,
|
||||
_ => color,
|
||||
};
|
||||
indexed(color as usize, colors)
|
||||
}
|
||||
Color::Indexed(index) => match (intensity, index) {
|
||||
(Flags::BOLD, 0..=7) => indexed(index as usize + 8, colors),
|
||||
(Flags::DIM, 0..=7) => indexed(NamedColor::DimBlack as usize + index as usize, colors),
|
||||
(Flags::DIM, 8..=15) => indexed(index as usize - 8, colors),
|
||||
(Flags::DIM, _) => dim(indexed(index as usize, colors)),
|
||||
_ => indexed(index as usize, colors),
|
||||
},
|
||||
Color::Spec(color) if cell.flags.contains(Flags::DIM) => dim(color),
|
||||
Color::Spec(color) => color,
|
||||
};
|
||||
let mut bg = resolve_rgb(cell.bg, colors);
|
||||
if cell.flags.contains(Flags::INVERSE) {
|
||||
std::mem::swap(&mut fg, &mut bg);
|
||||
}
|
||||
if cell.flags.contains(Flags::HIDDEN) {
|
||||
fg = bg;
|
||||
}
|
||||
(hsla(fg), hsla(bg))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn color_cube_and_grayscale_match_xterm() {
|
||||
assert_eq!(palette(16), rgb(0x000000));
|
||||
assert_eq!(palette(21), rgb(0x0000ff));
|
||||
assert_eq!(palette(46), rgb(0x00ff00));
|
||||
assert_eq!(palette(196), rgb(0xff0000));
|
||||
assert_eq!(palette(231), rgb(0xffffff));
|
||||
assert_eq!(palette(232), rgb(0x080808));
|
||||
assert_eq!(palette(255), rgb(0xeeeeee));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn default_named_colors_and_dynamic_overrides() {
|
||||
let mut colors = Colors::default();
|
||||
assert_eq!(
|
||||
resolve_rgb(Color::Named(NamedColor::Background), &colors),
|
||||
rgb(BACKGROUND)
|
||||
);
|
||||
assert_eq!(
|
||||
resolve_rgb(Color::Named(NamedColor::Foreground), &colors),
|
||||
rgb(FOREGROUND)
|
||||
);
|
||||
colors[NamedColor::Background] = Some(rgb(0x102030));
|
||||
colors[4] = Some(rgb(0x112233));
|
||||
assert_eq!(
|
||||
resolve_rgb(Color::Named(NamedColor::Background), &colors),
|
||||
rgb(0x102030)
|
||||
);
|
||||
assert_eq!(resolve_rgb(Color::Indexed(4), &colors), rgb(0x112233));
|
||||
assert_eq!(
|
||||
resolve_rgb(Color::Named(NamedColor::Blue), &colors),
|
||||
rgb(0x112233)
|
||||
);
|
||||
assert_eq!(
|
||||
resolve_rgb(Color::Spec(rgb(0x445566)), &colors),
|
||||
rgb(0x445566)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bold_brightens_ansi_foreground_without_changing_background() {
|
||||
let colors = Colors::default();
|
||||
let cell = Cell {
|
||||
fg: Color::Indexed(1),
|
||||
bg: Color::Indexed(2),
|
||||
flags: Flags::BOLD,
|
||||
..Cell::default()
|
||||
};
|
||||
assert_eq!(
|
||||
cell_colors(&cell, &colors),
|
||||
(hsla(palette(9)), hsla(palette(2)))
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dim_truecolor_inverse_and_hidden_are_applied_in_order() {
|
||||
let colors = Colors::default();
|
||||
let mut cell = Cell {
|
||||
fg: Color::Spec(rgb(0xffffff)),
|
||||
bg: Color::Spec(rgb(0x123456)),
|
||||
flags: Flags::DIM | Flags::INVERSE,
|
||||
..Cell::default()
|
||||
};
|
||||
assert_eq!(
|
||||
cell_colors(&cell, &colors),
|
||||
(hsla(rgb(0x123456)), hsla(dim(rgb(0xffffff))))
|
||||
);
|
||||
cell.flags.insert(Flags::HIDDEN);
|
||||
let (fg, bg) = cell_colors(&cell, &colors);
|
||||
assert_eq!(fg, bg);
|
||||
}
|
||||
}
|
||||
+141
@@ -0,0 +1,141 @@
|
||||
//! Select a concrete fixed-pitch family; GPUI does not resolve CSS font aliases.
|
||||
|
||||
use gpui::{Font, TextSystem, font, px};
|
||||
|
||||
// Nerd Fonts publishes its patched Hermit under the name "Hurmit".
|
||||
const PREFERRED: &[&str] = &[
|
||||
"Hermit",
|
||||
"Hurmit Nerd Font Mono",
|
||||
"Hurmit Nerd Font",
|
||||
"Hurmit NF",
|
||||
"SF Mono",
|
||||
"Noto Sans Mono",
|
||||
"Iosevka",
|
||||
"Iosevka Fixed",
|
||||
"Iosevka Term",
|
||||
];
|
||||
|
||||
pub fn terminal_font(text_system: &TextSystem) -> Font {
|
||||
let families = text_system.all_font_names();
|
||||
let family = select_family(&families, |family| is_monospace(text_system, family)).expect(
|
||||
"No usable monospace font found; install Hermit, Noto Sans Mono, or DejaVu Sans Mono",
|
||||
);
|
||||
log::info!("Terminal font: {family}");
|
||||
font(family.to_owned())
|
||||
}
|
||||
|
||||
fn select_family(families: &[String], mut is_monospace: impl FnMut(&str) -> bool) -> Option<&str> {
|
||||
for preferred in PREFERRED {
|
||||
if let Some(family) = families
|
||||
.iter()
|
||||
.find(|family| family.eq_ignore_ascii_case(preferred))
|
||||
&& is_monospace(family)
|
||||
{
|
||||
return Some(family);
|
||||
}
|
||||
}
|
||||
|
||||
// Font discovery order varies by platform. Try likely fixed-pitch names
|
||||
// first, then inspect the remaining families, including names such as
|
||||
// "Inconsolata" that contain neither "Mono" nor "Fixed".
|
||||
let mut fallback: Vec<_> = families
|
||||
.iter()
|
||||
.map(String::as_str)
|
||||
.filter(|name| !name.starts_with('.') && !name.eq_ignore_ascii_case("monospace"))
|
||||
.filter(|name| {
|
||||
!PREFERRED
|
||||
.iter()
|
||||
.any(|preferred| name.eq_ignore_ascii_case(preferred))
|
||||
})
|
||||
.collect();
|
||||
fallback.sort_by_cached_key(|name| {
|
||||
let lower = name.to_lowercase();
|
||||
let likely = lower.contains("mono") || lower.contains("fixed");
|
||||
(!likely, lower)
|
||||
});
|
||||
fallback.into_iter().find(|name| is_monospace(name))
|
||||
}
|
||||
|
||||
fn is_monospace(text_system: &TextSystem, family: &str) -> bool {
|
||||
let id = text_system.resolve_font(&font(family.to_owned()));
|
||||
// all_font_names also includes GPUI's fallback names, which might not be
|
||||
// installed. Reject a request that resolved to a different family.
|
||||
if !text_system
|
||||
.get_font_for_id(id)
|
||||
.is_some_and(|resolved| resolved.family.as_ref().eq_ignore_ascii_case(family))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
let Ok(reference) = text_system.advance(id, px(15.), 'M') else {
|
||||
return false;
|
||||
};
|
||||
let reference = f32::from(reference.width);
|
||||
if !reference.is_finite() || reference <= 0. {
|
||||
return false;
|
||||
}
|
||||
// Checking all printable ASCII catches proportional fonts with tabular
|
||||
// digits as well as fonts whose names misleadingly contain "Mono".
|
||||
(' '..='~').all(|character| {
|
||||
text_system
|
||||
.advance(id, px(15.), character)
|
||||
.is_ok_and(|advance| (f32::from(advance.width) - reference).abs() < 0.01)
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn families(names: &[&str]) -> Vec<String> {
|
||||
names.iter().map(|name| (*name).into()).collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn preferred_order_is_independent_of_discovery_order() {
|
||||
let mut installed = families(&["Iosevka", "Noto Sans Mono", "SF Mono", "Hermit"]);
|
||||
for expected in ["Hermit", "SF Mono", "Noto Sans Mono", "Iosevka"] {
|
||||
assert_eq!(select_family(&installed, |_| true), Some(expected));
|
||||
installed.retain(|name| name != expected);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn patched_hermit_has_the_same_preference_as_hermit() {
|
||||
let installed = families(&["SF Mono", "Noto Sans Mono", "Hurmit Nerd Font Mono"]);
|
||||
assert_eq!(
|
||||
select_family(&installed, |_| true),
|
||||
Some("Hurmit Nerd Font Mono")
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn skips_unusable_preferred_fonts() {
|
||||
let installed = families(&["Hermit", "SF Mono", "Iosevka"]);
|
||||
assert_eq!(
|
||||
select_family(&installed, |name| name != "Hermit"),
|
||||
Some("SF Mono")
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn fallback_checks_metrics_instead_of_relying_on_names() {
|
||||
let installed = families(&[
|
||||
"Fake Mono",
|
||||
"Arial",
|
||||
"Inconsolata",
|
||||
"monospace",
|
||||
".SystemUIFont",
|
||||
]);
|
||||
assert_eq!(
|
||||
select_family(&installed, |name| name == "Inconsolata"),
|
||||
Some("Inconsolata")
|
||||
);
|
||||
assert_eq!(select_family(&installed, |_| false), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn synthetic_aliases_are_never_chosen() {
|
||||
let installed = families(&["monospace", ".ZedMono", ".SystemUIFont"]);
|
||||
assert_eq!(select_family(&installed, |_| true), None);
|
||||
}
|
||||
}
|
||||
+238
@@ -0,0 +1,238 @@
|
||||
//! Legacy xterm keyboard encoding, independent of the terminal view.
|
||||
//!
|
||||
//! A view that writes an encoded key must stop GPUI event propagation, so that
|
||||
//! the same printable text is not also delivered through its input handler.
|
||||
//! IME commits can still be written directly by `replace_text_in_range`.
|
||||
|
||||
use alacritty_terminal::term::TermMode;
|
||||
use gpui::Keystroke;
|
||||
|
||||
/// Encode clipboard text using the application's negotiated paste mode.
|
||||
pub fn paste_text(text: &str, bracketed: bool) -> Vec<u8> {
|
||||
if bracketed {
|
||||
// ESC could inject the closing marker; Ctrl-C also ends paste in some
|
||||
// shells. Keep line endings verbatim inside the protected payload.
|
||||
let mut result = b"\x1b[200~".to_vec();
|
||||
result.extend(text.bytes().filter(|byte| !matches!(byte, 0x1b | 0x03)));
|
||||
result.extend_from_slice(b"\x1b[201~");
|
||||
result
|
||||
} else {
|
||||
// An ordinary paste is typed input: Enter is CR. Collapse CRLF first
|
||||
// so Windows text does not execute every line twice.
|
||||
text.replace("\r\n", "\r").replace('\n', "\r").into_bytes()
|
||||
}
|
||||
}
|
||||
|
||||
/// Encode a GPUI key for the terminal's current application-cursor mode.
|
||||
///
|
||||
/// Kitty keyboard reporting and application-keypad distinctions are not yet
|
||||
/// supported (GPUI normalizes most keypad key names).
|
||||
pub fn encode_key(key: &Keystroke, mode: TermMode) -> Option<Vec<u8>> {
|
||||
let modifiers = key.modifiers;
|
||||
if modifiers.platform {
|
||||
return None;
|
||||
}
|
||||
|
||||
// xterm's modifier parameter is 1 + Shift + 2*Alt + 4*Control.
|
||||
let modifier = 1
|
||||
+ u8::from(modifiers.shift)
|
||||
+ 2 * u8::from(modifiers.alt)
|
||||
+ 4 * u8::from(modifiers.control);
|
||||
|
||||
let cursor_key = match key.key.as_str() {
|
||||
"up" => Some('A'),
|
||||
"down" => Some('B'),
|
||||
"right" => Some('C'),
|
||||
"left" => Some('D'),
|
||||
"home" => Some('H'),
|
||||
"end" => Some('F'),
|
||||
_ => None,
|
||||
};
|
||||
if let Some(final_byte) = cursor_key {
|
||||
return Some(if modifier != 1 {
|
||||
format!("\x1b[1;{modifier}{final_byte}").into_bytes()
|
||||
} else if mode.contains(TermMode::APP_CURSOR) {
|
||||
format!("\x1bO{final_byte}").into_bytes()
|
||||
} else {
|
||||
format!("\x1b[{final_byte}").into_bytes()
|
||||
});
|
||||
}
|
||||
|
||||
let tilde_key = match key.key.as_str() {
|
||||
"insert" => Some(2),
|
||||
"delete" => Some(3),
|
||||
"pageup" => Some(5),
|
||||
"pagedown" => Some(6),
|
||||
"f5" => Some(15),
|
||||
"f6" => Some(17),
|
||||
"f7" => Some(18),
|
||||
"f8" => Some(19),
|
||||
"f9" => Some(20),
|
||||
"f10" => Some(21),
|
||||
"f11" => Some(23),
|
||||
"f12" => Some(24),
|
||||
_ => None,
|
||||
};
|
||||
if let Some(number) = tilde_key {
|
||||
return Some(if modifier == 1 {
|
||||
format!("\x1b[{number}~").into_bytes()
|
||||
} else {
|
||||
format!("\x1b[{number};{modifier}~").into_bytes()
|
||||
});
|
||||
}
|
||||
|
||||
let function_key = match key.key.as_str() {
|
||||
"f1" => Some('P'),
|
||||
"f2" => Some('Q'),
|
||||
"f3" => Some('R'),
|
||||
"f4" => Some('S'),
|
||||
_ => None,
|
||||
};
|
||||
if let Some(final_byte) = function_key {
|
||||
return Some(if modifier == 1 {
|
||||
format!("\x1bO{final_byte}").into_bytes()
|
||||
} else {
|
||||
format!("\x1b[1;{modifier}{final_byte}").into_bytes()
|
||||
});
|
||||
}
|
||||
|
||||
let mut bytes = match key.key.as_str() {
|
||||
"enter" => {
|
||||
if mode.contains(TermMode::LINE_FEED_NEW_LINE) {
|
||||
b"\r\n".to_vec()
|
||||
} else {
|
||||
vec![b'\r']
|
||||
}
|
||||
}
|
||||
"backspace" => vec![if modifiers.control { 0x08 } else { 0x7f }],
|
||||
"escape" => vec![0x1b],
|
||||
"tab" if modifiers.shift => {
|
||||
return Some(if !modifiers.control && !modifiers.alt {
|
||||
b"\x1b[Z".to_vec()
|
||||
} else {
|
||||
format!("\x1b[1;{modifier}Z").into_bytes()
|
||||
});
|
||||
}
|
||||
"tab" => vec![b'\t'],
|
||||
_ if modifiers.control => vec![control_byte(&key.key)?],
|
||||
// Do not fall back to `key`: a missing key_char can mean that a dead
|
||||
// key or compose sequence is still waiting for its next character.
|
||||
_ => key.key_char.as_ref()?.as_bytes().to_vec(),
|
||||
};
|
||||
if modifiers.alt {
|
||||
bytes.insert(0, 0x1b);
|
||||
}
|
||||
Some(bytes)
|
||||
}
|
||||
|
||||
fn control_byte(key: &str) -> Option<u8> {
|
||||
match key {
|
||||
"space" | "@" | "2" | "`" => Some(0),
|
||||
"[" | "{" | "3" => Some(0x1b),
|
||||
"\\" | "|" | "4" => Some(0x1c),
|
||||
"]" | "}" | "5" => Some(0x1d),
|
||||
"^" | "~" | "6" => Some(0x1e),
|
||||
"_" | "-" | "/" | "7" => Some(0x1f),
|
||||
"?" | "8" => Some(0x7f),
|
||||
_ if key.len() == 1 && key.as_bytes()[0].is_ascii_alphabetic() => {
|
||||
Some(key.as_bytes()[0].to_ascii_uppercase() & 0x1f)
|
||||
}
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn encode(binding: &str, mode: TermMode) -> Vec<u8> {
|
||||
encode_key(
|
||||
&Keystroke::parse(binding).unwrap().with_simulated_ime(),
|
||||
mode,
|
||||
)
|
||||
.unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bracketed_paste_cannot_inject_an_end_marker() {
|
||||
assert_eq!(
|
||||
paste_text("hello\n世界\r\n\x1b[201~\x03oops", true),
|
||||
"\x1b[200~hello\n世界\r\n[201~oops\x1b[201~".as_bytes()
|
||||
);
|
||||
assert_eq!(paste_text("", true), b"\x1b[200~\x1b[201~");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ordinary_paste_normalizes_line_endings_once() {
|
||||
assert_eq!(
|
||||
paste_text("one\r\ntwo\nthree\rfour\n", false),
|
||||
b"one\rtwo\rthree\rfour\r"
|
||||
);
|
||||
assert_eq!(paste_text("世界", false), "世界".as_bytes());
|
||||
assert!(paste_text("", false).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn shell_control_keys_and_alt_prefix() {
|
||||
for (key, expected) in [
|
||||
("ctrl-c", b"\x03".as_slice()),
|
||||
("ctrl-d", b"\x04"),
|
||||
("ctrl-z", b"\x1a"),
|
||||
("ctrl-space", b"\x00"),
|
||||
("ctrl-[", b"\x1b"),
|
||||
("ctrl-\\", b"\x1c"),
|
||||
("ctrl-]", b"\x1d"),
|
||||
("ctrl-6", b"\x1e"),
|
||||
("ctrl-/", b"\x1f"),
|
||||
("alt-ctrl-c", b"\x1b\x03"),
|
||||
("backspace", b"\x7f"),
|
||||
("ctrl-backspace", b"\x08"),
|
||||
("enter", b"\r"),
|
||||
("shift-tab", b"\x1b[Z"),
|
||||
] {
|
||||
assert_eq!(encode(key, TermMode::empty()), expected, "{key}");
|
||||
}
|
||||
assert_eq!(encode("enter", TermMode::LINE_FEED_NEW_LINE), b"\r\n");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn application_cursor_and_modified_navigation() {
|
||||
assert_eq!(encode("up", TermMode::empty()), b"\x1b[A");
|
||||
assert_eq!(encode("up", TermMode::APP_CURSOR), b"\x1bOA");
|
||||
assert_eq!(encode("home", TermMode::APP_CURSOR), b"\x1bOH");
|
||||
assert_eq!(encode("ctrl-left", TermMode::APP_CURSOR), b"\x1b[1;5D");
|
||||
assert_eq!(encode("alt-shift-right", TermMode::empty()), b"\x1b[1;4C");
|
||||
assert_eq!(encode("ctrl-delete", TermMode::empty()), b"\x1b[3;5~");
|
||||
assert_eq!(encode("pagedown", TermMode::empty()), b"\x1b[6~");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn function_keys_use_xterm_sequences() {
|
||||
assert_eq!(encode("f1", TermMode::empty()), b"\x1bOP");
|
||||
assert_eq!(encode("shift-f4", TermMode::empty()), b"\x1b[1;2S");
|
||||
assert_eq!(encode("f5", TermMode::empty()), b"\x1b[15~");
|
||||
assert_eq!(encode("ctrl-alt-f12", TermMode::empty()), b"\x1b[24;7~");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unicode_uses_committed_text_and_dead_keys_wait() {
|
||||
let mut key = Keystroke {
|
||||
key: "e".into(),
|
||||
key_char: Some("é".into()),
|
||||
..Default::default()
|
||||
};
|
||||
assert_eq!(encode_key(&key, TermMode::empty()).unwrap(), "é".as_bytes());
|
||||
key.key_char = Some("你好".into());
|
||||
assert_eq!(
|
||||
encode_key(&key, TermMode::empty()).unwrap(),
|
||||
"你好".as_bytes()
|
||||
);
|
||||
key.key_char = None;
|
||||
assert_eq!(encode_key(&key, TermMode::empty()), None);
|
||||
key.key_char = Some("e".into());
|
||||
key.modifiers.alt = true;
|
||||
assert_eq!(encode_key(&key, TermMode::empty()).unwrap(), b"\x1be");
|
||||
key.modifiers.platform = true;
|
||||
assert_eq!(encode_key(&key, TermMode::empty()), None);
|
||||
}
|
||||
}
|
||||
+37
@@ -0,0 +1,37 @@
|
||||
mod colors;
|
||||
mod fonts;
|
||||
mod input;
|
||||
mod render;
|
||||
mod session;
|
||||
mod terminal;
|
||||
|
||||
use gpui::{prelude::*, *};
|
||||
|
||||
fn main() -> anyhow::Result<()> {
|
||||
env_logger::init();
|
||||
let (session, events) = session::Session::new()?;
|
||||
Application::new().run(move |cx: &mut App| {
|
||||
cx.on_window_closed(|cx| {
|
||||
if cx.windows().is_empty() {
|
||||
cx.quit();
|
||||
}
|
||||
})
|
||||
.detach();
|
||||
let bounds = Bounds::centered(None, size(px(960.), px(640.)), cx);
|
||||
cx.open_window(
|
||||
WindowOptions {
|
||||
window_bounds: Some(WindowBounds::Windowed(bounds)),
|
||||
titlebar: Some(TitlebarOptions {
|
||||
title: Some("Terminal".into()),
|
||||
..Default::default()
|
||||
}),
|
||||
app_id: Some("dev.buzzert.terminal".into()),
|
||||
..Default::default()
|
||||
},
|
||||
move |window, cx| cx.new(|cx| terminal::TerminalView::new(session, events, window, cx)),
|
||||
)
|
||||
.expect("could not open terminal window");
|
||||
cx.activate(true);
|
||||
});
|
||||
Ok(())
|
||||
}
|
||||
+573
@@ -0,0 +1,573 @@
|
||||
//! Cached terminal rows and batched GPUI drawing.
|
||||
//!
|
||||
//! ASCII spans share one shaped line. Unicode clusters retain explicit terminal
|
||||
//! cell positions, so wide characters, combining marks, and bidi text cannot
|
||||
//! move their neighbours. Unchanged rows retain their shaped lines across frames.
|
||||
use std::sync::Arc;
|
||||
|
||||
use alacritty_terminal::{
|
||||
term::cell::{Cell, Flags},
|
||||
vte::ansi::CursorShape,
|
||||
};
|
||||
use gpui::{
|
||||
App, Bounds, Font, FontFeatures, Hsla, Pixels, Point, ShapedLine, TextRun, Window, fill, point,
|
||||
px, rgb, size,
|
||||
};
|
||||
|
||||
use crate::colors;
|
||||
|
||||
pub const FONT_SIZE: f32 = 15.;
|
||||
pub const LINE_HEIGHT: f32 = 20.;
|
||||
|
||||
#[derive(Clone, PartialEq)]
|
||||
pub struct RenderCell {
|
||||
pub cell: Cell,
|
||||
pub foreground: Hsla,
|
||||
pub background: Hsla,
|
||||
pub cursor: CursorShape,
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
pub struct Renderer {
|
||||
rows: Vec<CachedRow>,
|
||||
font: Option<Font>,
|
||||
cell_width: f32,
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
struct CachedRow {
|
||||
cells: Vec<RenderCell>,
|
||||
backgrounds: Vec<Span>,
|
||||
decorations: Vec<Decoration>,
|
||||
cursors: Vec<Decoration>,
|
||||
text: Vec<PositionedLine>,
|
||||
}
|
||||
|
||||
struct PositionedLine {
|
||||
column: usize,
|
||||
line: ShapedLine,
|
||||
// Unicode segments contain exactly one terminal cell cluster and color.
|
||||
// Paint those cached glyphs directly in one shared layer below.
|
||||
unicode_color: Option<Hsla>,
|
||||
}
|
||||
|
||||
#[derive(Debug, PartialEq)]
|
||||
struct Span {
|
||||
column: usize,
|
||||
columns: usize,
|
||||
color: Hsla,
|
||||
}
|
||||
|
||||
#[derive(Debug, PartialEq)]
|
||||
struct Decoration {
|
||||
span: Span,
|
||||
y: f32,
|
||||
height: f32,
|
||||
// Beam cursors use an absolute width instead of a full cell span.
|
||||
width: Option<f32>,
|
||||
}
|
||||
|
||||
/// A contiguous ASCII segment, or one explicitly positioned Unicode cell.
|
||||
#[derive(Debug, PartialEq)]
|
||||
struct TextSegment {
|
||||
column: usize,
|
||||
text: String,
|
||||
styles: Vec<TextStyle>,
|
||||
bold: bool,
|
||||
italic: bool,
|
||||
ascii: bool,
|
||||
}
|
||||
|
||||
#[derive(Debug, PartialEq)]
|
||||
struct TextStyle {
|
||||
bytes: usize,
|
||||
color: Hsla,
|
||||
}
|
||||
|
||||
impl Renderer {
|
||||
pub fn prepare(
|
||||
&mut self,
|
||||
rows: Vec<Vec<RenderCell>>,
|
||||
font: &Font,
|
||||
cell_width: f32,
|
||||
window: &mut Window,
|
||||
) {
|
||||
let metrics_changed = self.font.as_ref() != Some(font) || self.cell_width != cell_width;
|
||||
self.font = Some(font.clone());
|
||||
self.cell_width = cell_width;
|
||||
self.rows.resize_with(rows.len(), CachedRow::default);
|
||||
for (cached, cells) in self.rows.iter_mut().zip(rows) {
|
||||
if !metrics_changed && cached.cells == cells {
|
||||
continue;
|
||||
}
|
||||
let (backgrounds, decorations, cursors) = assemble_quads(&cells);
|
||||
let text = assemble_text(&cells)
|
||||
.into_iter()
|
||||
.map(|segment| {
|
||||
let mut face = font.clone();
|
||||
if segment.bold {
|
||||
face = face.bold();
|
||||
}
|
||||
if segment.italic {
|
||||
face = face.italic();
|
||||
}
|
||||
// GPUI's disable_ligatures helper only disables `calt`.
|
||||
// Disable the common ligature tags too: one ASCII glyph
|
||||
// must occupy exactly one terminal column.
|
||||
face.features = FontFeatures(Arc::new(vec![
|
||||
("calt".into(), 0),
|
||||
("liga".into(), 0),
|
||||
("clig".into(), 0),
|
||||
]));
|
||||
let unicode_color = (!segment.ascii).then(|| segment.styles[0].color);
|
||||
let runs: Vec<_> = segment
|
||||
.styles
|
||||
.into_iter()
|
||||
.map(|style| TextRun {
|
||||
len: style.bytes,
|
||||
font: face.clone(),
|
||||
color: style.color,
|
||||
background_color: None,
|
||||
underline: None,
|
||||
strikethrough: None,
|
||||
})
|
||||
.collect();
|
||||
PositionedLine {
|
||||
column: segment.column,
|
||||
unicode_color,
|
||||
line: window.text_system().shape_line(
|
||||
segment.text.into(),
|
||||
px(FONT_SIZE),
|
||||
&runs,
|
||||
// GPUI applies forced widths per glyph, so this
|
||||
// is valid only for non-ligature ASCII segments.
|
||||
segment.ascii.then_some(px(cell_width)),
|
||||
),
|
||||
}
|
||||
})
|
||||
.collect();
|
||||
*cached = CachedRow {
|
||||
cells,
|
||||
backgrounds,
|
||||
decorations,
|
||||
cursors,
|
||||
text,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
/// `origin` is the top-left terminal cell, after the view's padding.
|
||||
pub fn paint(&self, origin: Point<Pixels>, window: &mut Window, cx: &mut App) {
|
||||
let bounds = Bounds::new(
|
||||
origin,
|
||||
size(
|
||||
px(self
|
||||
.rows
|
||||
.iter()
|
||||
.map(|row| row.cells.len())
|
||||
.max()
|
||||
.unwrap_or(0) as f32
|
||||
* self.cell_width),
|
||||
px(self.rows.len() as f32 * LINE_HEIGHT),
|
||||
),
|
||||
);
|
||||
// Non-overlapping backgrounds share one draw order. This avoids a
|
||||
// bounds-tree insertion for every terminal cell, especially on resize.
|
||||
window.paint_layer(bounds, |window| {
|
||||
for (row_index, row) in self.rows.iter().enumerate() {
|
||||
for span in &row.backgrounds {
|
||||
window.paint_quad(fill(
|
||||
Bounds::new(
|
||||
origin
|
||||
+ point(
|
||||
px(span.column as f32 * self.cell_width),
|
||||
px(row_index as f32 * LINE_HEIGHT),
|
||||
),
|
||||
size(px(span.columns as f32 * self.cell_width), px(LINE_HEIGHT)),
|
||||
),
|
||||
span.color,
|
||||
));
|
||||
}
|
||||
}
|
||||
});
|
||||
for (row_index, row) in self.rows.iter().enumerate() {
|
||||
for text in &row.text {
|
||||
if text.unicode_color.is_some() {
|
||||
continue;
|
||||
}
|
||||
let position = origin
|
||||
+ point(
|
||||
px(text.column as f32 * self.cell_width),
|
||||
px(row_index as f32 * LINE_HEIGHT),
|
||||
);
|
||||
if let Err(error) = text.line.paint(position, px(LINE_HEIGHT), window, cx) {
|
||||
log::debug!("terminal text paint: {error}");
|
||||
}
|
||||
}
|
||||
}
|
||||
// A box-drawing/CJK screen can contain thousands of separate Unicode
|
||||
// clusters. ShapedLine::paint would create a bounds-tree layer for each
|
||||
// one; reuse its cached glyphs directly with one draw order instead.
|
||||
window.paint_layer(bounds, |window| {
|
||||
for (row_index, row) in self.rows.iter().enumerate() {
|
||||
for text in &row.text {
|
||||
let Some(color) = text.unicode_color else {
|
||||
continue;
|
||||
};
|
||||
let line = &text.line;
|
||||
let baseline =
|
||||
(px(LINE_HEIGHT) - line.ascent - line.descent) / 2. + line.ascent;
|
||||
let position = origin
|
||||
+ point(
|
||||
px(text.column as f32 * self.cell_width),
|
||||
px(row_index as f32 * LINE_HEIGHT) + baseline,
|
||||
);
|
||||
for run in &line.runs {
|
||||
for glyph in &run.glyphs {
|
||||
// Match GPUI's unwrapped ShapedLine painter: glyph
|
||||
// x is relative to the line; y uses the line baseline.
|
||||
let glyph_origin = position + point(glyph.position.x, px(0.));
|
||||
let result = if glyph.is_emoji {
|
||||
window.paint_emoji(
|
||||
glyph_origin,
|
||||
run.font_id,
|
||||
glyph.id,
|
||||
line.font_size,
|
||||
)
|
||||
} else {
|
||||
window.paint_glyph(
|
||||
glyph_origin,
|
||||
run.font_id,
|
||||
glyph.id,
|
||||
line.font_size,
|
||||
color,
|
||||
)
|
||||
};
|
||||
if let Err(error) = result {
|
||||
log::debug!("terminal Unicode paint: {error}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
// Decorations overlap text and therefore need their own draw order.
|
||||
window.paint_layer(bounds, |window| {
|
||||
for (row_index, row) in self.rows.iter().enumerate() {
|
||||
for decoration in &row.decorations {
|
||||
self.paint_decoration(decoration, row_index, origin, window);
|
||||
}
|
||||
}
|
||||
});
|
||||
window.paint_layer(bounds, |window| {
|
||||
for (row_index, row) in self.rows.iter().enumerate() {
|
||||
for cursor in &row.cursors {
|
||||
self.paint_decoration(cursor, row_index, origin, window);
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
fn paint_decoration(
|
||||
&self,
|
||||
decoration: &Decoration,
|
||||
row: usize,
|
||||
origin: Point<Pixels>,
|
||||
window: &mut Window,
|
||||
) {
|
||||
let span = &decoration.span;
|
||||
window.paint_quad(fill(
|
||||
Bounds::new(
|
||||
origin
|
||||
+ point(
|
||||
px(span.column as f32 * self.cell_width),
|
||||
px(row as f32 * LINE_HEIGHT + decoration.y),
|
||||
),
|
||||
size(
|
||||
px(decoration
|
||||
.width
|
||||
.unwrap_or(span.columns as f32 * self.cell_width)),
|
||||
px(decoration.height),
|
||||
),
|
||||
),
|
||||
span.color,
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
fn assemble_quads(cells: &[RenderCell]) -> (Vec<Span>, Vec<Decoration>, Vec<Decoration>) {
|
||||
let mut backgrounds: Vec<Span> = Vec::new();
|
||||
let mut decorations: Vec<Decoration> = Vec::new();
|
||||
let mut cursors = Vec::new();
|
||||
let default_background: Hsla = rgb(colors::BACKGROUND).into();
|
||||
for (column, cell) in cells.iter().enumerate() {
|
||||
if cell.background != default_background {
|
||||
append_span(&mut backgrounds, column, 1, cell.background);
|
||||
}
|
||||
let flags = cell.cell.flags;
|
||||
if !flags
|
||||
.intersects(Flags::WIDE_CHAR_SPACER | Flags::LEADING_WIDE_CHAR_SPACER | Flags::HIDDEN)
|
||||
{
|
||||
let columns = if flags.contains(Flags::WIDE_CHAR) {
|
||||
2
|
||||
} else {
|
||||
1
|
||||
};
|
||||
if flags.intersects(Flags::ALL_UNDERLINES) {
|
||||
append_decoration(
|
||||
&mut decorations,
|
||||
column,
|
||||
columns,
|
||||
cell.foreground,
|
||||
LINE_HEIGHT - 2.,
|
||||
);
|
||||
}
|
||||
if flags.contains(Flags::STRIKEOUT) {
|
||||
append_decoration(
|
||||
&mut decorations,
|
||||
column,
|
||||
columns,
|
||||
cell.foreground,
|
||||
LINE_HEIGHT / 2.,
|
||||
);
|
||||
}
|
||||
}
|
||||
let (y, height, width) = match cell.cursor {
|
||||
CursorShape::Beam => (0., LINE_HEIGHT, Some(2.)),
|
||||
CursorShape::Underline => (LINE_HEIGHT - 2., 2., None),
|
||||
_ => continue,
|
||||
};
|
||||
cursors.push(Decoration {
|
||||
span: Span {
|
||||
column,
|
||||
columns: 1,
|
||||
color: rgb(colors::FOREGROUND).into(),
|
||||
},
|
||||
y,
|
||||
height,
|
||||
width,
|
||||
});
|
||||
}
|
||||
(backgrounds, decorations, cursors)
|
||||
}
|
||||
|
||||
fn append_span(spans: &mut Vec<Span>, column: usize, columns: usize, color: Hsla) {
|
||||
if let Some(previous) = spans.last_mut()
|
||||
&& previous.column + previous.columns == column
|
||||
&& previous.color == color
|
||||
{
|
||||
previous.columns += columns;
|
||||
} else {
|
||||
spans.push(Span {
|
||||
column,
|
||||
columns,
|
||||
color,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
fn append_decoration(
|
||||
decorations: &mut Vec<Decoration>,
|
||||
column: usize,
|
||||
columns: usize,
|
||||
color: Hsla,
|
||||
y: f32,
|
||||
) {
|
||||
// Search backwards for this decoration kind; underline and strike can be
|
||||
// interleaved while still extending the same adjacent horizontal span.
|
||||
if let Some(previous) = decorations
|
||||
.iter_mut()
|
||||
.rev()
|
||||
.find(|decoration| decoration.y == y)
|
||||
&& previous.span.column + previous.span.columns == column
|
||||
&& previous.span.color == color
|
||||
{
|
||||
previous.span.columns += columns;
|
||||
} else {
|
||||
decorations.push(Decoration {
|
||||
span: Span {
|
||||
column,
|
||||
columns,
|
||||
color,
|
||||
},
|
||||
y,
|
||||
height: 1.,
|
||||
width: None,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
fn assemble_text(cells: &[RenderCell]) -> Vec<TextSegment> {
|
||||
let mut segments: Vec<TextSegment> = Vec::new();
|
||||
for (column, cell) in cells.iter().enumerate() {
|
||||
let flags = cell.cell.flags;
|
||||
if flags
|
||||
.intersects(Flags::WIDE_CHAR_SPACER | Flags::LEADING_WIDE_CHAR_SPACER | Flags::HIDDEN)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
let extra = cell.cell.zerowidth().filter(|extra| !extra.is_empty());
|
||||
if cell.cell.c == ' ' && extra.is_none() {
|
||||
// Keep interior spaces inside an existing ASCII segment, avoiding
|
||||
// a separate paint layer per word. Trailing spaces are trimmed below.
|
||||
if let Some(previous) = segments.last_mut()
|
||||
&& previous.ascii
|
||||
&& previous.column + previous.text.len() == column
|
||||
{
|
||||
previous.text.push(' ');
|
||||
if let Some(style) = previous.styles.last_mut() {
|
||||
style.bytes += 1;
|
||||
}
|
||||
}
|
||||
continue;
|
||||
}
|
||||
let mut text = cell.cell.c.to_string();
|
||||
if let Some(extra) = extra {
|
||||
text.extend(extra);
|
||||
}
|
||||
let ascii = cell.cell.c.is_ascii() && extra.is_none() && !flags.contains(Flags::WIDE_CHAR);
|
||||
let bold = flags.contains(Flags::BOLD);
|
||||
let italic = flags.contains(Flags::ITALIC);
|
||||
if ascii
|
||||
&& let Some(previous) = segments.last_mut()
|
||||
&& previous.ascii
|
||||
&& previous.bold == bold
|
||||
&& previous.italic == italic
|
||||
&& previous.column + previous.text.len() == column
|
||||
{
|
||||
previous.text.push(cell.cell.c);
|
||||
if let Some(style) = previous.styles.last_mut()
|
||||
&& style.color == cell.foreground
|
||||
{
|
||||
style.bytes += 1;
|
||||
} else {
|
||||
previous.styles.push(TextStyle {
|
||||
bytes: 1,
|
||||
color: cell.foreground,
|
||||
});
|
||||
}
|
||||
} else {
|
||||
segments.push(TextSegment {
|
||||
column,
|
||||
styles: vec![TextStyle {
|
||||
bytes: text.len(),
|
||||
color: cell.foreground,
|
||||
}],
|
||||
text,
|
||||
bold,
|
||||
italic,
|
||||
ascii,
|
||||
});
|
||||
}
|
||||
}
|
||||
for segment in &mut segments {
|
||||
if segment.ascii {
|
||||
let trimmed = segment.text.trim_end_matches(' ').len();
|
||||
let mut removed = segment.text.len() - trimmed;
|
||||
segment.text.truncate(trimmed);
|
||||
while removed > 0 {
|
||||
let style = segment.styles.last_mut().expect("nonempty ASCII style");
|
||||
let count = removed.min(style.bytes);
|
||||
style.bytes -= count;
|
||||
removed -= count;
|
||||
if style.bytes == 0 {
|
||||
segment.styles.pop();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
segments
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn cell(c: char) -> RenderCell {
|
||||
RenderCell {
|
||||
cell: Cell {
|
||||
c,
|
||||
..Cell::default()
|
||||
},
|
||||
foreground: rgb(colors::FOREGROUND).into(),
|
||||
background: rgb(colors::BACKGROUND).into(),
|
||||
cursor: CursorShape::Hidden,
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn blank_screen_has_no_text_or_background_work() {
|
||||
let cells = vec![cell(' '); 250];
|
||||
assert!(assemble_text(&cells).is_empty());
|
||||
let (backgrounds, decorations, cursors) = assemble_quads(&cells);
|
||||
assert!(backgrounds.is_empty() && decorations.is_empty() && cursors.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn colored_ascii_stays_in_one_positioned_line() {
|
||||
let mut cells: Vec<_> = "abcdef".chars().map(cell).collect();
|
||||
cells[2].foreground = rgb(0xff0000).into();
|
||||
let text = assemble_text(&cells);
|
||||
assert_eq!(text.len(), 1);
|
||||
assert_eq!(text[0].text, "abcdef");
|
||||
assert_eq!(
|
||||
text[0]
|
||||
.styles
|
||||
.iter()
|
||||
.map(|run| run.bytes)
|
||||
.collect::<Vec<_>>(),
|
||||
vec![2, 1, 3]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn internal_spaces_batch_but_blank_margins_do_not() {
|
||||
let cells: Vec<_> = " one two three ".chars().map(cell).collect();
|
||||
let text = assemble_text(&cells);
|
||||
assert_eq!(text.len(), 1);
|
||||
assert_eq!(text[0].column, 2);
|
||||
assert_eq!(text[0].text, "one two three");
|
||||
assert_eq!(
|
||||
text[0]
|
||||
.styles
|
||||
.iter()
|
||||
.map(|style| style.bytes)
|
||||
.sum::<usize>(),
|
||||
13
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unicode_clusters_do_not_shift_following_columns() {
|
||||
let mut cells = vec![cell('A'), cell('界'), cell(' '), cell('e'), cell('Z')];
|
||||
cells[1].cell.flags.insert(Flags::WIDE_CHAR);
|
||||
cells[2].cell.flags.insert(Flags::WIDE_CHAR_SPACER);
|
||||
cells[3].cell.push_zerowidth('\u{301}');
|
||||
let text = assemble_text(&cells);
|
||||
assert_eq!(
|
||||
text.iter()
|
||||
.map(|segment| (segment.column, segment.text.as_str()))
|
||||
.collect::<Vec<_>>(),
|
||||
vec![(0, "A"), (1, "界"), (3, "e\u{301}"), (4, "Z")]
|
||||
);
|
||||
assert!(!text[1].ascii && !text[2].ascii);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn backgrounds_and_decorations_merge_without_painting_blank_defaults() {
|
||||
let mut cells = vec![cell(' '); 10];
|
||||
for c in &mut cells[2..7] {
|
||||
c.background = rgb(0x123456).into();
|
||||
c.cell.flags.insert(Flags::UNDERLINE | Flags::STRIKEOUT);
|
||||
}
|
||||
let (backgrounds, decorations, _) = assemble_quads(&cells);
|
||||
assert_eq!(backgrounds.len(), 1);
|
||||
assert_eq!((backgrounds[0].column, backgrounds[0].columns), (2, 5));
|
||||
assert_eq!(decorations.len(), 2);
|
||||
assert!(
|
||||
decorations
|
||||
.iter()
|
||||
.all(|span| span.span.column == 2 && span.span.columns == 5)
|
||||
);
|
||||
}
|
||||
}
|
||||
+484
@@ -0,0 +1,484 @@
|
||||
//! One shell, its PTY, and its terminal state, independent of the window layout.
|
||||
//!
|
||||
//! A future pane can own a `Session` without owning a window. Alacritty handles
|
||||
//! escape sequences, scrollback, PTY polling, and child-process notifications.
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::sync::Arc;
|
||||
use std::sync::atomic::{AtomicBool, Ordering};
|
||||
use std::thread::{self, JoinHandle};
|
||||
|
||||
use alacritty_terminal::event::{Event, EventListener, WindowSize};
|
||||
use alacritty_terminal::event_loop::{EventLoop, EventLoopSender, Msg};
|
||||
use alacritty_terminal::grid::Dimensions;
|
||||
use alacritty_terminal::sync::FairMutex;
|
||||
use alacritty_terminal::term::{Config, Term};
|
||||
use alacritty_terminal::tty::{self, Options, Shell};
|
||||
use anyhow::{Context, Result};
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct EventProxy {
|
||||
sender: async_channel::Sender<Event>,
|
||||
wakeup_pending: Arc<AtomicBool>,
|
||||
}
|
||||
|
||||
impl EventProxy {
|
||||
fn new(sender: async_channel::Sender<Event>) -> Self {
|
||||
Self {
|
||||
sender,
|
||||
wakeup_pending: Arc::new(AtomicBool::new(false)),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl EventListener for EventProxy {
|
||||
fn send_event(&self, event: Event) {
|
||||
// Terminal output may generate thousands of updates between frames.
|
||||
// One queued wakeup suffices because the renderer reads the latest grid.
|
||||
if matches!(event, Event::Wakeup) && self.wakeup_pending.swap(true, Ordering::AcqRel) {
|
||||
return;
|
||||
}
|
||||
// The UI disappearing is normal during window shutdown.
|
||||
// An unbounded async channel wakes the UI immediately without making the
|
||||
// PTY thread wait for it or requiring an idle polling timer.
|
||||
let _ = self.sender.try_send(event);
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy)]
|
||||
struct GridSize(WindowSize);
|
||||
|
||||
impl Dimensions for GridSize {
|
||||
fn total_lines(&self) -> usize {
|
||||
self.screen_lines()
|
||||
}
|
||||
|
||||
fn screen_lines(&self) -> usize {
|
||||
self.0.num_lines as usize
|
||||
}
|
||||
|
||||
fn columns(&self) -> usize {
|
||||
self.0.num_cols as usize
|
||||
}
|
||||
}
|
||||
|
||||
pub struct Session {
|
||||
pub term: Arc<FairMutex<Term<EventProxy>>>,
|
||||
sender: EventLoopSender,
|
||||
wakeup_pending: Arc<AtomicBool>,
|
||||
size: WindowSize,
|
||||
// A pidfd identifies this process even after its numerical PID is reused.
|
||||
#[cfg(target_os = "linux")]
|
||||
process: LinuxProcess,
|
||||
worker: Option<JoinHandle<()>>,
|
||||
}
|
||||
|
||||
impl Session {
|
||||
pub fn new() -> Result<(Self, async_channel::Receiver<Event>)> {
|
||||
let program = std::env::var("SHELL")
|
||||
.ok()
|
||||
.filter(|shell| !shell.is_empty())
|
||||
.unwrap_or_else(|| "/bin/sh".into());
|
||||
Self::with_shell(Shell::new(program, Vec::new()))
|
||||
}
|
||||
|
||||
fn with_shell(shell: Shell) -> Result<(Self, async_channel::Receiver<Event>)> {
|
||||
let size = WindowSize {
|
||||
num_cols: 80,
|
||||
num_lines: 24,
|
||||
cell_width: 8,
|
||||
cell_height: 16,
|
||||
};
|
||||
let (tx, rx) = async_channel::unbounded();
|
||||
let proxy = EventProxy::new(tx);
|
||||
let wakeup_pending = proxy.wakeup_pending.clone();
|
||||
let term = Arc::new(FairMutex::new(Term::new(
|
||||
Config::default(),
|
||||
&GridSize(size),
|
||||
proxy.clone(),
|
||||
)));
|
||||
let options = Options {
|
||||
shell: Some(shell),
|
||||
// None preserves the directory from which the application launched.
|
||||
working_directory: None,
|
||||
drain_on_exit: true,
|
||||
env: HashMap::from([
|
||||
("TERM".into(), "xterm-256color".into()),
|
||||
("COLORTERM".into(), "truecolor".into()),
|
||||
]),
|
||||
};
|
||||
let pty = tty::new(&options, size, 0).context("Could not start the shell PTY")?;
|
||||
#[cfg(target_os = "linux")]
|
||||
let process = LinuxProcess::new(pty.child().id())?;
|
||||
let event_loop = EventLoop::new(term.clone(), proxy.clone(), pty, true, false)
|
||||
.context("Could not initialize PTY polling")?;
|
||||
let sender = event_loop.channel();
|
||||
// Keep the returned EventLoop alive only until the reader finishes. Its
|
||||
// returned value owns the PTY, which must be dropped to reap the shell.
|
||||
let worker = thread::Builder::new()
|
||||
.name("terminal-session".into())
|
||||
.spawn(move || {
|
||||
match event_loop.spawn().join() {
|
||||
Ok(state) => drop(state),
|
||||
Err(_) => log::error!("The terminal PTY thread panicked"),
|
||||
}
|
||||
// Also close the window on I/O failures that have no Exit event.
|
||||
proxy.send_event(Event::Exit);
|
||||
})
|
||||
.context("Could not start the terminal session thread")?;
|
||||
|
||||
Ok((
|
||||
Self {
|
||||
term,
|
||||
sender,
|
||||
wakeup_pending,
|
||||
size,
|
||||
#[cfg(target_os = "linux")]
|
||||
process,
|
||||
worker: Some(worker),
|
||||
},
|
||||
rx,
|
||||
))
|
||||
}
|
||||
|
||||
pub fn write(&self, bytes: Vec<u8>) {
|
||||
// An empty write can stall the Alacritty writer.
|
||||
if !bytes.is_empty() {
|
||||
let _ = self.sender.send(Msg::Input(bytes.into()));
|
||||
}
|
||||
}
|
||||
|
||||
pub fn size(&self) -> WindowSize {
|
||||
self.size
|
||||
}
|
||||
|
||||
/// Call when receiving `Event::Wakeup`, before reading the grid for a frame.
|
||||
pub fn acknowledge_wakeup(&self) {
|
||||
self.wakeup_pending.store(false, Ordering::Release);
|
||||
}
|
||||
|
||||
pub fn resize(&mut self, columns: usize, lines: usize, cell_width: u16, cell_height: u16) {
|
||||
// Alacritty requires at least two columns; a hidden/minimized pane may
|
||||
// temporarily have no pixel area. Clamp before converting to PTY u16s.
|
||||
let size = WindowSize {
|
||||
num_cols: columns.clamp(2, u16::MAX as usize) as u16,
|
||||
num_lines: lines.clamp(1, u16::MAX as usize) as u16,
|
||||
cell_width: cell_width.max(1),
|
||||
cell_height: cell_height.max(1),
|
||||
};
|
||||
if (
|
||||
size.num_cols,
|
||||
size.num_lines,
|
||||
size.cell_width,
|
||||
size.cell_height,
|
||||
) == (
|
||||
self.size.num_cols,
|
||||
self.size.num_lines,
|
||||
self.size.cell_width,
|
||||
self.size.cell_height,
|
||||
) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Update the grid before SIGWINCH lets the child draw at its new size.
|
||||
self.term.lock().resize(GridSize(size));
|
||||
self.size = size;
|
||||
let _ = self.sender.send(Msg::Resize(size));
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for Session {
|
||||
fn drop(&mut self) {
|
||||
let _ = self.sender.send(Msg::Shutdown);
|
||||
// Joining guarantees that the shell is reaped before application exit.
|
||||
// Usually SIGHUP finishes immediately. Linux escalation bounds the grace
|
||||
// period for shells that explicitly ignore SIGHUP.
|
||||
#[cfg(target_os = "linux")]
|
||||
self.process.finish_shutdown();
|
||||
if let Some(worker) = self.worker.take() {
|
||||
let _ = worker.join();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(target_os = "linux")]
|
||||
struct LinuxProcess(std::os::fd::OwnedFd);
|
||||
|
||||
#[cfg(target_os = "linux")]
|
||||
impl LinuxProcess {
|
||||
fn new(pid: u32) -> Result<Self> {
|
||||
use std::os::fd::FromRawFd;
|
||||
// SAFETY: pidfd_open takes an integer PID and flags, and returns a fresh
|
||||
// descriptor. No pointer arguments or shared process state are modified.
|
||||
let fd = unsafe { libc::syscall(libc::SYS_pidfd_open, pid, 0) };
|
||||
if fd == -1 {
|
||||
return Err(std::io::Error::last_os_error())
|
||||
.context("Could not open shell lifecycle handle (Linux 5.3+ required)");
|
||||
}
|
||||
// SAFETY: this successful syscall returned a descriptor owned by us.
|
||||
Ok(Self(unsafe {
|
||||
std::os::fd::OwnedFd::from_raw_fd(fd as i32)
|
||||
}))
|
||||
}
|
||||
|
||||
fn finish_shutdown(&self) {
|
||||
use std::os::fd::AsRawFd;
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
let deadline = Instant::now() + Duration::from_millis(300);
|
||||
let mut pollfd = libc::pollfd {
|
||||
fd: self.0.as_raw_fd(),
|
||||
events: libc::POLLIN,
|
||||
revents: 0,
|
||||
};
|
||||
loop {
|
||||
let timeout = deadline
|
||||
.saturating_duration_since(Instant::now())
|
||||
.as_millis() as i32;
|
||||
// SAFETY: pollfd points to one initialized descriptor for this call.
|
||||
let result = unsafe { libc::poll(&mut pollfd, 1, timeout) };
|
||||
if result > 0 && pollfd.revents & libc::POLLIN != 0 {
|
||||
return;
|
||||
}
|
||||
if result < 0
|
||||
&& std::io::Error::last_os_error().kind() == std::io::ErrorKind::Interrupted
|
||||
{
|
||||
continue;
|
||||
}
|
||||
break;
|
||||
}
|
||||
|
||||
// SAFETY: the pidfd names only our shell, even if it was already reaped.
|
||||
// A null siginfo pointer requests the usual kill(2) signal semantics.
|
||||
let result = unsafe {
|
||||
libc::syscall(
|
||||
libc::SYS_pidfd_send_signal,
|
||||
self.0.as_raw_fd(),
|
||||
libc::SIGKILL,
|
||||
std::ptr::null::<libc::siginfo_t>(),
|
||||
0,
|
||||
)
|
||||
};
|
||||
if result == -1 {
|
||||
let error = std::io::Error::last_os_error();
|
||||
if error.raw_os_error() != Some(libc::ESRCH) {
|
||||
log::warn!("Could not stop shell during shutdown: {error}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use alacritty_terminal::index::{Column, Line, Point};
|
||||
use alacritty_terminal::term::{TermMode, cell::Flags};
|
||||
use alacritty_terminal::vte::ansi::{Color, Processor, Rgb};
|
||||
|
||||
// Test-only timeout; production consumes this receiver asynchronously.
|
||||
fn receive_before(
|
||||
events: &async_channel::Receiver<Event>,
|
||||
deadline: Instant,
|
||||
) -> Result<Event, &'static str> {
|
||||
loop {
|
||||
match events.try_recv() {
|
||||
Ok(event) => return Ok(event),
|
||||
Err(async_channel::TryRecvError::Closed) => return Err("event channel closed"),
|
||||
Err(async_channel::TryRecvError::Empty) if Instant::now() >= deadline => {
|
||||
return Err("event receive timed out");
|
||||
}
|
||||
Err(async_channel::TryRecvError::Empty) => {
|
||||
thread::sleep(Duration::from_millis(1));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn output_wakes_a_waiting_ui_without_a_polling_timer() {
|
||||
use std::future::Future;
|
||||
use std::sync::atomic::AtomicUsize;
|
||||
use std::task::{Context, Poll, Wake, Waker};
|
||||
|
||||
struct WakeCounter(AtomicUsize);
|
||||
impl Wake for WakeCounter {
|
||||
fn wake(self: Arc<Self>) {
|
||||
self.0.fetch_add(1, Ordering::SeqCst);
|
||||
}
|
||||
}
|
||||
|
||||
let (tx, rx) = async_channel::unbounded();
|
||||
let proxy = EventProxy::new(tx);
|
||||
let counter = Arc::new(WakeCounter(AtomicUsize::new(0)));
|
||||
let waker = Waker::from(counter.clone());
|
||||
let mut cx = Context::from_waker(&waker);
|
||||
let mut receive = std::pin::pin!(rx.recv());
|
||||
assert!(matches!(receive.as_mut().poll(&mut cx), Poll::Pending));
|
||||
proxy.send_event(Event::Wakeup);
|
||||
assert_eq!(counter.0.load(Ordering::SeqCst), 1);
|
||||
assert!(matches!(
|
||||
receive.as_mut().poll(&mut cx),
|
||||
Poll::Ready(Ok(Event::Wakeup))
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn wakeups_are_coalesced_without_losing_protocol_events() {
|
||||
let (tx, rx) = async_channel::unbounded();
|
||||
let proxy = EventProxy::new(tx);
|
||||
for _ in 0..10_000 {
|
||||
proxy.send_event(Event::Wakeup);
|
||||
}
|
||||
proxy.send_event(Event::PtyWrite("response".into()));
|
||||
proxy.send_event(Event::Title("title".into()));
|
||||
assert!(matches!(rx.try_recv(), Ok(Event::Wakeup)));
|
||||
assert!(matches!(rx.try_recv(), Ok(Event::PtyWrite(value)) if value == "response"));
|
||||
assert!(matches!(rx.try_recv(), Ok(Event::Title(value)) if value == "title"));
|
||||
assert!(matches!(
|
||||
rx.try_recv(),
|
||||
Err(async_channel::TryRecvError::Empty)
|
||||
));
|
||||
proxy.wakeup_pending.store(false, Ordering::Release);
|
||||
proxy.send_event(Event::Wakeup);
|
||||
assert!(matches!(rx.try_recv(), Ok(Event::Wakeup)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[cfg(target_os = "linux")]
|
||||
fn closing_session_reaps_shell_even_when_sighup_is_ignored() {
|
||||
use std::os::fd::AsRawFd;
|
||||
|
||||
for ignore_hup in [false, true] {
|
||||
let script = format!(
|
||||
"{}printf '\\033]0;ready\\007'; read value",
|
||||
if ignore_hup { "trap '' HUP; " } else { "" }
|
||||
);
|
||||
let (session, events) =
|
||||
Session::with_shell(Shell::new("/bin/sh".into(), vec!["-c".into(), script]))
|
||||
.expect("start shell for shutdown test");
|
||||
let process = session.process.0.try_clone().unwrap();
|
||||
let deadline = Instant::now() + Duration::from_secs(5);
|
||||
loop {
|
||||
match receive_before(&events, deadline) {
|
||||
Ok(Event::Title(title)) if title == "ready" => break,
|
||||
Ok(_) => (),
|
||||
Err(error) => panic!("Shell did not reach read: {error}"),
|
||||
}
|
||||
}
|
||||
|
||||
let started = Instant::now();
|
||||
drop(session);
|
||||
assert!(
|
||||
started.elapsed() < Duration::from_secs(2),
|
||||
"shutdown was not bounded"
|
||||
);
|
||||
let mut status = std::mem::MaybeUninit::<libc::siginfo_t>::zeroed();
|
||||
// SAFETY: the cloned pidfd and writable siginfo are valid. WNOHANG
|
||||
// avoids waiting if the process was accidentally left running.
|
||||
let result = unsafe {
|
||||
libc::waitid(
|
||||
libc::P_PIDFD,
|
||||
process.as_raw_fd() as libc::id_t,
|
||||
status.as_mut_ptr(),
|
||||
libc::WEXITED | libc::WNOHANG,
|
||||
)
|
||||
};
|
||||
assert_eq!(result, -1, "the shell was left running or unreaped");
|
||||
assert_eq!(
|
||||
std::io::Error::last_os_error().raw_os_error(),
|
||||
Some(libc::ECHILD)
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ansi_state_survives_alternate_screen_and_resize() {
|
||||
let (tx, _rx) = async_channel::unbounded();
|
||||
let mut term = Term::new(
|
||||
Config::default(),
|
||||
&GridSize(WindowSize {
|
||||
num_cols: 80,
|
||||
num_lines: 24,
|
||||
cell_width: 8,
|
||||
cell_height: 16,
|
||||
}),
|
||||
EventProxy::new(tx),
|
||||
);
|
||||
let mut parser: Processor = Processor::new();
|
||||
parser.advance(&mut term, "\x1b[38;2;12;34;56mA界\x1b[0m".as_bytes());
|
||||
let first = &term.grid()[Point::new(Line(0), Column(0))];
|
||||
assert_eq!(first.c, 'A');
|
||||
assert_eq!(
|
||||
first.fg,
|
||||
Color::Spec(Rgb {
|
||||
r: 12,
|
||||
g: 34,
|
||||
b: 56
|
||||
})
|
||||
);
|
||||
assert!(
|
||||
term.grid()[Point::new(Line(0), Column(1))]
|
||||
.flags
|
||||
.contains(Flags::WIDE_CHAR)
|
||||
);
|
||||
assert!(
|
||||
term.grid()[Point::new(Line(0), Column(2))]
|
||||
.flags
|
||||
.contains(Flags::WIDE_CHAR_SPACER)
|
||||
);
|
||||
|
||||
parser.advance(&mut term, b"\x1b[?1049h\x1b[Halternate");
|
||||
assert!(term.mode().contains(TermMode::ALT_SCREEN));
|
||||
parser.advance(&mut term, b"\x1b[?1049l");
|
||||
assert!(!term.mode().contains(TermMode::ALT_SCREEN));
|
||||
assert_eq!(term.grid()[Point::new(Line(0), Column(0))].c, 'A');
|
||||
term.resize(GridSize(WindowSize {
|
||||
num_cols: 40,
|
||||
num_lines: 10,
|
||||
cell_width: 8,
|
||||
cell_height: 16,
|
||||
}));
|
||||
assert_eq!((term.columns(), term.screen_lines()), (40, 10));
|
||||
assert_eq!(term.grid()[Point::new(Line(0), Column(0))].c, 'A');
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn real_pty_transports_input_resize_environment_and_exit() {
|
||||
// Reading first lets the test resize before the child examines its TTY.
|
||||
let script = "read value; printf '\\033[2J\\033[H%s %s %s ' \"$value\" \"$TERM\" \"$COLORTERM\"; stty size";
|
||||
let (mut session, events) = Session::with_shell(Shell::new(
|
||||
"/bin/sh".into(),
|
||||
vec!["-c".into(), script.into()],
|
||||
))
|
||||
.expect("start real PTY");
|
||||
session.resize(100, 30, 9, 18);
|
||||
session.write(b"PTY_OK\n".to_vec());
|
||||
|
||||
let deadline = Instant::now() + Duration::from_secs(5);
|
||||
let mut child_exited = false;
|
||||
loop {
|
||||
let event =
|
||||
receive_before(&events, deadline).expect("PTY did not finish within five seconds");
|
||||
match event {
|
||||
Event::ChildExit(status) => {
|
||||
assert!(status.success());
|
||||
child_exited = true;
|
||||
}
|
||||
Event::Exit => break,
|
||||
_ => (),
|
||||
}
|
||||
}
|
||||
assert!(child_exited);
|
||||
let term = session.term.lock();
|
||||
let first_line: String = (0..term.columns())
|
||||
.map(|column| term.grid()[Point::new(Line(0), Column(column))].c)
|
||||
.collect();
|
||||
assert!(
|
||||
first_line.contains("PTY_OK xterm-256color truecolor 30 100"),
|
||||
"{first_line:?}"
|
||||
);
|
||||
assert_eq!((term.columns(), term.screen_lines()), (100, 30));
|
||||
}
|
||||
}
|
||||
+473
@@ -0,0 +1,473 @@
|
||||
//! A single terminal pane. Session owns the PTY; this view only handles presentation/input.
|
||||
use async_channel::Receiver;
|
||||
use std::ops::Range;
|
||||
|
||||
use alacritty_terminal::{
|
||||
event::Event,
|
||||
grid::{Dimensions, Scroll},
|
||||
index::{Column, Line, Point as GridPoint, Side},
|
||||
selection::{Selection, SelectionType},
|
||||
term::TermMode,
|
||||
vte::ansi::{Color, CursorShape, NamedColor},
|
||||
};
|
||||
use gpui::{prelude::*, *};
|
||||
|
||||
use crate::{
|
||||
colors, input,
|
||||
render::{FONT_SIZE, LINE_HEIGHT, RenderCell, Renderer},
|
||||
session::Session,
|
||||
};
|
||||
|
||||
const PADDING: f32 = 8.;
|
||||
|
||||
pub struct TerminalView {
|
||||
session: Session,
|
||||
focus: FocusHandle,
|
||||
font: Font,
|
||||
bounds: Bounds<Pixels>,
|
||||
cell_width: f32,
|
||||
selecting: bool,
|
||||
scroll_remainder: f32,
|
||||
preedit: String,
|
||||
cursor_bounds: Bounds<Pixels>,
|
||||
renderer: Renderer,
|
||||
_events: Task<()>,
|
||||
}
|
||||
|
||||
impl TerminalView {
|
||||
pub fn new(
|
||||
session: Session,
|
||||
events: Receiver<Event>,
|
||||
window: &mut Window,
|
||||
cx: &mut Context<Self>,
|
||||
) -> Self {
|
||||
let terminal_font = crate::fonts::terminal_font(window.text_system());
|
||||
let font_id = window.text_system().resolve_font(&terminal_font);
|
||||
let cell_width = window
|
||||
.text_system()
|
||||
.advance(font_id, px(FONT_SIZE), 'M')
|
||||
.map(|advance| f32::from(advance.width))
|
||||
.unwrap_or(9.)
|
||||
.max(1.);
|
||||
let focus = cx.focus_handle();
|
||||
window.focus(&focus);
|
||||
// Wake on PTY output rather than adding a polling interval to input latency.
|
||||
let task = cx.spawn_in(window, async move |view, cx| {
|
||||
while let Ok(first) = events.recv().await {
|
||||
let pending: Vec<_> = std::iter::once(first)
|
||||
.chain(std::iter::from_fn(|| events.try_recv().ok()))
|
||||
.take(4096)
|
||||
.collect();
|
||||
if cx
|
||||
.update(|window, cx| {
|
||||
view.update(cx, |view, cx| {
|
||||
for event in pending {
|
||||
match event {
|
||||
Event::Title(title) => window.set_window_title(&title),
|
||||
Event::ResetTitle => window.set_window_title("Terminal"),
|
||||
Event::PtyWrite(text) => view.session.write(text.into_bytes()),
|
||||
Event::TextAreaSizeRequest(format) => {
|
||||
view.session.write(format(view.session.size()).into_bytes())
|
||||
}
|
||||
Event::ColorRequest(index, format) => {
|
||||
let color = (index
|
||||
< alacritty_terminal::term::color::COUNT)
|
||||
.then(|| view.session.term.lock().colors()[index])
|
||||
.flatten();
|
||||
view.session.write(
|
||||
format(color.unwrap_or_else(|| colors::palette(index)))
|
||||
.into_bytes(),
|
||||
);
|
||||
}
|
||||
Event::Exit => window.remove_window(),
|
||||
Event::Wakeup => view.session.acknowledge_wakeup(),
|
||||
// OSC 52 is deliberately not wired to the desktop clipboard.
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
cx.notify();
|
||||
})
|
||||
})
|
||||
.is_err()
|
||||
{
|
||||
break;
|
||||
}
|
||||
// Give the compositor a turn even when a child continuously writes.
|
||||
futures_lite::future::yield_now().await;
|
||||
}
|
||||
});
|
||||
Self {
|
||||
session,
|
||||
focus,
|
||||
font: terminal_font,
|
||||
bounds: Bounds::default(),
|
||||
cell_width,
|
||||
selecting: false,
|
||||
scroll_remainder: 0.,
|
||||
preedit: String::new(),
|
||||
cursor_bounds: Bounds::default(),
|
||||
renderer: Renderer::default(),
|
||||
_events: task,
|
||||
}
|
||||
}
|
||||
|
||||
fn send(&mut self, bytes: Vec<u8>, cx: &mut Context<Self>) {
|
||||
if bytes.is_empty() {
|
||||
return;
|
||||
}
|
||||
let mut changed = !self.preedit.is_empty();
|
||||
self.preedit.clear();
|
||||
{
|
||||
let mut term = self.session.term.lock();
|
||||
changed |= term.grid().display_offset() != 0 || term.selection.is_some();
|
||||
term.scroll_display(Scroll::Bottom);
|
||||
term.selection = None;
|
||||
}
|
||||
self.session.write(bytes);
|
||||
// Echo arrives through the PTY. Do not draw an unchanged frame first.
|
||||
if changed {
|
||||
cx.notify();
|
||||
}
|
||||
}
|
||||
|
||||
fn key_down(&mut self, event: &KeyDownEvent, _: &mut Window, cx: &mut Context<Self>) {
|
||||
let key = &event.keystroke;
|
||||
if key.modifiers.control
|
||||
&& key.modifiers.shift
|
||||
&& !key.modifiers.alt
|
||||
&& !key.modifiers.platform
|
||||
{
|
||||
match key.key.as_str() {
|
||||
"c" | "C" => {
|
||||
if let Some(text) = self.session.term.lock().selection_to_string() {
|
||||
cx.write_to_clipboard(ClipboardItem::new_string(text));
|
||||
}
|
||||
cx.stop_propagation();
|
||||
return;
|
||||
}
|
||||
"v" | "V" => {
|
||||
if let Some(text) = cx.read_from_clipboard().and_then(|item| item.text()) {
|
||||
let bracketed = self
|
||||
.session
|
||||
.term
|
||||
.lock()
|
||||
.mode()
|
||||
.contains(TermMode::BRACKETED_PASTE);
|
||||
let text = input::paste_text(&text, bracketed);
|
||||
self.send(text, cx);
|
||||
}
|
||||
cx.stop_propagation();
|
||||
return;
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
if key.modifiers.shift
|
||||
&& !key.modifiers.control
|
||||
&& !key.modifiers.alt
|
||||
&& !key.modifiers.platform
|
||||
&& !self
|
||||
.session
|
||||
.term
|
||||
.lock()
|
||||
.mode()
|
||||
.contains(TermMode::ALT_SCREEN)
|
||||
{
|
||||
let scroll = match key.key.as_str() {
|
||||
"pageup" => Some(Scroll::PageUp),
|
||||
"pagedown" => Some(Scroll::PageDown),
|
||||
"home" => Some(Scroll::Top),
|
||||
"end" => Some(Scroll::Bottom),
|
||||
_ => None,
|
||||
};
|
||||
if let Some(scroll) = scroll {
|
||||
self.session.term.lock().scroll_display(scroll);
|
||||
cx.notify();
|
||||
cx.stop_propagation();
|
||||
return;
|
||||
}
|
||||
}
|
||||
let mode = *self.session.term.lock().mode();
|
||||
if let Some(bytes) = input::encode_key(key, mode) {
|
||||
self.send(bytes, cx);
|
||||
cx.stop_propagation();
|
||||
}
|
||||
}
|
||||
|
||||
fn grid_point(&self, position: Point<Pixels>) -> (GridPoint, Side) {
|
||||
let term = self.session.term.lock();
|
||||
let x = (f32::from(position.x - self.bounds.left()) - PADDING).max(0.) / self.cell_width;
|
||||
let y =
|
||||
((f32::from(position.y - self.bounds.top()) - PADDING).max(0.) / LINE_HEIGHT) as usize;
|
||||
let column = (x as usize).min(term.columns() - 1);
|
||||
let line = y.min(term.screen_lines() - 1) as i32 - term.grid().display_offset() as i32;
|
||||
(
|
||||
GridPoint::new(Line(line), Column(column)),
|
||||
if x.fract() < 0.5 {
|
||||
Side::Left
|
||||
} else {
|
||||
Side::Right
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
fn mouse_down(&mut self, event: &MouseDownEvent, window: &mut Window, cx: &mut Context<Self>) {
|
||||
window.focus(&self.focus);
|
||||
let (point, side) = self.grid_point(event.position);
|
||||
let ty = match event.click_count {
|
||||
2 => SelectionType::Semantic,
|
||||
3.. => SelectionType::Lines,
|
||||
_ => SelectionType::Simple,
|
||||
};
|
||||
self.session.term.lock().selection = Some(Selection::new(ty, point, side));
|
||||
self.selecting = true;
|
||||
cx.notify();
|
||||
}
|
||||
|
||||
fn mouse_move(&mut self, event: &MouseMoveEvent, _: &mut Window, cx: &mut Context<Self>) {
|
||||
if self.selecting && event.dragging() {
|
||||
let (point, side) = self.grid_point(event.position);
|
||||
if let Some(selection) = &mut self.session.term.lock().selection {
|
||||
selection.update(point, side);
|
||||
}
|
||||
cx.notify();
|
||||
}
|
||||
}
|
||||
|
||||
fn scroll(&mut self, event: &ScrollWheelEvent, _: &mut Window, cx: &mut Context<Self>) {
|
||||
self.scroll_remainder += match event.delta {
|
||||
ScrollDelta::Lines(delta) => delta.y * 3.,
|
||||
ScrollDelta::Pixels(delta) => f32::from(delta.y) / LINE_HEIGHT,
|
||||
};
|
||||
let lines = self.scroll_remainder.trunc() as i32;
|
||||
self.scroll_remainder -= lines as f32;
|
||||
if lines != 0 {
|
||||
let mode = *self.session.term.lock().mode();
|
||||
if mode.contains(TermMode::ALT_SCREEN | TermMode::ALTERNATE_SCROLL)
|
||||
&& !event.modifiers.shift
|
||||
{
|
||||
let arrow = match (mode.contains(TermMode::APP_CURSOR), lines > 0) {
|
||||
(true, true) => b"\x1bOA",
|
||||
(true, false) => b"\x1bOB",
|
||||
(false, true) => b"\x1b[A",
|
||||
(false, false) => b"\x1b[B",
|
||||
};
|
||||
self.send(arrow.repeat(lines.unsigned_abs().min(100) as usize), cx);
|
||||
} else {
|
||||
self.session
|
||||
.term
|
||||
.lock()
|
||||
.scroll_display(Scroll::Delta(lines));
|
||||
cx.notify();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn prepare(&mut self, bounds: Bounds<Pixels>, window: &mut Window) {
|
||||
let prepare_started = std::time::Instant::now();
|
||||
self.bounds = bounds;
|
||||
let columns = ((f32::from(bounds.size.width) - 2. * PADDING) / self.cell_width)
|
||||
.floor()
|
||||
.max(2.) as usize;
|
||||
let lines = ((f32::from(bounds.size.height) - 2. * PADDING) / LINE_HEIGHT)
|
||||
.floor()
|
||||
.max(1.) as usize;
|
||||
self.session.resize(
|
||||
columns,
|
||||
lines,
|
||||
self.cell_width.round() as u16,
|
||||
LINE_HEIGHT as u16,
|
||||
);
|
||||
let term = self.session.term.lock();
|
||||
let content = term.renderable_content();
|
||||
let offset = content.display_offset as i32;
|
||||
let cursor = content.cursor;
|
||||
self.cursor_bounds = Bounds::new(
|
||||
bounds.origin
|
||||
+ point(
|
||||
px(PADDING + cursor.point.column.0 as f32 * self.cell_width),
|
||||
px(PADDING + (cursor.point.line.0 + offset) as f32 * LINE_HEIGHT),
|
||||
),
|
||||
size(px(self.cell_width), px(LINE_HEIGHT)),
|
||||
);
|
||||
let mut rows = vec![Vec::with_capacity(columns); lines];
|
||||
for indexed in content.display_iter {
|
||||
let (mut foreground, mut background) =
|
||||
colors::cell_colors(indexed.cell, content.colors);
|
||||
if content
|
||||
.selection
|
||||
.is_some_and(|selection| selection.contains(indexed.point))
|
||||
{
|
||||
foreground = rgb(0xffffff).into();
|
||||
background = rgb(0x3c536d).into();
|
||||
}
|
||||
let shape = if indexed.point == cursor.point {
|
||||
cursor.shape
|
||||
} else {
|
||||
CursorShape::Hidden
|
||||
};
|
||||
if shape == CursorShape::Block {
|
||||
background = colors::resolve(Color::Named(NamedColor::Cursor), content.colors);
|
||||
foreground = colors::resolve(Color::Named(NamedColor::Background), content.colors);
|
||||
}
|
||||
let row = (indexed.point.line.0 + offset) as usize;
|
||||
rows[row].push(RenderCell {
|
||||
cell: indexed.cell.clone(),
|
||||
foreground,
|
||||
background,
|
||||
cursor: shape,
|
||||
});
|
||||
}
|
||||
drop(term);
|
||||
self.renderer
|
||||
.prepare(rows, &self.font, self.cell_width, window);
|
||||
log::debug!(target: "terminal::timing", "prepare_us={} cells={}", prepare_started.elapsed().as_micros(), columns * lines);
|
||||
}
|
||||
}
|
||||
|
||||
impl Render for TerminalView {
|
||||
fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
|
||||
let prepare_view = cx.entity();
|
||||
let paint_view = cx.entity();
|
||||
div()
|
||||
.size_full()
|
||||
.bg(rgb(colors::BACKGROUND))
|
||||
.overflow_hidden()
|
||||
.track_focus(&self.focus)
|
||||
.cursor(CursorStyle::IBeam)
|
||||
.on_key_down(cx.listener(Self::key_down))
|
||||
.on_mouse_down(MouseButton::Left, cx.listener(Self::mouse_down))
|
||||
.on_mouse_move(cx.listener(Self::mouse_move))
|
||||
.on_mouse_up(
|
||||
MouseButton::Left,
|
||||
cx.listener(|view, _, _, _| view.selecting = false),
|
||||
)
|
||||
.on_mouse_up_out(
|
||||
MouseButton::Left,
|
||||
cx.listener(|view, _, _, _| view.selecting = false),
|
||||
)
|
||||
.on_scroll_wheel(cx.listener(Self::scroll))
|
||||
.child(
|
||||
canvas(
|
||||
move |bounds, window, cx| {
|
||||
prepare_view.update(cx, |view, _| view.prepare(bounds, window))
|
||||
},
|
||||
move |bounds, (), window, cx| {
|
||||
let paint_started = std::time::Instant::now();
|
||||
let view = paint_view.read(cx);
|
||||
let focus = view.focus.clone();
|
||||
let base_font = view.font.clone();
|
||||
let preedit = view.preedit.clone();
|
||||
let cursor_bounds = view.cursor_bounds;
|
||||
window.handle_input(
|
||||
&focus,
|
||||
ElementInputHandler::new(bounds, paint_view.clone()),
|
||||
cx,
|
||||
);
|
||||
window.with_content_mask(Some(ContentMask { bounds }), |window| {
|
||||
let origin = bounds.origin + point(px(PADDING), px(PADDING));
|
||||
paint_view.update(cx, |view, cx| view.renderer.paint(origin, window, cx));
|
||||
if !preedit.is_empty() {
|
||||
let run = TextRun {
|
||||
len: preedit.len(),
|
||||
font: base_font.clone(),
|
||||
color: rgb(colors::FOREGROUND).into(),
|
||||
background_color: Some(rgb(colors::BACKGROUND).into()),
|
||||
underline: Some(UnderlineStyle {
|
||||
thickness: px(1.),
|
||||
color: None,
|
||||
wavy: false,
|
||||
}),
|
||||
strikethrough: None,
|
||||
};
|
||||
let shaped = window.text_system().shape_line(
|
||||
preedit.into(),
|
||||
px(FONT_SIZE),
|
||||
&[run],
|
||||
None,
|
||||
);
|
||||
let _ =
|
||||
shaped.paint(cursor_bounds.origin, px(LINE_HEIGHT), window, cx);
|
||||
}
|
||||
});
|
||||
log::debug!(target: "terminal::timing", "paint_us={}", paint_started.elapsed().as_micros());
|
||||
},
|
||||
)
|
||||
.size_full(),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
impl EntityInputHandler for TerminalView {
|
||||
fn text_for_range(
|
||||
&mut self,
|
||||
_: Range<usize>,
|
||||
_: &mut Option<Range<usize>>,
|
||||
_: &mut Window,
|
||||
_: &mut Context<Self>,
|
||||
) -> Option<String> {
|
||||
None
|
||||
}
|
||||
fn selected_text_range(
|
||||
&mut self,
|
||||
_: bool,
|
||||
_: &mut Window,
|
||||
_: &mut Context<Self>,
|
||||
) -> Option<UTF16Selection> {
|
||||
Some(UTF16Selection {
|
||||
range: 0..0,
|
||||
reversed: false,
|
||||
})
|
||||
}
|
||||
fn marked_text_range(&self, _: &mut Window, _: &mut Context<Self>) -> Option<Range<usize>> {
|
||||
(!self.preedit.is_empty()).then(|| 0..self.preedit.encode_utf16().count())
|
||||
}
|
||||
fn unmark_text(&mut self, _: &mut Window, cx: &mut Context<Self>) {
|
||||
self.preedit.clear();
|
||||
cx.notify();
|
||||
}
|
||||
fn replace_text_in_range(
|
||||
&mut self,
|
||||
_: Option<Range<usize>>,
|
||||
text: &str,
|
||||
_: &mut Window,
|
||||
cx: &mut Context<Self>,
|
||||
) {
|
||||
if text.is_empty() {
|
||||
if !self.preedit.is_empty() {
|
||||
self.preedit.clear();
|
||||
cx.notify();
|
||||
}
|
||||
} else {
|
||||
self.send(text.as_bytes().to_vec(), cx);
|
||||
}
|
||||
}
|
||||
fn replace_and_mark_text_in_range(
|
||||
&mut self,
|
||||
_: Option<Range<usize>>,
|
||||
text: &str,
|
||||
_: Option<Range<usize>>,
|
||||
_: &mut Window,
|
||||
cx: &mut Context<Self>,
|
||||
) {
|
||||
self.preedit = text.to_owned();
|
||||
cx.notify();
|
||||
}
|
||||
fn bounds_for_range(
|
||||
&mut self,
|
||||
_: Range<usize>,
|
||||
_: Bounds<Pixels>,
|
||||
_: &mut Window,
|
||||
_: &mut Context<Self>,
|
||||
) -> Option<Bounds<Pixels>> {
|
||||
Some(self.cursor_bounds)
|
||||
}
|
||||
fn character_index_for_point(
|
||||
&mut self,
|
||||
_: Point<Pixels>,
|
||||
_: &mut Window,
|
||||
_: &mut Context<Self>,
|
||||
) -> Option<usize> {
|
||||
None
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user