Initial GPUI Wayland terminal with Alacritty core

This commit is contained in:
2026-11-17 00:12:24 -08:00
commit de1d5776b6
26 changed files with 10792 additions and 0 deletions
+1
View File
@@ -0,0 +1 @@
/target/
Generated
+7097
View File
File diff suppressed because it is too large Load Diff
+43
View File
@@ -0,0 +1,43 @@
[package]
name = "terminal"
version = "0.1.0"
edition = "2024"
publish = false
[dependencies]
alacritty_terminal = "=0.26.0"
anyhow = "1"
async-channel = "2"
gpui = { version = "=0.2.2", default-features = false, features = ["wayland"] }
log = "0.4"
env_logger = "0.11"
futures-lite = "2"
[target.'cfg(target_os = "linux")'.dependencies]
libc = "0.2"
[patch.crates-io]
# GPUI's zed-async-tar uses xattr 0.2.3, whose Linux ENOATTR alias was removed
# from libc. Keep the compatibility fix local; see vendor/xattr/PATCH.md.
xattr = { path = "vendor/xattr" }
[profile.dev]
debug = 1
opt-level = 1
# Text shaping and GPUI scene construction are latency-sensitive even in a
# development build. Keep our debug info/assertions while optimizing these paths.
[profile.dev.package.gpui]
opt-level = 2
[profile.dev.package.cosmic-text]
opt-level = 2
[profile.dev.package.rustybuzz]
opt-level = 2
[profile.dev.package.swash]
opt-level = 2
[profile.release]
lto = "thin"
+149
View File
@@ -0,0 +1,149 @@
# Terminal
A small GPU-rendered terminal built with [GPUI 0.2.2](https://gpui.rs/) and
[alacritty_terminal 0.26.0](https://docs.rs/alacritty_terminal/0.26.0/).
The initial target is Linux desktop on Wayland. Alacritty provides the terminal
state machine, VTE parser, scrollback, PTY, and shell I/O; GPUI provides the window,
text rendering, and desktop input.
## Build and run
Use a recent stable Rust toolchain; development currently uses Rust 1.96. Launch
from Linux 5.3 or newer (pidfd-based shell cleanup), in a running Wayland desktop with `WAYLAND_DISPLAY` set and a working Vulkan
driver. This build enables GPUI's Wayland backend only.
Representative Fedora dependencies:
```sh
sudo dnf install gcc gcc-c++ make cmake pkgconf-pkg-config \
fontconfig-devel freetype-devel libxkbcommon-devel libxkbcommon-x11-devel \
libxcb-devel wayland-devel openssl-devel vulkan-loader mesa-vulkan-drivers \
dejavu-sans-mono-fonts
```
Representative Ubuntu dependencies:
```sh
sudo apt install build-essential cmake pkg-config \
libfontconfig1-dev libfreetype6-dev libxkbcommon-dev libxkbcommon-x11-dev \
libxcb1-dev libwayland-dev libssl-dev libvulkan1 mesa-vulkan-drivers \
fonts-dejavu-core
```
The package names follow the relevant portions of
[Zed's Linux dependency script](https://github.com/zed-industries/zed/blob/main/script/linux).
Your GPU may need its vendor's Vulkan driver instead of Mesa. GPUI 0.2.2 also
links the XKB X11 library even when only its Wayland window backend is enabled.
```sh
cargo run --locked
# Optimized build:
cargo run --locked --release
```
The window starts `$SHELL`, falling back to `/bin/sh`, and inherits the launch
directory. The child receives `TERM=xterm-256color` and `COLORTERM=truecolor`.
Run `exit` or close the window to end the session. To select another shell:
```sh
SHELL=/bin/bash cargo run --locked
```
For diagnostics, use `RUST_LOG=debug cargo run --locked`. If no window appears,
check that the process has access to your Wayland session and that Vulkan works
on that desktop. To inspect the renderer's CPU work without enabling logs from
all dependencies:
```sh
RUST_LOG=terminal::timing=debug cargo run --locked
```
Each frame logs `prepare_us` and `paint_us`, the time in microseconds spent in
our preparation and painting callbacks. These exclude GPU execution, compositor
scheduling, and presentation; they are not measurements of total input latency.
## Controls and behavior
| Input | Action |
| --- | --- |
| Drag with the left mouse button | Select text |
| Double-click / triple-click | Select a word / line |
| Ctrl+Shift+C | Copy the selection |
| Ctrl+Shift+V | Paste, respecting bracketed-paste mode |
| Mouse wheel / touchpad | Scroll terminal history |
| Shift+PageUp / Shift+PageDown | Scroll one page |
| Shift+Home / Shift+End | Jump to the oldest history / live screen |
Typing returns to the live screen. Ctrl+C, Ctrl+D, Alt combinations, arrows,
navigation keys, and function keys are sent to the terminal application.
In alternate-screen applications, Shift+navigation is passed through and the
wheel sends arrow keys when the application enables alternate scrolling.
The renderer supports ANSI and 256-color palettes, truecolor, bold/italic/dim,
underlining, reverse video, selection, wide characters and combining marks.
Window resizing updates both the terminal grid and PTY size. Alternate-screen
applications use Alacritty's terminal modes. Scrollback retains up to 10,000
lines by default. The view selects an installed font in this order: Hermit
(including its Hurmit Nerd Font variants), SF Mono, Noto Sans Mono, Iosevka,
then another fixed-pitch family. Font advances are checked to avoid choosing a
proportional fallback. Text is 15 logical pixels, with a 20-pixel line height and
8-pixel padding.
## Structure
| Module | Responsibility |
| --- | --- |
| `src/main.rs` | Application startup and window lifecycle |
| `src/session.rs` | One shell, PTY event loop, terminal grid, resize, and shutdown |
| `src/terminal.rs` | One terminal view: focus, selection, scrollback, clipboard, text input, and render coordination |
| `src/render.rs` | Cached terminal text layout and batched drawing |
| `src/input.rs` | Xterm-style key encoding and paste framing |
| `src/colors.rs` | Default palette, runtime color overrides, and cell color attributes |
| `src/fonts.rs` | Preferred installed fonts and verified fixed-pitch fallback |
The session does not depend on GPUI or window layout. Future tabs or split panes
can compose multiple views and sessions while reusing the parser and PTY code.
Persistent multiplexing would add a session owner outside the window lifecycle.
PTY events wake the UI through an asynchronous channel. Output notifications
are coalesced, and the UI yields between event batches so a busy child cannot
monopolize the UI task. There is no periodic redraw polling. Typing requests a
new frame when shell output arrives, or immediately if it changes selection,
scrollback position, or input-method composition.
The renderer retains shaped text for unchanged rows. It groups adjacent ASCII
cells into text runs, while keeping wide and combining-character cells aligned
to terminal columns. Blank margins are skipped, and matching backgrounds and
text decorations are merged into spans to reduce drawing work.
The build uses published crates and does not require a local Alacritty checkout.
`vendor/xattr` carries a small compatibility patch for GPUI's transitive
`zed-async-tar` dependency: Linux now uses `libc::ENODATA` in place of a removed
`ENOATTR` alias. See [the patch notes](vendor/xattr/PATCH.md). The dependency
versions are recorded in `Cargo.lock`.
## Development and scope
The development profile retains debug information and assertions, with level-1
optimization and level-2 optimization for GPUI and the font-shaping crates.
This keeps `cargo run` responsive during window resizing; the first build takes
longer than a fully unoptimized build. Unicode clusters use cached glyphs in one
shared paint layer, preserving cell positions without per-character layers.
```sh
cargo fmt --check
cargo check --locked
cargo test --locked
cargo clippy --locked --all-targets -- -D warnings
```
Tests cover key and paste encoding, palette behavior, terminal parsing and
resizing, and PTY lifecycle. They do not replace testing rendering and input
under a real compositor.
This first version has a single shell and window. It does not yet provide panes,
tabs, session persistence, configuration files, application mouse reporting,
the Kitty keyboard protocol, OSC 52 clipboard access, or clickable hyperlinks.
macOS is an intended next target and has not been validated. Font shaping,
input methods, and terminal application compatibility still need broader
desktop testing.
+197
View File
@@ -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
View File
@@ -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
View File
@@ -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
View File
@@ -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
View File
@@ -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
View File
@@ -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
View File
@@ -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
}
}
+34
View File
@@ -0,0 +1,34 @@
# THIS FILE IS AUTOMATICALLY GENERATED BY CARGO
#
# When uploading crates to the registry Cargo will automatically
# "normalize" Cargo.toml files for maximal compatibility
# with all versions of Cargo and also rewrite `path` dependencies
# to registry (e.g., crates.io) dependencies.
#
# If you are reading this file be aware that the original Cargo.toml
# will likely look very different (and much more reasonable).
# See Cargo.toml.orig for the original contents.
[package]
name = "xattr"
version = "0.2.3"
authors = ["Steven Allen <steven@stebalien.com>"]
description = "unix extended filesystem attributes"
documentation = "https://docs.rs/xattr"
keywords = [
"xattr",
"filesystem",
"unix",
]
license = "MIT/Apache-2.0"
repository = "https://github.com/Stebalien/xattr"
[dependencies.libc]
version = "0.2"
[dev-dependencies.tempfile]
version = "3"
[features]
default = ["unsupported"]
unsupported = []
+26
View File
@@ -0,0 +1,26 @@
[package]
name = "xattr"
version = "0.2.3"
authors = ["Steven Allen <steven@stebalien.com>"]
description = "unix extended filesystem attributes"
documentation = "https://docs.rs/xattr"
repository = "https://github.com/Stebalien/xattr"
keywords = ["xattr", "filesystem", "unix"]
license = "MIT/Apache-2.0"
[features]
default = ["unsupported"]
# Adds a dummy implementation for unsupported platforms. This is useful when
# developing platform-independent code that doesn't absolutely need xattr
# support.
#
# You can disable this feature if you want compilation to fail on unsupported
# platforms. This would make sense if you absolutely need xattr support.
unsupported = []
[dependencies]
libc = "0.2"
[dev-dependencies]
tempfile = "3"
+201
View File
@@ -0,0 +1,201 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
+25
View File
@@ -0,0 +1,25 @@
Copyright (c) 2015 Steven Allen
Permission is hereby granted, free of charge, to any
person obtaining a copy of this software and associated
documentation files (the "Software"), to deal in the
Software without restriction, including without
limitation the rights to use, copy, modify, merge,
publish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software
is furnished to do so, subject to the following
conditions:
The above copyright notice and this permission notice
shall be included in all copies or substantial portions
of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF
ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR
IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
+13
View File
@@ -0,0 +1,13 @@
# xattr 0.2.3 compatibility patch
This directory contains the source of the crates.io `xattr` 0.2.3 release
(MIT OR Apache-2.0). The upstream license files are included.
GPUI 0.2.2 depends on `zed-async-tar` 0.5.0-zed, which requires this old xattr
version. Recent `libc` releases removed the Linux/Android `ENOATTR` alias.
`src/sys/mod.rs` therefore uses `libc::ENODATA` on those targets, retaining
`libc::ENOATTR` on macOS and BSD. No other source behavior is changed.
Remove this Cargo patch when GPUI's dependency chain uses a maintained xattr
version. Vendoring this small fix avoids pinning libc and unrelated networking
dependencies to older releases.
+22
View File
@@ -0,0 +1,22 @@
xattr
=====
[![Build Status](https://travis-ci.org/Stebalien/xattr.svg?branch=master)](https://travis-ci.org/Stebalien/xattr)
[![Build Status](https://api.cirrus-ci.com/github/Stebalien/xattr.svg)](https://cirrus-ci.com/github/Stebalien/xattr)
A small library for setting, getting, and listing extended attributes.
Supported Platforms: Android, Linux, MacOS, FreeBSD, and NetBSD.
API Documentation: https://stebalien.github.com/xattr/xattr/
Unsupported Platforms
--------------------------
This library includes no-op support for unsupported platforms. That is, it will
build on *all* platforms but always fail on unsupported platforms.
1. You can turn this off by disabling the default `unsupported` feature. If you
do so, this library will fail to compile on unsupported platforms.
2. Alternatively, you can detect unsupported platforms at runtime by checking
the `xattr::SUPPORTED_PLATFORM` boolean.
+28
View File
@@ -0,0 +1,28 @@
use std::error::Error;
use std::fmt;
/// The error type returned on unsupported platforms.
///
/// On unsupported platforms, all operations will fail with an `io::Error` with
/// a kind `io::ErrorKind::Other` and an `UnsupportedPlatformError` error as the inner error.
/// While you *could* check the inner error, it's probably simpler just to check
/// `xattr::SUPPORTED_PLATFORM`.
///
/// This error mostly exists for pretty error messages.
#[derive(Copy, Clone, Debug)]
pub struct UnsupportedPlatformError;
impl Error for UnsupportedPlatformError {
fn description(&self) -> &str {
"unsupported platform"
}
}
impl fmt::Display for UnsupportedPlatformError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(
f,
"unsupported platform, please file a bug at `https://github.com/Stebalien/xattr'"
)
}
}
+116
View File
@@ -0,0 +1,116 @@
//! A pure-Rust library to manage extended attributes.
//!
//! It provides support for manipulating extended attributes
//! (`xattrs`) on modern Unix filesystems. See the `attr(5)`
//! manpage for more details.
//!
//! An extension trait [`FileExt`](::FileExt) is provided to directly work with
//! standard `File` objects and file descriptors.
//!
//! NOTE: In case of a symlink as path argument, all methods
//! in this library work on the symlink itself **without**
//! de-referencing it.
//!
//! ```rust
//! let mut xattrs = xattr::list("/").unwrap().peekable();
//!
//! if xattrs.peek().is_none() {
//! println!("no xattr set on root");
//! return;
//! }
//!
//! println!("Extended attributes:");
//! for attr in xattrs {
//! println!(" - {:?}", attr);
//! }
//! ```
extern crate libc;
mod error;
mod sys;
mod util;
use std::ffi::OsStr;
use std::fs::File;
use std::io;
use std::os::unix::io::AsRawFd;
use std::path::Path;
pub use error::UnsupportedPlatformError;
pub use sys::{XAttrs, SUPPORTED_PLATFORM};
/// Get an extended attribute for the specified file.
pub fn get<N, P>(path: P, name: N) -> io::Result<Option<Vec<u8>>>
where
P: AsRef<Path>,
N: AsRef<OsStr>,
{
util::extract_noattr(sys::get_path(path.as_ref(), name.as_ref()))
}
/// Set an extended attribute on the specified file.
pub fn set<N, P>(path: P, name: N, value: &[u8]) -> io::Result<()>
where
P: AsRef<Path>,
N: AsRef<OsStr>,
{
sys::set_path(path.as_ref(), name.as_ref(), value)
}
/// Remove an extended attribute from the specified file.
pub fn remove<N, P>(path: P, name: N) -> io::Result<()>
where
P: AsRef<Path>,
N: AsRef<OsStr>,
{
sys::remove_path(path.as_ref(), name.as_ref())
}
/// List extended attributes attached to the specified file.
///
/// Note: this may not list *all* attributes. Speficially, it definitely won't list any trusted
/// attributes unless you are root and it may not list system attributes.
pub fn list<P>(path: P) -> io::Result<XAttrs>
where
P: AsRef<Path>,
{
sys::list_path(path.as_ref())
}
/// Extension trait to manipulate extended attributes on `File`-like objects.
pub trait FileExt: AsRawFd {
/// Get an extended attribute for the specified file.
fn get_xattr<N>(&self, name: N) -> io::Result<Option<Vec<u8>>>
where
N: AsRef<OsStr>,
{
util::extract_noattr(sys::get_fd(self.as_raw_fd(), name.as_ref()))
}
/// Set an extended attribute on the specified file.
fn set_xattr<N>(&self, name: N, value: &[u8]) -> io::Result<()>
where
N: AsRef<OsStr>,
{
sys::set_fd(self.as_raw_fd(), name.as_ref(), value)
}
/// Remove an extended attribute from the specified file.
fn remove_xattr<N>(&self, name: N) -> io::Result<()>
where
N: AsRef<OsStr>,
{
sys::remove_fd(self.as_raw_fd(), name.as_ref())
}
/// List extended attributes attached to the specified file.
///
/// Note: this may not list *all* attributes. Speficially, it definitely won't list any trusted
/// attributes unless you are root and it may not list system attributes.
fn list_xattr(&self) -> io::Result<XAttrs> {
sys::list_fd(self.as_raw_fd())
}
}
impl FileExt for File {}
+367
View File
@@ -0,0 +1,367 @@
//! FreeBSD and NetBSD xattr support.
use std::ffi::{CString, OsStr, OsString};
use std::io;
use std::mem;
use std::os::unix::ffi::{OsStrExt, OsStringExt};
use std::os::unix::io::RawFd;
use std::path::Path;
use libc::{c_char, c_int, c_void, size_t, ssize_t, EPERM};
use util::{allocate_loop, path_to_c};
const EXTATTR_NAMESPACE_USER_STRING: &'static str = "user";
const EXTATTR_NAMESPACE_SYSTEM_STRING: &'static str = "system";
const EXTATTR_NAMESPACE_NAMES: [&'static str; 3] = [
"empty",
EXTATTR_NAMESPACE_USER_STRING,
EXTATTR_NAMESPACE_SYSTEM_STRING,
];
const EXTATTR_NAMESPACE_USER: c_int = 1;
const EXTATTR_NAMESPACE_SYSTEM: c_int = 2;
extern "C" {
pub fn extattr_list_fd(
fd: c_int,
attrnamespace: c_int,
data: *mut c_void,
nbytes: size_t,
) -> ssize_t;
pub fn extattr_get_fd(
fd: c_int,
attrnamespace: c_int,
attrname: *const c_char,
data: *mut c_void,
nbytes: size_t,
) -> ssize_t;
pub fn extattr_delete_fd(fd: c_int, attrname: c_int, attrname: *const c_char) -> c_int;
pub fn extattr_set_fd(
fd: c_int,
attrname: c_int,
attrname: *const c_char,
data: *const c_void,
nbytes: size_t,
) -> ssize_t;
pub fn extattr_list_link(
path: *const c_char,
attrnamespace: c_int,
data: *mut c_void,
nbytes: size_t,
) -> ssize_t;
pub fn extattr_get_link(
path: *const c_char,
attrnamespace: c_int,
attrname: *const c_char,
data: *mut c_void,
nbytes: size_t,
) -> ssize_t;
pub fn extattr_delete_link(
path: *const c_char,
attrname: c_int,
attrname: *const c_char,
) -> c_int;
pub fn extattr_set_link(
path: *const c_char,
attrname: c_int,
attrname: *const c_char,
data: *const c_void,
nbytes: size_t,
) -> ssize_t;
}
/// An iterator over a set of extended attributes names.
pub struct XAttrs {
user_attrs: Box<[u8]>,
system_attrs: Box<[u8]>,
offset: usize,
}
impl Clone for XAttrs {
fn clone(&self) -> Self {
XAttrs {
user_attrs: Vec::from(&*self.user_attrs).into_boxed_slice(),
system_attrs: Vec::from(&*self.system_attrs).into_boxed_slice(),
offset: self.offset,
}
}
fn clone_from(&mut self, other: &XAttrs) {
self.offset = other.offset;
let mut data = mem::replace(&mut self.user_attrs, Box::new([])).into_vec();
data.extend(other.user_attrs.iter().cloned());
self.user_attrs = data.into_boxed_slice();
data = mem::replace(&mut self.system_attrs, Box::new([])).into_vec();
data.extend(other.system_attrs.iter().cloned());
self.system_attrs = data.into_boxed_slice();
}
}
impl Iterator for XAttrs {
type Item = OsString;
fn next(&mut self) -> Option<OsString> {
if self.user_attrs.is_empty() && self.system_attrs.is_empty() {
return None;
}
if self.offset == self.user_attrs.len() + self.system_attrs.len() {
return None;
}
let data = if self.offset < self.system_attrs.len() {
&self.system_attrs[self.offset..]
} else {
&self.user_attrs[self.offset - self.system_attrs.len()..]
};
let siz = data[0] as usize;
self.offset += siz + 1;
if self.offset < self.system_attrs.len() {
Some(prefix_namespace(
OsStr::from_bytes(&data[1..siz + 1]),
EXTATTR_NAMESPACE_SYSTEM,
))
} else {
Some(prefix_namespace(
OsStr::from_bytes(&data[1..siz + 1]),
EXTATTR_NAMESPACE_USER,
))
}
}
fn size_hint(&self) -> (usize, Option<usize>) {
if self.user_attrs.len() + self.system_attrs.len() == self.offset {
(0, Some(0))
} else {
(1, None)
}
}
}
fn name_to_ns(name: &OsStr) -> io::Result<(c_int, CString)> {
let mut groups = name.as_bytes().splitn(2, |&b| b == b'.').take(2);
let nsname = match groups.next() {
Some(s) => s,
None => {
return Err(io::Error::new(
io::ErrorKind::InvalidInput,
"couldn't find namespace",
))
}
};
let propname = match groups.next() {
Some(s) => s,
None => {
return Err(io::Error::new(
io::ErrorKind::InvalidInput,
"couldn't find attribute",
))
}
};
let ns_int = match EXTATTR_NAMESPACE_NAMES
.iter()
.position(|&s| s.as_bytes() == nsname)
{
Some(i) => i,
None => {
return Err(io::Error::new(
io::ErrorKind::InvalidInput,
"no matching namespace",
))
}
};
Ok((ns_int as c_int, CString::new(propname)?))
}
fn prefix_namespace(attr: &OsStr, ns: c_int) -> OsString {
let nsname = EXTATTR_NAMESPACE_NAMES[ns as usize];
let mut v = Vec::with_capacity(nsname.as_bytes().len() + attr.as_bytes().len() + 1);
v.extend(nsname.as_bytes());
v.extend(".".as_bytes());
v.extend(attr.as_bytes());
OsString::from_vec(v)
}
pub fn get_fd(fd: RawFd, name: &OsStr) -> io::Result<Vec<u8>> {
let (ns, name) = name_to_ns(name)?;
unsafe {
allocate_loop(|buf, len| {
extattr_get_fd(fd, ns, name.as_ptr(), buf as *mut c_void, len as size_t)
})
}
}
pub fn set_fd(fd: RawFd, name: &OsStr, value: &[u8]) -> io::Result<()> {
let (ns, name) = name_to_ns(name)?;
let ret = unsafe {
extattr_set_fd(
fd,
ns,
name.as_ptr(),
value.as_ptr() as *const c_void,
value.len() as size_t,
)
};
if ret == -1 {
Err(io::Error::last_os_error())
} else {
Ok(())
}
}
pub fn remove_fd(fd: RawFd, name: &OsStr) -> io::Result<()> {
let (ns, name) = name_to_ns(name)?;
let ret = unsafe { extattr_delete_fd(fd, ns, name.as_ptr()) };
if ret != 0 {
Err(io::Error::last_os_error())
} else {
Ok(())
}
}
pub fn list_fd(fd: RawFd) -> io::Result<XAttrs> {
let sysvec = unsafe {
let res = allocate_loop(|buf, len| {
extattr_list_fd(
fd,
EXTATTR_NAMESPACE_SYSTEM,
buf as *mut c_void,
len as size_t,
)
});
// On FreeBSD, system attributes require root privileges to view. However,
// to mimic the behavior of listxattr in linux and osx, we need to query
// them anyway and return empty results if we get EPERM
match res {
Ok(v) => v,
Err(err) => {
if err.raw_os_error() == Some(EPERM) {
Vec::new()
} else {
return Err(err);
}
}
}
};
let uservec = unsafe {
let res = allocate_loop(|buf, len| {
extattr_list_fd(
fd,
EXTATTR_NAMESPACE_USER,
buf as *mut c_void,
len as size_t,
)
});
match res {
Ok(v) => v,
Err(err) => return Err(err),
}
};
Ok(XAttrs {
system_attrs: sysvec.into_boxed_slice(),
user_attrs: uservec.into_boxed_slice(),
offset: 0,
})
}
pub fn get_path(path: &Path, name: &OsStr) -> io::Result<Vec<u8>> {
let (ns, name) = name_to_ns(name)?;
let path = path_to_c(path)?;
unsafe {
allocate_loop(|buf, len| {
extattr_get_link(
path.as_ptr(),
ns,
name.as_ptr(),
buf as *mut c_void,
len as size_t,
)
})
}
}
pub fn set_path(path: &Path, name: &OsStr, value: &[u8]) -> io::Result<()> {
let (ns, name) = name_to_ns(name)?;
let path = path_to_c(path)?;
let ret = unsafe {
extattr_set_link(
path.as_ptr(),
ns,
name.as_ptr(),
value.as_ptr() as *const c_void,
value.len() as size_t,
)
};
if ret == -1 {
Err(io::Error::last_os_error())
} else {
Ok(())
}
}
pub fn remove_path(path: &Path, name: &OsStr) -> io::Result<()> {
let (ns, name) = name_to_ns(name)?;
let path = path_to_c(path)?;
let ret = unsafe { extattr_delete_link(path.as_ptr(), ns, name.as_ptr()) };
if ret != 0 {
Err(io::Error::last_os_error())
} else {
Ok(())
}
}
pub fn list_path(path: &Path) -> io::Result<XAttrs> {
let path = path_to_c(path)?;
let sysvec = unsafe {
let res = allocate_loop(|buf, len| {
extattr_list_link(
path.as_ptr(),
EXTATTR_NAMESPACE_SYSTEM,
buf as *mut c_void,
len as size_t,
)
});
// On FreeBSD, system attributes require root privileges to view. However,
// to mimic the behavior of listxattr in linux and osx, we need to query
// them anyway and return empty results if we get EPERM
match res {
Ok(v) => v,
Err(err) => {
if err.raw_os_error() == Some(EPERM) {
Vec::new()
} else {
return Err(err);
}
}
}
};
let uservec = unsafe {
let res = allocate_loop(|buf, len| {
extattr_list_link(
path.as_ptr(),
EXTATTR_NAMESPACE_USER,
buf as *mut c_void,
len as size_t,
)
});
match res {
Ok(v) => v,
Err(err) => return Err(err),
}
};
Ok(XAttrs {
system_attrs: sysvec.into_boxed_slice(),
user_attrs: uservec.into_boxed_slice(),
offset: 0,
})
}
+52
View File
@@ -0,0 +1,52 @@
use libc::{c_char, c_int, c_void, size_t, ssize_t};
extern "C" {
pub fn flistxattr(fd: c_int, buf: *mut c_char, size: size_t) -> ssize_t;
pub fn fgetxattr(fd: c_int, name: *const c_char, value: *mut c_void, size: size_t) -> ssize_t;
pub fn fremovexattr(fd: c_int, name: *const c_char) -> c_int;
pub fn llistxattr(path: *const c_char, buf: *mut c_char, size: size_t) -> ssize_t;
pub fn lgetxattr(
path: *const c_char,
name: *const c_char,
value: *mut c_void,
size: size_t,
) -> ssize_t;
pub fn lremovexattr(path: *const c_char, name: *const c_char) -> c_int;
}
pub unsafe fn fsetxattr(
fd: c_int,
name: *const c_char,
value: *const c_void,
size: size_t,
) -> ssize_t {
extern "C" {
fn fsetxattr(
fd: c_int,
name: *const c_char,
value: *const c_void,
size: size_t,
flags: c_int,
) -> ssize_t;
}
fsetxattr(fd, name, value, size, 0)
}
pub unsafe fn lsetxattr(
path: *const c_char,
name: *const c_char,
value: *const c_void,
size: size_t,
) -> ssize_t {
extern "C" {
fn lsetxattr(
path: *const c_char,
name: *const c_char,
value: *const c_void,
size: size_t,
flags: c_int,
) -> ssize_t;
}
lsetxattr(path, name, value, size, 0)
}
+120
View File
@@ -0,0 +1,120 @@
use libc::{c_char, c_int, c_void, size_t, ssize_t, uint32_t};
const XATTR_NOFOLLOW: c_int = 0x0001;
#[inline(always)]
pub unsafe fn fremovexattr(fd: c_int, name: *const c_char) -> c_int {
extern "C" {
fn fremovexattr(fd: c_int, name: *const c_char, options: c_int) -> c_int;
}
fremovexattr(fd, name, 0)
}
#[inline(always)]
pub unsafe fn fsetxattr(
fd: c_int,
name: *const c_char,
value: *const c_void,
size: size_t,
) -> ssize_t {
extern "C" {
fn fsetxattr(
fd: c_int,
name: *const c_char,
value: *const c_void,
size: size_t,
position: uint32_t,
options: c_int,
) -> ssize_t;
}
fsetxattr(fd, name, value, size, 0, 0)
}
#[inline(always)]
pub unsafe fn fgetxattr(
fd: c_int,
name: *const c_char,
value: *mut c_void,
size: size_t,
) -> ssize_t {
extern "C" {
fn fgetxattr(
fd: c_int,
name: *const c_char,
value: *mut c_void,
size: size_t,
position: uint32_t,
options: c_int,
) -> ssize_t;
}
fgetxattr(fd, name, value, size, 0, 0)
}
#[inline(always)]
pub unsafe fn flistxattr(fd: c_int, buf: *mut c_char, size: size_t) -> ssize_t {
extern "C" {
fn flistxattr(fd: c_int, buf: *mut c_char, size: size_t, options: c_int) -> ssize_t;
}
flistxattr(fd, buf, size, 0)
}
#[inline(always)]
pub unsafe fn lremovexattr(path: *const c_char, name: *const c_char) -> c_int {
extern "C" {
fn removexattr(path: *const c_char, name: *const c_char, options: c_int) -> c_int;
}
removexattr(path, name, XATTR_NOFOLLOW)
}
#[inline(always)]
pub unsafe fn lsetxattr(
path: *const c_char,
name: *const c_char,
value: *const c_void,
size: size_t,
) -> ssize_t {
extern "C" {
fn setxattr(
path: *const c_char,
name: *const c_char,
value: *const c_void,
size: size_t,
position: uint32_t,
options: c_int,
) -> ssize_t;
}
setxattr(path, name, value, size, 0, XATTR_NOFOLLOW)
}
#[inline(always)]
pub unsafe fn lgetxattr(
path: *const c_char,
name: *const c_char,
value: *mut c_void,
size: size_t,
) -> ssize_t {
extern "C" {
fn getxattr(
path: *const c_char,
name: *const c_char,
value: *mut c_void,
size: size_t,
position: uint32_t,
options: c_int,
) -> ssize_t;
}
getxattr(path, name, value, size, 0, XATTR_NOFOLLOW)
}
#[inline(always)]
pub unsafe fn llistxattr(path: *const c_char, buf: *mut c_char, size: size_t) -> ssize_t {
extern "C" {
fn listxattr(
path: *const c_char,
buf: *mut c_char,
size: size_t,
options: c_int,
) -> ssize_t;
}
listxattr(path, buf, size, XATTR_NOFOLLOW)
}
+168
View File
@@ -0,0 +1,168 @@
#[cfg(any(target_os = "linux", target_os = "android"))]
mod linux;
#[cfg(any(target_os = "linux", target_os = "android"))]
use self::linux::*;
#[cfg(target_os = "macos")]
mod macos;
#[cfg(target_os = "macos")]
use self::macos::*;
use std::ffi::{OsStr, OsString};
use std::io;
use std::mem;
use std::os::unix::ffi::OsStrExt;
use std::os::unix::io::RawFd;
use std::path::Path;
use libc::{c_char, c_void, size_t};
use util::{allocate_loop, name_to_c, path_to_c};
/// An iterator over a set of extended attributes names.
pub struct XAttrs {
data: Box<[u8]>,
offset: usize,
}
impl Clone for XAttrs {
fn clone(&self) -> Self {
XAttrs {
data: Vec::from(&*self.data).into_boxed_slice(),
offset: self.offset,
}
}
fn clone_from(&mut self, other: &XAttrs) {
self.offset = other.offset;
let mut data = mem::replace(&mut self.data, Box::new([])).into_vec();
data.extend(other.data.iter().cloned());
self.data = data.into_boxed_slice();
}
}
// Yes, I could avoid these allocations on linux/macos. However, if we ever want to be freebsd
// compatible, we need to be able to prepend the namespace to the extended attribute names.
// Furthermore, borrowing makes the API messy.
impl Iterator for XAttrs {
type Item = OsString;
fn next(&mut self) -> Option<OsString> {
let data = &self.data[self.offset..];
if data.is_empty() {
None
} else {
// always null terminated (unless empty).
let end = data.iter().position(|&b| b == 0u8).unwrap();
self.offset += end + 1;
Some(OsStr::from_bytes(&data[..end]).to_owned())
}
}
fn size_hint(&self) -> (usize, Option<usize>) {
if self.data.len() == self.offset {
(0, Some(0))
} else {
(1, None)
}
}
}
pub fn get_fd(fd: RawFd, name: &OsStr) -> io::Result<Vec<u8>> {
let name = name_to_c(name)?;
unsafe {
allocate_loop(|buf, len| fgetxattr(fd, name.as_ptr(), buf as *mut c_void, len as size_t))
}
}
pub fn set_fd(fd: RawFd, name: &OsStr, value: &[u8]) -> io::Result<()> {
let name = name_to_c(name)?;
let ret = unsafe {
fsetxattr(
fd,
name.as_ptr(),
value.as_ptr() as *const c_void,
value.len() as size_t,
)
};
if ret != 0 {
Err(io::Error::last_os_error())
} else {
Ok(())
}
}
pub fn remove_fd(fd: RawFd, name: &OsStr) -> io::Result<()> {
let name = name_to_c(name)?;
let ret = unsafe { fremovexattr(fd, name.as_ptr()) };
if ret != 0 {
Err(io::Error::last_os_error())
} else {
Ok(())
}
}
pub fn list_fd(fd: RawFd) -> io::Result<XAttrs> {
let vec =
unsafe { allocate_loop(|buf, len| flistxattr(fd, buf as *mut c_char, len as size_t))? };
Ok(XAttrs {
data: vec.into_boxed_slice(),
offset: 0,
})
}
pub fn get_path(path: &Path, name: &OsStr) -> io::Result<Vec<u8>> {
let name = name_to_c(name)?;
let path = path_to_c(path)?;
unsafe {
allocate_loop(|buf, len| {
lgetxattr(
path.as_ptr(),
name.as_ptr(),
buf as *mut c_void,
len as size_t,
)
})
}
}
pub fn set_path(path: &Path, name: &OsStr, value: &[u8]) -> io::Result<()> {
let name = name_to_c(name)?;
let path = path_to_c(path)?;
let ret = unsafe {
lsetxattr(
path.as_ptr(),
name.as_ptr(),
value.as_ptr() as *const c_void,
value.len() as size_t,
)
};
if ret != 0 {
Err(io::Error::last_os_error())
} else {
Ok(())
}
}
pub fn remove_path(path: &Path, name: &OsStr) -> io::Result<()> {
let name = name_to_c(name)?;
let path = path_to_c(path)?;
let ret = unsafe { lremovexattr(path.as_ptr(), name.as_ptr()) };
if ret != 0 {
Err(io::Error::last_os_error())
} else {
Ok(())
}
}
pub fn list_path(path: &Path) -> io::Result<XAttrs> {
let path = path_to_c(path)?;
let vec = unsafe {
allocate_loop(|buf, len| llistxattr(path.as_ptr(), buf as *mut c_char, len as size_t))?
};
Ok(XAttrs {
data: vec.into_boxed_slice(),
offset: 0,
})
}
+45
View File
@@ -0,0 +1,45 @@
macro_rules! platforms {
($($($platform:expr);* => $module:ident),*) => {
$(
#[cfg(any($(target_os = $platform),*))]
#[cfg_attr(not(any($(target_os = $platform),*)), allow(dead_code))]
mod $module;
#[cfg(any($(target_os = $platform),*))]
pub use self::$module::*;
#[cfg(all(any($(target_os = $platform),*), not(any(target_os = "linux", target_os = "android"))))]
pub const ENOATTR: ::libc::c_int = ::libc::ENOATTR;
)*
#[cfg(all(feature = "unsupported", not(any($($(target_os = $platform),*),*))))]
#[cfg_attr(any($($(target_os = $platform),*),*), allow(dead_code))]
mod unsupported;
#[cfg(all(feature = "unsupported", not(any($($(target_os = $platform),*),*))))]
pub use self::unsupported::*;
#[cfg(all(feature = "unsupported", not(any($($(target_os = $platform),*),*))))]
pub const ENOATTR: ::libc::c_int = 0;
/// A constant indicating whether or not the target platform is supported.
///
/// To make programmer's lives easier, this library builds on all platforms.
/// However, all function calls on unsupported platforms will return
/// `io::Error`s.
///
/// Note: If you would like compilation to simply fail on unsupported platforms,
/// turn of the `unsupported` feature.
pub const SUPPORTED_PLATFORM: bool = cfg!(any($($(target_os = $platform),*),*));
}
}
// Linux calls this error ENODATA. Recent libc versions no longer expose the
// deprecated ENOATTR alias; Darwin and BSD still use their native ENOATTR.
#[cfg(any(target_os = "linux", target_os = "android"))]
pub const ENOATTR: ::libc::c_int = ::libc::ENODATA;
platforms! {
"android"; "linux"; "macos" => linux_macos,
"freebsd"; "netbsd" => bsd
}
+77
View File
@@ -0,0 +1,77 @@
use std::ffi::{OsStr, OsString};
use std::io;
use std::os::unix::io::RawFd;
use std::path::Path;
use UnsupportedPlatformError;
/// An iterator over a set of extended attributes names.
#[derive(Clone, Debug)]
pub struct XAttrs;
impl Iterator for XAttrs {
type Item = OsString;
fn next(&mut self) -> Option<OsString> {
unreachable!("this should never exist")
}
fn size_hint(&self) -> (usize, Option<usize>) {
unreachable!("this should never exist")
}
}
pub fn get_fd(_: RawFd, _: &OsStr) -> io::Result<Vec<u8>> {
Err(io::Error::new(
io::ErrorKind::Other,
UnsupportedPlatformError,
))
}
pub fn set_fd(_: RawFd, _: &OsStr, _: &[u8]) -> io::Result<()> {
Err(io::Error::new(
io::ErrorKind::Other,
UnsupportedPlatformError,
))
}
pub fn remove_fd(_: RawFd, _: &OsStr) -> io::Result<()> {
Err(io::Error::new(
io::ErrorKind::Other,
UnsupportedPlatformError,
))
}
pub fn list_fd(_: RawFd) -> io::Result<XAttrs> {
Err(io::Error::new(
io::ErrorKind::Other,
UnsupportedPlatformError,
))
}
pub fn get_path(_: &Path, _: &OsStr) -> io::Result<Vec<u8>> {
Err(io::Error::new(
io::ErrorKind::Other,
UnsupportedPlatformError,
))
}
pub fn set_path(_: &Path, _: &OsStr, _: &[u8]) -> io::Result<()> {
Err(io::Error::new(
io::ErrorKind::Other,
UnsupportedPlatformError,
))
}
pub fn remove_path(_: &Path, _: &OsStr) -> io::Result<()> {
Err(io::Error::new(
io::ErrorKind::Other,
UnsupportedPlatformError,
))
}
pub fn list_path(_: &Path) -> io::Result<XAttrs> {
Err(io::Error::new(
io::ErrorKind::Other,
UnsupportedPlatformError,
))
}
+65
View File
@@ -0,0 +1,65 @@
use std::ffi::CString;
use std::ffi::OsStr;
use std::io;
use std::os::unix::ffi::OsStrExt;
use std::path::Path;
use std::ptr;
use libc::{ssize_t, ERANGE};
// Need to use this one as libc only defines this on supported platforms. Given
// that we want to at least compile on unsupported platforms, we define this in
// our platform-specific modules.
use sys::ENOATTR;
#[allow(dead_code)]
pub fn name_to_c(name: &OsStr) -> io::Result<CString> {
match CString::new(name.as_bytes()) {
Ok(name) => Ok(name),
Err(_) => Err(io::Error::new(
io::ErrorKind::InvalidInput,
"name must not contain null bytes",
)),
}
}
pub fn path_to_c(path: &Path) -> io::Result<CString> {
match CString::new(path.as_os_str().as_bytes()) {
Ok(name) => Ok(name),
Err(_) => Err(io::Error::new(io::ErrorKind::NotFound, "file not found")),
}
}
pub fn extract_noattr(result: io::Result<Vec<u8>>) -> io::Result<Option<Vec<u8>>> {
result.map(Some).or_else(|e| match e.raw_os_error() {
Some(ENOATTR) => Ok(None),
_ => Err(e),
})
}
pub unsafe fn allocate_loop<F: FnMut(*mut u8, usize) -> ssize_t>(mut f: F) -> io::Result<Vec<u8>> {
let mut vec: Vec<u8> = Vec::new();
loop {
let ret = (f)(ptr::null_mut(), 0);
if ret < 0 {
return Err(io::Error::last_os_error());
} else if ret == 0 {
break;
}
vec.reserve_exact(ret as usize);
let ret = (f)(vec.as_mut_ptr(), vec.capacity());
if ret >= 0 {
vec.set_len(ret as usize);
break;
} else {
let error = io::Error::last_os_error();
if error.raw_os_error() == Some(ERANGE) {
continue;
}
return Err(error);
}
}
vec.shrink_to_fit();
Ok(vec)
}