From 0cd3fe8f975515c28a44825dce7894da802296d9 Mon Sep 17 00:00:00 2001 From: Wez Furlong Date: Sun, 20 Apr 2025 07:03:29 -0700 Subject: [PATCH] wezterm-escape-parser: allow building no_std (but with alloc) This commit makes a number of parts of wezterm's core parsing functionality no_std compatible, but requiring alloc. In the no_std environment, several lookup tables that would normally have been used to accelerate some operations are not available and we instead fall back to an O(n) operation. --- Cargo.lock | 9 +- Cargo.toml | 16 +- Makefile | 1 + bidi/README.md | 2 + bidi/src/direction.rs | 2 +- bidi/src/lib.rs | 21 ++- color-types/Cargo.toml | 6 +- color-types/src/lib.rs | 177 ++++++++++++++++++---- lua-api-crates/color-funcs/Cargo.toml | 1 + procinfo/Cargo.toml | 2 +- termwiz/Cargo.toml | 10 +- termwiz/src/error.rs | 3 - wezterm-dynamic/Cargo.toml | 9 +- wezterm-dynamic/derive/src/fromdynamic.rs | 8 +- wezterm-dynamic/src/array.rs | 7 +- wezterm-dynamic/src/drop.rs | 5 + wezterm-dynamic/src/error.rs | 38 ++++- wezterm-dynamic/src/fromdynamic.rs | 42 ++++- wezterm-dynamic/src/lib.rs | 4 + wezterm-dynamic/src/object.rs | 23 +-- wezterm-dynamic/src/todynamic.rs | 28 +++- wezterm-dynamic/src/value.rs | 11 +- wezterm-escape-parser/Cargo.toml | 11 +- wezterm-escape-parser/src/allocate.rs | 13 ++ wezterm-escape-parser/src/apc.rs | 18 +-- wezterm-escape-parser/src/color.rs | 2 + wezterm-escape-parser/src/csi.rs | 6 +- wezterm-escape-parser/src/error.rs | 29 ++-- wezterm-escape-parser/src/esc.rs | 2 +- wezterm-escape-parser/src/hyperlink.rs | 5 +- wezterm-escape-parser/src/lib.rs | 11 +- wezterm-escape-parser/src/osc.rs | 84 +++++++--- wezterm-escape-parser/src/parser/mod.rs | 8 +- wezterm-input-types/Cargo.toml | 3 +- wezterm-input-types/src/lib.rs | 137 +++++++++++++---- 35 files changed, 568 insertions(+), 186 deletions(-) create mode 100644 wezterm-escape-parser/src/allocate.rs diff --git a/Cargo.lock b/Cargo.lock index 91a6de24a..ade14b790 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -893,6 +893,7 @@ dependencies = [ "serde", "serde_json", "serde_yaml", + "wezterm-color-types", "wezterm-dynamic", "wezterm-term", ] @@ -3735,6 +3736,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841" dependencies = [ "autocfg", + "libm", ] [[package]] @@ -5642,7 +5644,6 @@ name = "termwiz" version = "0.24.0" dependencies = [ "anyhow", - "base64 0.22.1", "bitflags 2.9.0", "cassowary", "criterion", @@ -5652,7 +5653,6 @@ dependencies = [ "finl_unicode", "fixedbitset", "fnv", - "hex", "image", "k9", "libc", @@ -6627,6 +6627,7 @@ version = "0.3.0" dependencies = [ "csscolorparser", "deltae", + "num-traits", "serde", "wezterm-dynamic", ] @@ -6648,7 +6649,7 @@ dependencies = [ "maplit", "ordered-float 4.6.0", "strsim", - "thiserror 1.0.69", + "thiserror 2.0.12", "wezterm-dynamic-derive", ] @@ -6681,7 +6682,7 @@ dependencies = [ "pest_derive", "serde", "sha2", - "thiserror 1.0.69", + "thiserror 2.0.12", "vtparse", "wezterm-blob-leases", "wezterm-color-types", diff --git a/Cargo.toml b/Cargo.toml index 3472a3640..63e4f0879 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -40,7 +40,7 @@ async-task = "4.7" async-trait = "0.1" async_ossl = { path = "async_ossl" } backtrace = "0.3" -base64 = "0.22" +base64 = {version="0.22", default-features=false } base91 = { path = "base91" } battery = { path = "lua-api-crates/battery" } benchmarking = "0.4" @@ -83,7 +83,7 @@ encoding_rs = "0.8" enum-display-derive = "0.1" env-bootstrap = { path = "env-bootstrap" } env_logger = "0.11" -euclid = "0.22" +euclid = {version="0.22", default-features=false} fancy-regex = "0.11" fastrand = "2.0" filedescriptor = { version="0.8.3", path = "filedescriptor" } @@ -110,7 +110,7 @@ guillotiere = "0.6" harfbuzz = { path = "deps/harfbuzz" } heapless = "0.8" hdrhistogram = "7.1" -hex = "0.4" +hex = {version="0.4", default-features=false} hostname = "0.4" http_req = "0.11" human-sort = "0.2" @@ -148,14 +148,14 @@ ntapi = "0.4" nucleo-matcher = "0.3" num = "0.4" num-derive = "0.4" -num-traits = "0.2" +num-traits = {version="0.2", default-features=false } objc = "0.2" objc2 = "0.6" objc2-core-graphics = "0.3" objc2-foundation = "0.3" objc2-user-notifications = "0.3" openssl = "0.10.57" -ordered-float = "4.1" +ordered-float = {version="4.1", default-features=false} parking_lot = "0.12" passfd = "0.1.6" percent-encoding = "2.3" @@ -183,7 +183,7 @@ reqwest = "0.12" resize = "0.5" rstest = "0.21" rusqlite = "0.32" -serde = {version="1.0", features = ["derive"]} +serde = {version="1.0", default-features=false, features = ["derive"]} serde-funcs = { path = "lua-api-crates/serde-funcs" } serde_json = "1.0" serde_with = {version="2.0", features = ["chrono_0_4"]} @@ -230,7 +230,7 @@ url-funcs = { path = "lua-api-crates/url-funcs" } utf8parse = "0.2" uuid = "1.13" varbincode = "0.1" -vtparse = { version="0.7", path="vtparse" } +vtparse = { version="0.7", path="vtparse", default-features=false } walkdir = "2" wayland-backend = "0.3.5" wayland-client = "0.31" @@ -247,7 +247,7 @@ wezterm-dynamic-derive = { version="0.1.1", path="wezterm-dynamic/derive" } wezterm-escape-parser = { version="0.1.0", path="wezterm-escape-parser" } wezterm-font = { path = "wezterm-font" } wezterm-gui-subcommands = { path = "wezterm-gui-subcommands" } -wezterm-input-types = { version="0.1", path = "wezterm-input-types" } +wezterm-input-types = { version="0.1", path = "wezterm-input-types", default-features=false } wezterm-mux-server-impl = { path = "wezterm-mux-server-impl" } wezterm-open-url = { path = "wezterm-open-url" } wezterm-ssh = { path = "wezterm-ssh" } diff --git a/Makefile b/Makefile index af01a973f..a0a4659a8 100644 --- a/Makefile +++ b/Makefile @@ -7,6 +7,7 @@ test: check: cargo check + cargo check -p wezterm-escape-parser build: cargo build $(BUILD_OPTS) -p wezterm diff --git a/bidi/README.md b/bidi/README.md index 73b100577..046a75ac7 100644 --- a/bidi/README.md +++ b/bidi/README.md @@ -8,6 +8,8 @@ other code in wezterm. The focus for this crate is conformance. +This crate is `no_std`, but does require `alloc`. + ## Status This crate resolves embedding levels and can reorder line ranges. diff --git a/bidi/src/direction.rs b/bidi/src/direction.rs index 1379c4589..305103b4d 100644 --- a/bidi/src/direction.rs +++ b/bidi/src/direction.rs @@ -40,7 +40,7 @@ impl Direction { pub enum DirectionIter, T> { LTR(I), - RTL(std::iter::Rev), + RTL(core::iter::Rev), } impl, T> DirectionIter { diff --git a/bidi/src/lib.rs b/bidi/src/lib.rs index 1dd68f72b..4029269e8 100644 --- a/bidi/src/lib.rs +++ b/bidi/src/lib.rs @@ -1,10 +1,16 @@ +#![no_std] +use alloc::borrow::Cow; +use core::ops::Range; use level::MAX_DEPTH; use level_stack::{LevelStack, Override}; use log::trace; -use std::borrow::Cow; -use std::ops::Range; use wezterm_dynamic::{FromDynamic, ToDynamic}; +extern crate alloc; +use crate::alloc::string::ToString; +use alloc::vec; +use alloc::vec::Vec; + mod bidi_brackets; mod bidi_class; mod direction; @@ -1870,8 +1876,8 @@ struct Pair { closing_pos: usize, } -impl std::fmt::Debug for Pair { - fn fmt(&self, fmt: &mut std::fmt::Formatter) -> std::fmt::Result { +impl core::fmt::Debug for Pair { + fn fmt(&self, fmt: &mut core::fmt::Formatter) -> core::fmt::Result { write!(fmt, "Pair{{{},{}}}", self.opening_pos, self.closing_pos) } } @@ -1884,8 +1890,8 @@ struct BracketStack { pairs: Vec, } -impl std::fmt::Debug for BracketStack { - fn fmt(&self, fmt: &mut std::fmt::Formatter) -> std::fmt::Result { +impl core::fmt::Debug for BracketStack { + fn fmt(&self, fmt: &mut core::fmt::Formatter) -> core::fmt::Result { fmt.debug_struct("BracketStack") .field("closing_bracket", &&self.closing_bracket[0..self.depth]) .field("position", &&self.position[0..self.depth]) @@ -1984,7 +1990,7 @@ fn lookup_closing(c: char) -> Option<(char, BracketType)> { } pub fn bidi_class_for_char(c: char) -> BidiClass { - use std::cmp::Ordering; + use core::cmp::Ordering; if let Ok(idx) = bidi_class::BIDI_CLASS.binary_search_by(|&(lower, upper, _)| { if c >= lower && c <= upper { Ordering::Equal @@ -2010,6 +2016,7 @@ pub fn bidi_class_for_char(c: char) -> BidiClass { #[cfg(test)] mod tests { use super::*; + use alloc::format; use k9::assert_equal as assert_eq; #[test] diff --git a/color-types/Cargo.toml b/color-types/Cargo.toml index 1237e1f61..eeda11164 100644 --- a/color-types/Cargo.toml +++ b/color-types/Cargo.toml @@ -9,9 +9,11 @@ license = "MIT" [features] use_serde = ["serde"] +std = ["serde/std", "dep:deltae", "csscolorparser/lab"] [dependencies] -csscolorparser = {workspace=true, features=["lab"]} -deltae.workspace = true +csscolorparser = {workspace=true, optional=true} +deltae = {workspace = true, optional=true} +num-traits = {workspace=true, features=["libm"]} serde = {workspace=true, features = ["derive"], optional=true} wezterm-dynamic.workspace = true diff --git a/color-types/src/lib.rs b/color-types/src/lib.rs index 234e6a614..bc32223da 100644 --- a/color-types/src/lib.rs +++ b/color-types/src/lib.rs @@ -1,17 +1,35 @@ +#![cfg_attr(not(feature = "std"), no_std)] + +use core::hash::{Hash, Hasher}; +use core::str::FromStr; +#[cfg(feature = "std")] use csscolorparser::Color; +#[cfg(not(feature = "std"))] +use num_traits::float::Float; #[cfg(feature = "use_serde")] use serde::{Deserialize, Serialize}; +#[cfg(feature = "std")] use std::collections::HashMap; -use std::hash::{Hash, Hasher}; -use std::str::FromStr; +#[cfg(feature = "std")] use std::sync::LazyLock; use wezterm_dynamic::{FromDynamic, FromDynamicOptions, ToDynamic, Value}; +extern crate alloc; + +use alloc::format; +use alloc::string::String; +use alloc::vec::Vec; + +#[cfg(feature = "std")] static SRGB_TO_F32_TABLE: LazyLock<[f32; 256]> = LazyLock::new(generate_srgb8_to_linear_f32_table); +#[cfg(feature = "std")] static F32_TO_U8_TABLE: LazyLock<[u32; 104]> = LazyLock::new(generate_linear_f32_to_srgb8_table); +#[cfg(feature = "std")] static RGB_TO_SRGB_TABLE: LazyLock<[u8; 256]> = LazyLock::new(generate_rgb_to_srgb8_table); +#[cfg(feature = "std")] static RGB_TO_F32_TABLE: LazyLock<[f32; 256]> = LazyLock::new(generate_rgb_to_linear_f32_table); +#[cfg(feature = "std")] fn generate_rgb_to_srgb8_table() -> [u8; 256] { let mut table = [0; 256]; for (val, entry) in table.iter_mut().enumerate() { @@ -21,6 +39,7 @@ fn generate_rgb_to_srgb8_table() -> [u8; 256] { table } +#[cfg(feature = "std")] fn generate_rgb_to_linear_f32_table() -> [f32; 256] { let mut table = [0.; 256]; for (val, entry) in table.iter_mut().enumerate() { @@ -29,6 +48,7 @@ fn generate_rgb_to_linear_f32_table() -> [f32; 256] { table } +#[cfg(feature = "std")] fn generate_srgb8_to_linear_f32_table() -> [f32; 256] { let mut table = [0.; 256]; for (val, entry) in table.iter_mut().enumerate() { @@ -43,6 +63,7 @@ fn generate_srgb8_to_linear_f32_table() -> [f32; 256] { } #[allow(clippy::unreadable_literal)] +#[cfg(feature = "std")] fn generate_linear_f32_to_srgb8_table() -> [u32; 104] { // My intent was to generate this array on the fly using the code that is commented // out below. It is based on this gist: @@ -128,16 +149,17 @@ fn linear_f32_to_srgbf32(f: f32) -> f32 { } } +#[cfg(feature = "std")] pub fn linear_u8_to_srgb8(f: u8) -> u8 { unsafe { *RGB_TO_SRGB_TABLE.get_unchecked(f as usize) } } -#[allow(clippy::unreadable_literal)] -const ALMOST_ONE: u32 = 0x3f7fffff; -#[allow(clippy::unreadable_literal)] -const MINVAL: u32 = (127 - 13) << 23; - +#[cfg(feature = "std")] fn linear_f32_to_srgb8_using_table(f: f32) -> u8 { + #[allow(clippy::unreadable_literal)] + const ALMOST_ONE: u32 = 0x3f7fffff; + #[allow(clippy::unreadable_literal)] + const MINVAL: u32 = (127 - 13) << 23; let minval = f32::from_bits(MINVAL); let almost_one = f32::from_bits(ALMOST_ONE); @@ -159,13 +181,43 @@ fn linear_f32_to_srgb8_using_table(f: f32) -> u8 { ((bias + scale * t) >> 16) as u8 } +fn linear_f32_to_srgb8(f: f32) -> u8 { + #[cfg(feature = "std")] + { + return linear_f32_to_srgb8_using_table(f); + } + #[cfg(not(feature = "std"))] + { + (linear_f32_to_srgbf32(f) * 255.) as u8 + } +} + /// Convert from srgb in u8 0-255 to linear floating point rgb 0-1.0 fn srgb8_to_linear_f32(val: u8) -> f32 { - unsafe { *SRGB_TO_F32_TABLE.get_unchecked(val as usize) } + #[cfg(feature = "std")] + { + return unsafe { *SRGB_TO_F32_TABLE.get_unchecked(val as usize) }; + } + #[cfg(not(feature = "std"))] + { + let c = (val as f32) / 255.0; + if c <= 0.04045 { + c / 12.92 + } else { + ((c + 0.055) / 1.055).powf(2.4) + } + } } fn rgb_to_linear_f32(val: u8) -> f32 { - unsafe { *RGB_TO_F32_TABLE.get_unchecked(val as usize) } + #[cfg(feature = "std")] + { + unsafe { *RGB_TO_F32_TABLE.get_unchecked(val as usize) } + } + #[cfg(not(feature = "std"))] + { + (val as f32) / 255.0 + } } /// A pixel holding SRGBA32 data in big endian format @@ -318,6 +370,7 @@ impl From for (f32, f32, f32, f32) { } } +#[cfg(feature = "std")] impl From for SrgbaTuple { fn from(color: Color) -> Self { Self( @@ -329,17 +382,20 @@ impl From for SrgbaTuple { } } +#[cfg(feature = "std")] static NAMED_COLORS: LazyLock> = LazyLock::new(build_colors); -fn build_colors() -> HashMap { - let mut map = HashMap::new(); - let rgb_txt = include_str!("rgb.txt"); +const RGB_TXT: &str = core::include_str!("rgb.txt"); - map.insert("transparent".to_string(), SrgbaTuple(0., 0., 0., 0.)); - map.insert("none".to_string(), SrgbaTuple(0., 0., 0., 0.)); - map.insert("clear".to_string(), SrgbaTuple(0., 0., 0., 0.)); +fn iter_rgb_txt(mut func: impl FnMut(&str, SrgbaTuple) -> bool) { + let transparent = SrgbaTuple(0., 0., 0., 0.); + for name in &["transparent", "none", "clear"] { + if (func)(name, transparent) { + return; + } + } - for line in rgb_txt.lines() { + for line in RGB_TXT.lines() { let mut fields = line.split_ascii_whitespace(); let red = fields.next().unwrap(); let green = fields.next().unwrap(); @@ -347,17 +403,27 @@ fn build_colors() -> HashMap { let name = fields.collect::>().join(" "); let name = name.to_ascii_lowercase(); - map.insert( - name, - SrgbaTuple( - red.parse::().unwrap() / 255., - green.parse::().unwrap() / 255., - blue.parse::().unwrap() / 255., - 1.0, - ), + let color = SrgbaTuple( + red.parse::().unwrap() / 255., + green.parse::().unwrap() / 255., + blue.parse::().unwrap() / 255., + 1.0, ); - } + if (func)(&name, color) { + return; + } + } +} + +#[cfg(feature = "std")] +fn build_colors() -> HashMap { + let mut map = HashMap::new(); + + iter_rgb_txt(|name, color| { + map.insert(name.to_string(), color); + false + }); map } @@ -367,7 +433,23 @@ impl SrgbaTuple { /// The list of names can be found here: /// pub fn from_named(name: &str) -> Option { - NAMED_COLORS.get(&name.to_ascii_lowercase()).cloned() + #[cfg(feature = "std")] + { + return NAMED_COLORS.get(&name.to_ascii_lowercase()).cloned(); + } + #[cfg(not(feature = "std"))] + { + let mut result = None; + iter_rgb_txt(|candidate, color| { + if candidate.eq_ignore_ascii_case(name) { + result.replace(color); + true + } else { + false + } + }); + result + } } /// Returns self multiplied by the supplied alpha value. @@ -442,20 +524,24 @@ impl SrgbaTuple { ) } + #[cfg(feature = "std")] pub fn to_laba(self) -> (f64, f64, f64, f64) { Color::new(self.0.into(), self.1.into(), self.2.into(), self.3.into()).to_lab() } + #[cfg(feature = "std")] pub fn to_hsla(self) -> (f64, f64, f64, f64) { Color::new(self.0.into(), self.1.into(), self.2.into(), self.3.into()).to_hsla() } + #[cfg(feature = "std")] pub fn from_hsla(h: f64, s: f64, l: f64, a: f64) -> Self { let Color { r, g, b, a } = Color::from_hsla(h, s, l, a); Self(r as f32, g as f32, b as f32, a as f32) } /// Scale the color towards the maximum saturation by factor, a value ranging from 0.0 to 1.0. + #[cfg(feature = "std")] pub fn saturate(&self, factor: f64) -> Self { let (h, s, l, a) = self.to_hsla(); let s = apply_scale(s, factor); @@ -463,6 +549,7 @@ impl SrgbaTuple { } /// Increase the saturation by amount, a value ranging from 0.0 to 1.0. + #[cfg(feature = "std")] pub fn saturate_fixed(&self, amount: f64) -> Self { let (h, s, l, a) = self.to_hsla(); let s = apply_fixed(s, amount); @@ -470,6 +557,7 @@ impl SrgbaTuple { } /// Scale the color towards the maximum lightness by factor, a value ranging from 0.0 to 1.0 + #[cfg(feature = "std")] pub fn lighten(&self, factor: f64) -> Self { let (h, s, l, a) = self.to_hsla(); let l = apply_scale(l, factor); @@ -477,6 +565,7 @@ impl SrgbaTuple { } /// Lighten the color by amount, a value ranging from 0.0 to 1.0 + #[cfg(feature = "std")] pub fn lighten_fixed(&self, amount: f64) -> Self { let (h, s, l, a) = self.to_hsla(); let l = apply_fixed(l, amount); @@ -484,24 +573,29 @@ impl SrgbaTuple { } /// Rotate the hue angle by the specified number of degrees + #[cfg(feature = "std")] pub fn adjust_hue_fixed(&self, amount: f64) -> Self { let (h, s, l, a) = self.to_hsla(); let h = normalize_angle(h + amount); Self::from_hsla(h, s, l, a) } + #[cfg(feature = "std")] pub fn complement(&self) -> Self { self.adjust_hue_fixed(180.) } + #[cfg(feature = "std")] pub fn complement_ryb(&self) -> Self { self.adjust_hue_fixed_ryb(180.) } + #[cfg(feature = "std")] pub fn triad(&self) -> (Self, Self) { (self.adjust_hue_fixed(120.), self.adjust_hue_fixed(-120.)) } + #[cfg(feature = "std")] pub fn square(&self) -> (Self, Self, Self) { ( self.adjust_hue_fixed(90.), @@ -512,6 +606,7 @@ impl SrgbaTuple { /// Rotate the hue angle by the specified number of degrees, using /// the RYB color wheel + #[cfg(feature = "std")] pub fn adjust_hue_fixed_ryb(&self, amount: f64) -> Self { let (h, s, l, a) = self.to_hsla(); let h = rgb_hue_to_ryb_hue(h); @@ -520,6 +615,7 @@ impl SrgbaTuple { Self::from_hsla(h, s, l, a) } + #[cfg(feature = "std")] fn lab_value(&self) -> deltae::LabValue { let (l, a, b, _alpha) = self.to_laba(); deltae::LabValue { @@ -529,12 +625,14 @@ impl SrgbaTuple { } } + #[cfg(feature = "std")] pub fn delta_e(&self, other: &Self) -> f32 { let a = self.lab_value(); let b = other.lab_value(); *deltae::DeltaE::new(a, b, deltae::DEMethod::DE2000).value() } + #[cfg(feature = "std")] pub fn contrast_ratio(&self, other: &Self) -> f32 { self.to_linear().contrast_ratio(&other.to_linear()) } @@ -546,6 +644,7 @@ impl SrgbaTuple { /// foreground color. /// If the ratio is already suitable, returns None; the caller should /// continue to use `self` as the foreground color. + #[cfg(feature = "std")] pub fn ensure_contrast_ratio(&self, other: &Self, min_ratio: f32) -> Option { self.to_linear() .ensure_contrast_ratio(&other.to_linear(), min_ratio) @@ -555,6 +654,7 @@ impl SrgbaTuple { /// Convert an RGB color space hue angle to an RYB colorspace hue angle /// +#[cfg(feature = "std")] fn rgb_hue_to_ryb_hue(hue: f64) -> f64 { if hue < 35. { map_range(hue, 0., 35., 0., 60.) @@ -574,6 +674,7 @@ fn rgb_hue_to_ryb_hue(hue: f64) -> f64 { } /// Convert an RYB color space hue angle to an RGB colorspace hue angle +#[cfg(feature = "std")] fn ryb_huge_to_rgb_hue(hue: f64) -> f64 { if hue < 60. { map_range(hue, 0., 60., 0., 35.) @@ -592,12 +693,14 @@ fn ryb_huge_to_rgb_hue(hue: f64) -> f64 { } } +#[cfg(feature = "std")] fn map_range(x: f64, x1: f64, x2: f64, y1: f64, y2: f64) -> f64 { let a_slope = (y2 - y1) / (x2 - x1); let a_slope_intercept = y1 - (a_slope * x1); x * a_slope + a_slope_intercept } +#[cfg(feature = "std")] fn normalize_angle(t: f64) -> f64 { let mut t = t % 360.0; if t < 0.0 { @@ -606,12 +709,14 @@ fn normalize_angle(t: f64) -> f64 { t } +#[cfg(feature = "std")] fn apply_scale(current: f64, factor: f64) -> f64 { let difference = if factor >= 0. { 1.0 - current } else { current }; let delta = difference.max(0.) * factor; (current + delta).max(0.) } +#[cfg(feature = "std")] fn apply_fixed(current: f64, amount: f64) -> f64 { (current + amount).max(0.) } @@ -776,9 +881,13 @@ impl FromStr for SrgbaTuple { } else { Err(()) } - } else if let Ok(c) = csscolorparser::parse(s) { - Ok(Self(c.r as f32, c.g as f32, c.b as f32, c.a as f32)) } else { + #[cfg(feature = "std")] + { + if let Ok(c) = csscolorparser::parse(s) { + return Ok(Self(c.r as f32, c.g as f32, c.b as f32, c.a as f32)); + } + } Self::from_named(s).ok_or(()) } } @@ -872,9 +981,9 @@ impl LinearRgba { /// Convert to an SRGB u32 pixel pub fn srgba_pixel(self) -> SrgbaPixel { SrgbaPixel::rgba( - linear_f32_to_srgb8_using_table(self.0), - linear_f32_to_srgb8_using_table(self.1), - linear_f32_to_srgb8_using_table(self.2), + linear_f32_to_srgb8(self.0), + linear_f32_to_srgb8(self.1), + linear_f32_to_srgb8(self.2), (self.3 * 255.) as u8, ) } @@ -894,16 +1003,19 @@ impl LinearRgba { ) } + #[cfg(feature = "std")] pub fn relative_luminance(&self) -> f32 { 0.2126 * self.0 + 0.7152 * self.1 + 0.0722 * self.2 } + #[cfg(feature = "std")] pub fn contrast_ratio(&self, other: &Self) -> f32 { let lum_a = self.relative_luminance(); let lum_b = other.relative_luminance(); Self::lum_contrast_ratio(lum_a, lum_b) } + #[cfg(feature = "std")] fn lum_contrast_ratio(lum_a: f32, lum_b: f32) -> f32 { let a = lum_a + 0.05; let b = lum_b + 0.05; @@ -914,6 +1026,7 @@ impl LinearRgba { } } + #[cfg(feature = "std")] fn to_oklaba(&self) -> [f32; 4] { let (r, g, b, alpha) = (self.0, self.1, self.2, self.3); let l_ = (0.4122214708 * r + 0.5363325363 * g + 0.0514459929 * b).cbrt(); @@ -925,6 +1038,7 @@ impl LinearRgba { [l, a, b, alpha] } + #[cfg(feature = "std")] fn from_oklaba(l: f32, a: f32, b: f32, alpha: f32) -> Self { let l_ = (l + 0.3963377774 * a + 0.2158037573 * b).powi(3); let m_ = (l - 0.1055613458 * a - 0.0638541728 * b).powi(3); @@ -944,6 +1058,7 @@ impl LinearRgba { /// foreground color. /// If the ratio is already suitable, returns None; the caller should /// continue to use `self` as the foreground color. + #[cfg(feature = "std")] pub fn ensure_contrast_ratio(&self, other: &Self, min_ratio: f32) -> Option { if self == other { // Intentionally the same color, don't try to fixup diff --git a/lua-api-crates/color-funcs/Cargo.toml b/lua-api-crates/color-funcs/Cargo.toml index 3f497a9ef..de8dd21c0 100644 --- a/lua-api-crates/color-funcs/Cargo.toml +++ b/lua-api-crates/color-funcs/Cargo.toml @@ -21,4 +21,5 @@ serde = {workspace=true, features=["derive"]} serde_json.workspace = true serde_yaml.workspace = true wezterm-dynamic.workspace = true +wezterm-color-types = {workspace=true, features=["std"]} wezterm-term = { workspace=true, features=["use_serde"] } diff --git a/procinfo/Cargo.toml b/procinfo/Cargo.toml index 814824dd5..e695a35a6 100644 --- a/procinfo/Cargo.toml +++ b/procinfo/Cargo.toml @@ -13,7 +13,7 @@ lua = ["dep:luahelper", "dep:wezterm-dynamic"] libc.workspace = true log.workspace = true luahelper = { workspace=true, optional = true } -wezterm-dynamic = { workspace=true, optional = true } +wezterm-dynamic = { workspace=true, optional = true, features=["std"]} [target."cfg(windows)".dependencies] ntapi.workspace = true diff --git a/termwiz/Cargo.toml b/termwiz/Cargo.toml index b2d2d8741..c3ea45f02 100644 --- a/termwiz/Cargo.toml +++ b/termwiz/Cargo.toml @@ -12,7 +12,6 @@ readme = "README.md" [dependencies] anyhow.workspace = true -base64.workspace = true bitflags = "2.0" cassowary = {workspace=true, optional=true} fancy-regex.workspace = true @@ -20,14 +19,13 @@ filedescriptor.workspace = true finl_unicode.workspace = true fixedbitset.workspace = true fnv = {workspace=true, optional=true} -hex.workspace = true image = {workspace=true, optional=true} libc.workspace = true log.workspace = true memmem.workspace = true num-derive.workspace = true num-traits.workspace = true -ordered-float.workspace = true +ordered-float = {workspace = true, features=["std"]} pest = {workspace=true, optional=true} pest_derive = {workspace=true, optional=true} phf.workspace = true @@ -41,9 +39,9 @@ unicode-segmentation.workspace = true vtparse.workspace = true wezterm-bidi.workspace = true wezterm-blob-leases = {workspace=true, optional=true} -wezterm-color-types.workspace = true -wezterm-dynamic.workspace = true -wezterm-escape-parser.workspace = true +wezterm-color-types = {workspace = true, features=["std"]} +wezterm-dynamic = {workspace = true, features=["std"]} +wezterm-escape-parser = {workspace = true, features=["std"]} wezterm-input-types.workspace = true [features] diff --git a/termwiz/src/error.rs b/termwiz/src/error.rs index 175d96161..a7c1cc34d 100644 --- a/termwiz/src/error.rs +++ b/termwiz/src/error.rs @@ -48,9 +48,6 @@ pub enum InternalError { #[error(transparent)] Utf8(#[from] std::str::Utf8Error), - #[error(transparent)] - Base64(#[from] base64::DecodeError), - #[error(transparent)] ParseFloat(#[from] std::num::ParseFloatError), diff --git a/wezterm-dynamic/Cargo.toml b/wezterm-dynamic/Cargo.toml index 957db809d..8eeef8cba 100644 --- a/wezterm-dynamic/Cargo.toml +++ b/wezterm-dynamic/Cargo.toml @@ -6,11 +6,14 @@ repository = "https://github.com/wezterm/wezterm" description = "config serialization for wezterm via dynamic json-like data values" license = "MIT" +[features] +std = ["thiserror/std", "dep:strsim", "ordered-float/std"] + [dependencies] log.workspace = true -ordered-float.workspace = true -strsim.workspace = true -thiserror.workspace = true +ordered-float = {workspace = true, features=["libm"]} +strsim = {workspace = true, optional=true} +thiserror = {version="2.0", default-features=false} wezterm-dynamic-derive.workspace = true [dev-dependencies] diff --git a/wezterm-dynamic/derive/src/fromdynamic.rs b/wezterm-dynamic/derive/src/fromdynamic.rs index 505430c80..19972d73b 100644 --- a/wezterm-dynamic/derive/src/fromdynamic.rs +++ b/wezterm-dynamic/derive/src/fromdynamic.rs @@ -93,7 +93,7 @@ fn derive_struct(input: &DeriveInput, fields: &FieldsNamed) -> Result { quote!( - use std::convert::TryFrom; + use core::convert::TryFrom; let target = <#try_from>::from_dynamic(value, options)?; <#ident>::try_from(target).map_err(|e| wezterm_dynamic::Error::Message(format!("{:#}", e))) ) @@ -116,7 +116,7 @@ fn derive_struct(input: &DeriveInput, fields: &FieldsNamed) -> Result std::result::Result { + fn from_dynamic(value: &wezterm_dynamic::Value, options: wezterm_dynamic::FromDynamicOptions) -> core::result::Result { use wezterm_dynamic::{Value, BorrowedKey, ObjectKeyTrait}; #adjust_options #from_dynamic @@ -157,7 +157,7 @@ fn derive_enum(input: &DeriveInput, enumeration: &DataEnum) -> Result { quote!( - use std::convert::TryFrom; + use core::convert::TryFrom; let target = <#try_from>::from_dynamic(value, options)?; <#ident>::try_from(target).map_err(|e| wezterm_dynamic::Error::Message(format!("{:#}", e))) ) @@ -311,7 +311,7 @@ fn derive_enum(input: &DeriveInput, enumeration: &DataEnum) -> Result std::result::Result { + fn from_dynamic(value: &wezterm_dynamic::Value, options: wezterm_dynamic::FromDynamicOptions) -> core::result::Result { use wezterm_dynamic::{Value, BorrowedKey, ObjectKeyTrait}; #from_dynamic } diff --git a/wezterm-dynamic/src/array.rs b/wezterm-dynamic/src/array.rs index a6c490186..7376a3879 100644 --- a/wezterm-dynamic/src/array.rs +++ b/wezterm-dynamic/src/array.rs @@ -1,7 +1,12 @@ use crate::Value; +use core::cmp::Ordering; use core::iter::FromIterator; use core::ops::{Deref, DerefMut}; -use std::cmp::Ordering; + +#[cfg(not(feature = "std"))] +extern crate alloc; + +use alloc::vec::Vec; #[derive(Clone, Debug, Default, PartialEq, Eq, Hash)] pub struct Array { diff --git a/wezterm-dynamic/src/drop.rs b/wezterm-dynamic/src/drop.rs index f68464f0a..a12c01284 100644 --- a/wezterm-dynamic/src/drop.rs +++ b/wezterm-dynamic/src/drop.rs @@ -1,5 +1,10 @@ use crate::Value; +#[cfg(not(feature = "std"))] +extern crate alloc; + +use alloc::vec::Vec; + /// Non-recursive drop implementation. /// This is taken from dtolnay's miniserde library /// and is reproduced here under the terms of its diff --git a/wezterm-dynamic/src/error.rs b/wezterm-dynamic/src/error.rs index 077a3920b..e224e0856 100644 --- a/wezterm-dynamic/src/error.rs +++ b/wezterm-dynamic/src/error.rs @@ -1,14 +1,25 @@ use crate::fromdynamic::{FromDynamicOptions, UnknownFieldAction}; use crate::object::Object; use crate::value::Value; +#[cfg(feature = "std")] use std::cell::RefCell; +#[cfg(feature = "std")] use std::rc::Rc; use thiserror::Error; +#[cfg(not(feature = "std"))] +extern crate alloc; + +use alloc::string::{String, ToString}; +use alloc::vec::Vec; +use alloc::{format, vec}; + +#[cfg(feature = "std")] pub trait WarningCollector { fn warn(&self, message: String); } +#[cfg(feature = "std")] thread_local! { static WARNING_COLLECTOR: RefCell>> = RefCell::new(None); } @@ -72,6 +83,7 @@ pub enum Error { impl Error { /// Log a warning; if a warning collector is set for the current thread, /// use it, otherwise, log a regular warning message. + #[cfg(feature = "std")] pub fn warn(message: String) { WARNING_COLLECTOR.with(|collector| { let collector = collector.borrow(); @@ -83,6 +95,7 @@ impl Error { }); } + #[cfg(feature = "std")] pub fn capture_warnings T, T>(f: F) -> (T, Vec) { let warnings = Rc::new(RefCell::new(vec![])); @@ -109,6 +122,7 @@ impl Error { } /// Replace the warning collector for the current thread + #[cfg(feature = "std")] fn set_warning_collector(c: T) { WARNING_COLLECTOR.with(|collector| { collector.borrow_mut().replace(Box::new(c)); @@ -116,6 +130,7 @@ impl Error { } /// Clear the warning collector for the current thread + #[cfg(feature = "std")] fn clear_warning_collector() { WARNING_COLLECTOR.with(|collector| { collector.borrow_mut().take(); @@ -127,7 +142,7 @@ impl Error { object: &crate::Object, possible: &'static [&'static str], ) -> Vec { - let mut errors = vec![]; + let mut errors = Vec::new(); for key in object.keys() { match key { @@ -170,6 +185,7 @@ impl Error { match options.deprecated_fields { UnknownFieldAction::Deny => Err(err), UnknownFieldAction::Warn => { + #[cfg(feature = "std")] Self::warn(format!("{:#}", err)); Ok(()) } @@ -192,11 +208,15 @@ impl Error { return Ok(()); } - let show_warning = options.unknown_fields == UnknownFieldAction::Warn || errors.len() > 1; + #[cfg(feature = "std")] + { + let show_warning = + options.unknown_fields == UnknownFieldAction::Warn || errors.len() > 1; - if show_warning { - for err in &errors { - Self::warn(format!("{:#}", err)); + if show_warning { + for err in &errors { + Self::warn(format!("{:#}", err)); + } } } @@ -209,6 +229,12 @@ impl Error { Ok(()) } + #[cfg(not(feature = "std"))] + fn possible_matches(_used: &str, _possible: &'static [&'static str]) -> &'static str { + "" + } + + #[cfg(feature = "std")] fn possible_matches(used: &str, possible: &'static [&'static str]) -> String { // Produce similar field name list let mut candidates: Vec<(f64, &str)> = possible @@ -216,7 +242,7 @@ impl Error { .map(|&name| (strsim::jaro_winkler(used, name), name)) .filter(|(confidence, _)| *confidence > 0.8) .collect(); - candidates.sort_by(|a, b| b.0.partial_cmp(&a.0).unwrap_or(std::cmp::Ordering::Equal)); + candidates.sort_by(|a, b| b.0.partial_cmp(&a.0).unwrap_or(core::cmp::Ordering::Equal)); let suggestions: Vec<&str> = candidates.into_iter().map(|(_, name)| name).collect(); // Filter the suggestions out of the allowed field names diff --git a/wezterm-dynamic/src/fromdynamic.rs b/wezterm-dynamic/src/fromdynamic.rs index 2186fd683..2cb019714 100644 --- a/wezterm-dynamic/src/fromdynamic.rs +++ b/wezterm-dynamic/src/fromdynamic.rs @@ -1,9 +1,20 @@ use crate::error::Error; use crate::value::Value; +use core::convert::TryInto; +#[cfg(feature = "std")] +use core::hash::Hash; use ordered_float::OrderedFloat; +#[cfg(feature = "std")] use std::collections::HashMap; -use std::convert::TryInto; -use std::hash::Hash; + +#[cfg(not(feature = "std"))] +extern crate alloc; + +use alloc::boxed::Box; +use alloc::collections::BTreeMap; +use alloc::string::{String, ToString}; +use alloc::sync::Arc; +use alloc::vec::Vec; /// Specify how FromDynamic will treat unknown fields /// when converting from Value to a given target type @@ -55,6 +66,7 @@ impl FromDynamic for ordered_float::NotNan { } } +#[cfg(feature = "std")] impl FromDynamic for std::time::Duration { fn from_dynamic(value: &Value, options: FromDynamicOptions) -> Result { let f = f64::from_dynamic(value, options)?; @@ -69,10 +81,10 @@ impl FromDynamic for Box { } } -impl FromDynamic for std::sync::Arc { +impl FromDynamic for Arc { fn from_dynamic(value: &Value, options: FromDynamicOptions) -> Result { let value = T::from_dynamic(value, options)?; - Ok(std::sync::Arc::new(value)) + Ok(Arc::new(value)) } } @@ -106,6 +118,25 @@ impl FromDynamic for [T; N] { } } +impl FromDynamic for BTreeMap { + fn from_dynamic(value: &Value, options: FromDynamicOptions) -> Result { + match value { + Value::Object(obj) => { + let mut map = BTreeMap::new(); + for (k, v) in obj.iter() { + map.insert(K::from_dynamic(k, options)?, T::from_dynamic(v, options)?); + } + Ok(map) + } + other => Err(Error::NoConversion { + source_type: other.variant_name().to_string(), + dest_type: "BTreeMap", + }), + } + } +} + +#[cfg(feature = "std")] impl FromDynamic for HashMap { fn from_dynamic(value: &Value, options: FromDynamicOptions) -> Result { match value { @@ -134,7 +165,7 @@ impl FromDynamic for Vec { // lua uses tables for everything; we can end up here if we got an empty // table and treated it as an object. Allow that to stand-in for an empty // array instead. - Value::Object(obj) if obj.is_empty() => Ok(vec![]), + Value::Object(obj) if obj.is_empty() => Ok(Vec::new()), other => Err(Error::NoConversion { source_type: other.variant_name().to_string(), dest_type: "Vec", @@ -167,6 +198,7 @@ impl FromDynamic for bool { } } +#[cfg(feature = "std")] impl FromDynamic for std::path::PathBuf { fn from_dynamic(value: &Value, _options: FromDynamicOptions) -> Result { match value { diff --git a/wezterm-dynamic/src/lib.rs b/wezterm-dynamic/src/lib.rs index 9e6876661..a659f1a80 100644 --- a/wezterm-dynamic/src/lib.rs +++ b/wezterm-dynamic/src/lib.rs @@ -1,6 +1,10 @@ //! Types for representing Rust types in a more dynamic form //! that is similar to JSON or Lua values. +#![cfg_attr(not(feature = "std"), no_std)] +#![cfg_attr(not(feature = "std"), macro_use)] +extern crate alloc; + mod array; mod drop; mod error; diff --git a/wezterm-dynamic/src/object.rs b/wezterm-dynamic/src/object.rs index 9d3c9858a..8a5a704ac 100644 --- a/wezterm-dynamic/src/object.rs +++ b/wezterm-dynamic/src/object.rs @@ -1,7 +1,12 @@ use crate::Value; -use std::cmp::Ordering; -use std::collections::BTreeMap; -use std::ops::{Deref, DerefMut}; +use core::cmp::Ordering; +use core::ops::{Deref, DerefMut}; + +#[cfg(not(feature = "std"))] +extern crate alloc; + +use alloc::borrow::Borrow; +use alloc::collections::BTreeMap; /// We'd like to avoid allocating when resolving struct fields, /// so this is the borrowed version of Value. @@ -33,7 +38,7 @@ impl<'a> ObjectKeyTrait for BorrowedKey<'a> { } } -impl<'a> std::borrow::Borrow for Value { +impl<'a> Borrow for Value { fn borrow(&self) -> &(dyn ObjectKeyTrait + 'a) { self } @@ -59,8 +64,8 @@ impl<'a> Ord for (dyn ObjectKeyTrait + 'a) { } } -impl<'a> std::hash::Hash for (dyn ObjectKeyTrait + 'a) { - fn hash(&self, state: &mut H) { +impl<'a> core::hash::Hash for (dyn ObjectKeyTrait + 'a) { + fn hash(&self, state: &mut H) { self.key().hash(state) } } @@ -77,8 +82,8 @@ impl Object { } } -impl std::fmt::Debug for Object { - fn fmt(&self, fmt: &mut std::fmt::Formatter) -> std::fmt::Result { +impl core::fmt::Debug for Object { + fn fmt(&self, fmt: &mut core::fmt::Formatter) -> core::fmt::Result { self.inner.fmt(fmt) } } @@ -99,7 +104,7 @@ impl PartialOrd for Object { impl Drop for Object { fn drop(&mut self) { - for (_, child) in std::mem::take(&mut self.inner) { + for (_, child) in core::mem::take(&mut self.inner) { crate::drop::safely(child); } } diff --git a/wezterm-dynamic/src/todynamic.rs b/wezterm-dynamic/src/todynamic.rs index 5de29e9a5..c3d6a4707 100644 --- a/wezterm-dynamic/src/todynamic.rs +++ b/wezterm-dynamic/src/todynamic.rs @@ -1,7 +1,17 @@ use crate::object::Object; use crate::value::Value; use ordered_float::OrderedFloat; -use std::collections::{BTreeMap, HashMap}; +#[cfg(feature = "std")] +use std::collections::HashMap; + +#[cfg(not(feature = "std"))] +extern crate alloc; + +use alloc::boxed::Box; +use alloc::collections::BTreeMap; +use alloc::string::{String, ToString}; +use alloc::sync::Arc; +use alloc::vec::Vec; /// The ToDynamic trait allows a type to emit a representation of itself /// as the Value type. @@ -33,12 +43,25 @@ impl ToDynamic for ordered_float::NotNan { } } +#[cfg(feature = "std")] impl ToDynamic for std::time::Duration { fn to_dynamic(&self) -> Value { Value::F64(OrderedFloat(self.as_secs_f64())) } } +impl ToDynamic for BTreeMap { + fn to_dynamic(&self) -> Value { + Value::Object( + self.iter() + .map(|(k, v)| (k.to_dynamic(), v.to_dynamic())) + .collect::>() + .into(), + ) + } +} + +#[cfg(feature = "std")] impl ToDynamic for HashMap { fn to_dynamic(&self) -> Value { Value::Object( @@ -50,7 +73,7 @@ impl ToDynamic for HashMap ToDynamic for std::sync::Arc { +impl ToDynamic for Arc { fn to_dynamic(&self) -> Value { self.as_ref().to_dynamic() } @@ -111,6 +134,7 @@ impl ToDynamic for str { } } +#[cfg(feature = "std")] impl ToDynamic for std::path::PathBuf { fn to_dynamic(&self) -> Value { Value::String(self.to_string_lossy().to_string()) diff --git a/wezterm-dynamic/src/value.rs b/wezterm-dynamic/src/value.rs index a675dd63d..60ae192c2 100644 --- a/wezterm-dynamic/src/value.rs +++ b/wezterm-dynamic/src/value.rs @@ -1,7 +1,14 @@ use crate::array::Array; use crate::object::Object; +#[cfg(not(feature = "std"))] +use ordered_float::FloatCore; use ordered_float::OrderedFloat; +#[cfg(not(feature = "std"))] +extern crate alloc; + +use alloc::string::String; + /// Represents values of various possible other types. /// Value is intended to be convertible to the same set /// of types as Lua and is a superset of the types possible @@ -24,8 +31,8 @@ impl Default for Value { } } -impl std::fmt::Debug for Value { - fn fmt(&self, fmt: &mut std::fmt::Formatter) -> std::fmt::Result { +impl core::fmt::Debug for Value { + fn fmt(&self, fmt: &mut core::fmt::Formatter) -> core::fmt::Result { match self { Self::String(s) => fmt.write_fmt(format_args!("{:?}", s)), Self::Null => fmt.write_str("nil"), diff --git a/wezterm-escape-parser/Cargo.toml b/wezterm-escape-parser/Cargo.toml index 681f4af5a..9f1438090 100644 --- a/wezterm-escape-parser/Cargo.toml +++ b/wezterm-escape-parser/Cargo.toml @@ -10,9 +10,9 @@ documentation = "https://docs.rs/wezterm-escape-parser" keywords = ["terminal", "escape", "parser"] [dependencies] -base64.workspace = true +base64 = {workspace = true, default-features=false, features=["alloc"]} bitflags = "2.0" -hex.workspace = true +hex = {workspace = true, default-features=false, features=["alloc"]} image = {workspace =true, optional=true } log.workspace = true nix = { workspace=true, optional=true, features=["mman", "fs"] } @@ -23,14 +23,15 @@ pest = {workspace = true, optional=true} pest_derive = {workspace = true, optional=true} serde = {workspace=true, optional=true} sha2 = {workspace=true, optional=true} -thiserror.workspace = true -vtparse.workspace = true +thiserror = {version = "2.0", default-features=false } +vtparse = {workspace = true, features=["alloc"]} wezterm-blob-leases = {workspace=true, optional=true} wezterm-color-types.workspace = true wezterm-dynamic.workspace = true -wezterm-input-types.workspace = true +wezterm-input-types = {workspace = true, default-features=false} [features] +std = ["vtparse/std", "thiserror/std", "wezterm-input-types/std", "hex/std"] kitty-shm = ["dep:nix"] use_serde = ["dep:serde", "wezterm-color-types/use_serde", "wezterm-blob-leases/serde", "bitflags/serde", "wezterm-input-types/serde"] use_image = ["image", "dep:image"] diff --git a/wezterm-escape-parser/src/allocate.rs b/wezterm-escape-parser/src/allocate.rs new file mode 100644 index 000000000..64f464c41 --- /dev/null +++ b/wezterm-escape-parser/src/allocate.rs @@ -0,0 +1,13 @@ +#[cfg(not(feature = "std"))] +extern crate alloc; + +pub use alloc::borrow::ToOwned; +pub use alloc::boxed::Box; +pub use alloc::collections::BTreeMap; +pub use alloc::string::{String, ToString}; +pub use alloc::vec::Vec; + +#[cfg(not(feature = "std"))] +pub use alloc::collections::BTreeMap as HashMap; +#[cfg(feature = "std")] +pub use std::collections::HashMap; diff --git a/wezterm-escape-parser/src/apc.rs b/wezterm-escape-parser/src/apc.rs index abaf759c7..7e5f0264e 100644 --- a/wezterm-escape-parser/src/apc.rs +++ b/wezterm-escape-parser/src/apc.rs @@ -1,20 +1,16 @@ +use crate::allocate::*; use crate::osc::{base64_decode, base64_encode}; -use std::collections::BTreeMap; -use std::fmt::{Display, Error as FmtError, Formatter}; +use core::fmt::{Display, Error as FmtError, Formatter}; fn get<'a>(keys: &BTreeMap<&str, &'a str>, k: &str) -> Option<&'a str> { keys.get(k).map(|&s| s) } -fn geti(keys: &BTreeMap<&str, &str>, k: &str) -> Option { +fn geti(keys: &BTreeMap<&str, &str>, k: &str) -> Option { get(keys, k).and_then(|s| s.parse().ok()) } -fn set( - keys: &mut BTreeMap<&'static str, String>, - k: &'static str, - v: &Option, -) { +fn set(keys: &mut BTreeMap<&'static str, String>, k: &'static str, v: &Option) { if let Some(v) = v { keys.insert(k, v.to_string()); } @@ -68,8 +64,8 @@ pub enum KittyImageData { }, } -impl std::fmt::Debug for KittyImageData { - fn fmt(&self, fmt: &mut Formatter) -> std::fmt::Result { +impl core::fmt::Debug for KittyImageData { + fn fmt(&self, fmt: &mut Formatter) -> core::fmt::Result { match self { Self::Direct(data) => write!(fmt, "Direct({} bytes of data)", data.len()), Self::DirectBin(data) => write!(fmt, "DirectBin({} bytes of data)", data.len()), @@ -1068,7 +1064,7 @@ impl KittyImage { } let mut keys_payload_iter = data[1..].splitn(2, |&d| d == b';'); let keys = keys_payload_iter.next()?; - let key_string = std::str::from_utf8(keys).ok()?; + let key_string = core::str::from_utf8(keys).ok()?; let mut keys: BTreeMap<&str, &str> = BTreeMap::new(); for k_v in key_string.split(',') { let mut k_v = k_v.splitn(2, '='); diff --git a/wezterm-escape-parser/src/color.rs b/wezterm-escape-parser/src/color.rs index b83f5f952..ee8e18264 100644 --- a/wezterm-escape-parser/src/color.rs +++ b/wezterm-escape-parser/src/color.rs @@ -4,6 +4,8 @@ use serde::{Deserialize, Deserializer, Serialize, Serializer}; pub use wezterm_color_types::{LinearRgba, SrgbaTuple}; use wezterm_dynamic::{FromDynamic, FromDynamicOptions, ToDynamic, Value}; +use crate::allocate::*; + #[derive(Debug, Clone, Copy, FromPrimitive, PartialEq, Eq, FromDynamic, ToDynamic)] #[cfg_attr(feature = "use_serde", derive(Serialize, Deserialize))] #[repr(u8)] diff --git a/wezterm-escape-parser/src/csi.rs b/wezterm-escape-parser/src/csi.rs index 1f2799fcf..08bf18b52 100644 --- a/wezterm-escape-parser/src/csi.rs +++ b/wezterm-escape-parser/src/csi.rs @@ -1,15 +1,17 @@ use super::OneBased; use crate::color::{AnsiColor, ColorSpec, RgbColor, SrgbaTuple}; use bitflags::bitflags; +use core::convert::TryInto; +use core::fmt::{Display, Error as FmtError, Formatter}; use num_derive::*; use num_traits::{FromPrimitive, ToPrimitive}; #[cfg(feature = "use_serde")] use serde::{Deserialize, Serialize}; -use std::convert::TryInto; -use std::fmt::{Display, Error as FmtError, Formatter}; use wezterm_dynamic::{FromDynamic, ToDynamic}; use wezterm_input_types::Modifiers; +use crate::allocate::*; + pub use vtparse::CsiParam; /// Specify whether you want to slowly or rapidly annoy your users diff --git a/wezterm-escape-parser/src/error.rs b/wezterm-escape-parser/src/error.rs index 48555495b..d10c6c9c4 100644 --- a/wezterm-escape-parser/src/error.rs +++ b/wezterm-escape-parser/src/error.rs @@ -1,4 +1,6 @@ -use std::fmt::Display; +use core::fmt::Display; + +use crate::allocate::*; /// The termwiz Error type encapsulates a range of internal /// errors in an opaque manner. You can use the `source` @@ -33,28 +35,27 @@ where #[doc(hidden)] pub enum InternalError { #[error(transparent)] - Fmt(#[from] std::fmt::Error), + Fmt(#[from] core::fmt::Error), + #[cfg(feature = "std")] #[error(transparent)] Io(#[from] std::io::Error), + #[cfg(feature = "std")] #[error(transparent)] FromUtf8(#[from] std::string::FromUtf8Error), + #[cfg(not(feature = "std"))] + #[error(transparent)] + FromUtf8(#[from] alloc::string::FromUtf8Error), #[error(transparent)] - Utf8(#[from] std::str::Utf8Error), + Utf8(#[from] core::str::Utf8Error), #[error(transparent)] - Base64(#[from] base64::DecodeError), + ParseFloat(#[from] core::num::ParseFloatError), #[error(transparent)] - ParseFloat(#[from] std::num::ParseFloatError), - - #[error(transparent)] - ParseInt(#[from] std::num::ParseIntError), - - #[error(transparent)] - FloatIsNan(#[from] ordered_float::FloatIsNan), + ParseInt(#[from] core::num::ParseIntError), #[error("{0}")] StringErr(#[from] StringWrap), @@ -74,7 +75,7 @@ pub enum InternalError { #[error("{}", .context)] Context { context: String, - source: Box, + source: Box, }, } @@ -151,9 +152,9 @@ pub trait Context { F: FnOnce() -> C; } -impl Context for std::result::Result +impl Context for core::result::Result where - E: std::error::Error + Send + Sync + 'static, + E: core::error::Error + Send + Sync + 'static, { fn context(self, context: C) -> Result where diff --git a/wezterm-escape-parser/src/esc.rs b/wezterm-escape-parser/src/esc.rs index d28143e3a..16128c159 100644 --- a/wezterm-escape-parser/src/esc.rs +++ b/wezterm-escape-parser/src/esc.rs @@ -1,6 +1,6 @@ +use core::fmt::{Display, Error as FmtError, Formatter, Write as FmtWrite}; use num_derive::*; use num_traits::{FromPrimitive, ToPrimitive}; -use std::fmt::{Display, Error as FmtError, Formatter, Write as FmtWrite}; #[derive(Debug, Clone, PartialEq, Eq)] pub enum Esc { diff --git a/wezterm-escape-parser/src/hyperlink.rs b/wezterm-escape-parser/src/hyperlink.rs index 73779c5d3..510377a2a 100644 --- a/wezterm-escape-parser/src/hyperlink.rs +++ b/wezterm-escape-parser/src/hyperlink.rs @@ -1,10 +1,11 @@ use crate::{Result, ensure, format_err}; +use core::hash::{Hash, Hasher}; #[cfg(feature = "use_serde")] use serde::{Deserialize, Serialize}; -use std::collections::HashMap; -use std::hash::{Hash, Hasher}; use wezterm_dynamic::{FromDynamic, ToDynamic}; +use crate::allocate::*; + #[cfg_attr(feature = "use_serde", derive(Serialize, Deserialize))] #[derive(Debug, Clone, PartialEq, Eq, FromDynamic, ToDynamic)] pub struct Hyperlink { diff --git a/wezterm-escape-parser/src/lib.rs b/wezterm-escape-parser/src/lib.rs index c93bcea11..70b5f0ef9 100644 --- a/wezterm-escape-parser/src/lib.rs +++ b/wezterm-escape-parser/src/lib.rs @@ -2,6 +2,7 @@ // using derive(FromPrimitive) #![allow(clippy::useless_attribute)] #![allow(clippy::upper_case_acronyms)] +#![cfg_attr(not(feature = "std"), no_std)] //! This module provides the ability to parse escape sequences and attach //! semantic meaning to them. It can also encode the semantic values as //! escape sequences. It provides encoding and decoding functionality @@ -12,6 +13,12 @@ use core::fmt::{Display, Formatter, Result as FmtResult, Write as FmtWrite}; use num_derive::*; use wezterm_color_types::LinearRgba; +#[cfg_attr(not(feature = "std"), macro_use)] +extern crate alloc; + +mod allocate; +use allocate::*; + pub mod apc; pub mod color; pub mod csi; @@ -367,8 +374,8 @@ impl Display for Sixel { (3, 1) => 3, (1, 1) => 7, _ => { - eprintln!("bad pad/pan combo: {:?}", self); - return Err(std::fmt::Error); + log::error!("bad pad/pan combo: {:?}", self); + return Err(core::fmt::Error); } }, if self.background_is_transparent { 1 } else { 0 }, diff --git a/wezterm-escape-parser/src/osc.rs b/wezterm-escape-parser/src/osc.rs index 1bb37d75c..1060214d8 100644 --- a/wezterm-escape-parser/src/osc.rs +++ b/wezterm-escape-parser/src/osc.rs @@ -1,17 +1,19 @@ use crate::color::SrgbaTuple; pub use crate::hyperlink::Hyperlink; -use crate::{Result, bail, ensure}; +use crate::{Result, bail, ensure, format_err}; use base64::Engine; use bitflags::bitflags; +use core::fmt::{Display, Error as FmtError, Formatter, Result as FmtResult}; +use core::str; +use core::str::FromStr; use num_derive::*; use num_traits::FromPrimitive; use ordered_float::NotNan; -use std::collections::HashMap; -use std::fmt::{Display, Error as FmtError, Formatter, Result as FmtResult}; -use std::str; -use std::str::FromStr; +#[cfg(feature = "std")] use std::sync::LazyLock; +use crate::allocate::*; + #[derive(Debug, Clone, PartialEq)] pub enum ColorOrQuery { Color(SrgbaTuple), @@ -409,6 +411,7 @@ pub enum OperatingSystemCommandCode { } impl OscMap { +#[cfg(feature = "std")] fn new() -> Self { let mut code_to_variant = HashMap::new(); let mut variant_to_code = HashMap::new(); @@ -425,6 +428,28 @@ impl OscMap { variant_to_code, } } + +#[cfg(not(feature = "std"))] + fn linear_search_code(code: &str) -> Option { + use OperatingSystemCommandCode::*; + match code { + $( + $value => Some($label), + )* + _ => None, + } + } + +#[cfg(not(feature = "std"))] + fn linear_search_variant(v: &OperatingSystemCommandCode) -> &'static str { + use OperatingSystemCommandCode::*; + match *v { + $( + $label => $value, + )* + } + } + } }; } @@ -480,12 +505,16 @@ osc_entries!( ); struct OscMap { + #[cfg(feature = "std")] code_to_variant: HashMap<&'static str, OperatingSystemCommandCode>, + #[cfg(feature = "std")] variant_to_code: HashMap, } +#[cfg(feature = "std")] static OSC_MAP: LazyLock = LazyLock::new(OscMap::new); +#[cfg(feature = "std")] impl OperatingSystemCommandCode { fn from_code(code: &str) -> Option { OSC_MAP.code_to_variant.get(code).copied() @@ -496,6 +525,17 @@ impl OperatingSystemCommandCode { } } +#[cfg(not(feature = "std"))] +impl OperatingSystemCommandCode { + fn from_code(code: &str) -> Option { + OscMap::linear_search_code(code) + } + + fn as_code(self) -> &'static str { + OscMap::linear_search_variant(&self) + } +} + impl Display for OperatingSystemCommand { fn fmt(&self, f: &mut Formatter) -> FmtResult { write!(f, "\x1b]")?; @@ -592,7 +632,7 @@ pub enum FinalTermClick { SmartVertical, } -impl std::convert::TryFrom<&str> for FinalTermClick { +impl core::convert::TryFrom<&str> for FinalTermClick { type Error = crate::Error; fn try_from(s: &str) -> Result { match s { @@ -635,7 +675,7 @@ impl Default for FinalTermPromptKind { } } -impl std::convert::TryFrom<&str> for FinalTermPromptKind { +impl core::convert::TryFrom<&str> for FinalTermPromptKind { type Error = crate::Error; fn try_from(s: &str) -> Result { match s { @@ -722,7 +762,7 @@ impl FinalTermSemanticPrompt { single!(MarkEndOfPromptAndStartOfInputUntilEndOfLine, "I"); let mut params = HashMap::new(); - use std::convert::TryInto; + use core::convert::TryInto; for s in osc.iter().skip(if param == "D" { 3 } else { 2 }) { if let Some(equal) = s.iter().position(|c| *c == b'=') { @@ -1021,7 +1061,7 @@ impl Display for ITermFileData { fn fmt(&self, f: &mut Formatter) -> FmtResult { write!(f, "File")?; let mut sep = "="; - let emit_sep = |sep, f: &mut Formatter| -> std::result::Result<&str, FmtError> { + let emit_sep = |sep, f: &mut Formatter| -> core::result::Result<&str, FmtError> { write!(f, "{}", sep)?; Ok(";") }; @@ -1089,7 +1129,7 @@ impl Display for ITermDimension { } } -impl std::str::FromStr for ITermDimension { +impl core::str::FromStr for ITermDimension { type Err = crate::Error; fn from_str(s: &str) -> Result { ITermDimension::parse(s) @@ -1203,8 +1243,9 @@ impl ITermProprietary { if osc.len() == 3 && keyword == "ReportCellSize" && p1.is_some() { if let Some(p1) = p1 { return Ok(ITermProprietary::ReportCellSize { - height_pixels: NotNan::new(p1.parse()?)?, - width_pixels: NotNan::new(String::from_utf8_lossy(osc[2]).parse()?)?, + height_pixels: NotNan::new(p1.parse()?).map_err(not_nan_err)?, + width_pixels: NotNan::new(String::from_utf8_lossy(osc[2]).parse()?) + .map_err(not_nan_err)?, scale: None, }); } @@ -1212,9 +1253,13 @@ impl ITermProprietary { if osc.len() == 4 && keyword == "ReportCellSize" && p1.is_some() { if let Some(p1) = p1 { return Ok(ITermProprietary::ReportCellSize { - height_pixels: NotNan::new(p1.parse()?)?, - width_pixels: NotNan::new(String::from_utf8_lossy(osc[2]).parse()?)?, - scale: Some(NotNan::new(String::from_utf8_lossy(osc[3]).parse()?)?), + height_pixels: NotNan::new(p1.parse()?).map_err(not_nan_err)?, + width_pixels: NotNan::new(String::from_utf8_lossy(osc[2]).parse()?) + .map_err(not_nan_err)?, + scale: Some( + NotNan::new(String::from_utf8_lossy(osc[3]).parse()?) + .map_err(not_nan_err)?, + ), }); } } @@ -1273,15 +1318,14 @@ pub(crate) fn base64_encode>(s: T) -> String { } /// base64::decode is deprecated, so make a less frustrating helper -pub(crate) fn base64_decode>( - s: T, -) -> std::result::Result, base64::DecodeError> { +pub(crate) fn base64_decode>(s: T) -> Result> { use base64::engine::{GeneralPurpose, GeneralPurposeConfig}; GeneralPurpose::new( &base64::alphabet::STANDARD, GeneralPurposeConfig::new().with_decode_allow_trailing_bits(true), ) .decode(s) + .map_err(|err| crate::format_err!("base64_decode: {:#}", err)) } impl Display for ITermProprietary { @@ -1334,6 +1378,10 @@ impl Display for ITermProprietary { } } +fn not_nan_err(err: ordered_float::FloatIsNan) -> crate::Error { + format_err!("{:#}", err) +} + #[cfg(test)] mod test { use super::*; diff --git a/wezterm-escape-parser/src/parser/mod.rs b/wezterm-escape-parser/src/parser/mod.rs index 2cdf5016f..d619c4cb5 100644 --- a/wezterm-escape-parser/src/parser/mod.rs +++ b/wezterm-escape-parser/src/parser/mod.rs @@ -5,13 +5,15 @@ use crate::{ Action, CSI, DeviceControlMode, EnterDeviceControlMode, Esc, OperatingSystemCommand, ShortDeviceControl, }; +#[cfg(feature = "tmux_cc")] +use core::borrow::BorrowMut; +use core::cell::RefCell; use log::error; use num_traits::FromPrimitive; -#[cfg(feature = "tmux_cc")] -use std::borrow::BorrowMut; -use std::cell::RefCell; use vtparse::{CsiParam, VTActor, VTParser}; +use crate::allocate::*; + mod sixel; use sixel::SixelBuilder; diff --git a/wezterm-input-types/Cargo.toml b/wezterm-input-types/Cargo.toml index c223aa4ce..ba6a527ef 100644 --- a/wezterm-input-types/Cargo.toml +++ b/wezterm-input-types/Cargo.toml @@ -16,4 +16,5 @@ serde = {workspace=true, features = ["rc", "derive"], optional=true} wezterm-dynamic.workspace = true [features] -default = ["serde"] +default = ["serde", "std"] +std = ["serde/std", "euclid/std"] diff --git a/wezterm-input-types/src/lib.rs b/wezterm-input-types/src/lib.rs index 93383b014..833aa22b1 100644 --- a/wezterm-input-types/src/lib.rs +++ b/wezterm-input-types/src/lib.rs @@ -1,13 +1,25 @@ -use bitflags::*; +#![cfg_attr(not(feature = "std"), no_std)] + #[cfg(feature = "serde")] -use serde::*; -use std::collections::HashMap; -use std::convert::TryFrom; -use std::fmt::Write; -use std::sync::atomic::AtomicBool; -use std::sync::{Arc, LazyLock}; +use ::serde::*; +use alloc::sync::Arc; +use bitflags::*; +use core::convert::TryFrom; +use core::fmt::Write; +use core::sync::atomic::AtomicBool; +#[cfg(feature = "std")] +use std::sync::LazyLock; use wezterm_dynamic::{FromDynamic, ToDynamic}; +extern crate alloc; + +use alloc::string::{String, ToString}; +use alloc::vec::Vec; +use alloc::{format, vec}; + +#[cfg(feature = "std")] +use std::collections::HashMap; + pub struct PixelUnit; pub struct ScreenPixelUnit; pub type Point = euclid::Point2D; @@ -317,12 +329,12 @@ impl KeyCode { impl TryFrom<&str> for KeyCode { type Error = String; - fn try_from(s: &str) -> std::result::Result { + fn try_from(s: &str) -> core::result::Result { macro_rules! m { ($($val:ident),* $(,)?) => { match s { $( - stringify!($val) => return Ok(Self::$val), + core::stringify!($val) => return Ok(Self::$val), )* _ => {} } @@ -994,17 +1006,19 @@ impl PhysKeyCode { } } - fn make_map() -> HashMap { - let mut map = HashMap::new(); - + fn for_each_code(mut func: impl FnMut(&str, Self) -> bool) { macro_rules! m { ($($val:ident),* $(,)?) => { $( - let key = stringify!($val).to_string(); + let key = stringify!($val); if key.len() == 1 { - map.insert(key.to_ascii_lowercase(), PhysKeyCode::$val); + if (func)(&key.to_ascii_lowercase(), PhysKeyCode::$val) { + return; + } + } + if (func)(key, PhysKeyCode::$val) { + return; } - map.insert(key, PhysKeyCode::$val); )* } } @@ -1118,20 +1132,37 @@ impl PhysKeyCode { Z, ); - map.insert("0".to_string(), PhysKeyCode::K0); - map.insert("1".to_string(), PhysKeyCode::K1); - map.insert("2".to_string(), PhysKeyCode::K2); - map.insert("3".to_string(), PhysKeyCode::K3); - map.insert("4".to_string(), PhysKeyCode::K4); - map.insert("5".to_string(), PhysKeyCode::K5); - map.insert("6".to_string(), PhysKeyCode::K6); - map.insert("7".to_string(), PhysKeyCode::K7); - map.insert("8".to_string(), PhysKeyCode::K8); - map.insert("9".to_string(), PhysKeyCode::K9); + for (label, value) in [ + ("0", PhysKeyCode::K0), + ("1", PhysKeyCode::K1), + ("2", PhysKeyCode::K2), + ("3", PhysKeyCode::K3), + ("4", PhysKeyCode::K4), + ("5", PhysKeyCode::K5), + ("6", PhysKeyCode::K6), + ("7", PhysKeyCode::K7), + ("8", PhysKeyCode::K8), + ("9", PhysKeyCode::K9), + ] { + if (func)(label, value) { + return; + } + } + } + + #[cfg(feature = "std")] + fn make_map() -> HashMap { + let mut map = HashMap::new(); + + Self::for_each_code(|label, code| { + map.insert(label.to_string(), code); + false + }); map } + #[cfg(feature = "std")] fn make_inv_map() -> HashMap { let mut map = HashMap::new(); for (k, v) in PHYSKEYCODE_MAP.iter() { @@ -1139,18 +1170,60 @@ impl PhysKeyCode { } map } + + fn name_to_code(name: &str) -> Option { + #[cfg(feature = "std")] + { + return PHYSKEYCODE_MAP.get(name).copied(); + } + #[cfg(not(feature = "std"))] + { + let mut result = None; + Self::for_each_code(|label, code| { + if label == name { + result.replace(code); + true + } else { + false + } + }); + result + } + } + + fn to_name(&self) -> Option { + #[cfg(feature = "std")] + { + return INV_PHYSKEYCODE_MAP.get(self).cloned(); + } + #[cfg(not(feature = "std"))] + { + let mut result = None; + Self::for_each_code(|label, code| { + if code == *self { + result.replace(label.to_string()); + true + } else { + false + } + }); + result + } + } } +#[cfg(feature = "std")] static PHYSKEYCODE_MAP: LazyLock> = LazyLock::new(PhysKeyCode::make_map); +#[cfg(feature = "std")] static INV_PHYSKEYCODE_MAP: LazyLock> = LazyLock::new(PhysKeyCode::make_inv_map); impl TryFrom<&str> for PhysKeyCode { type Error = String; - fn try_from(s: &str) -> std::result::Result { - if let Some(code) = PHYSKEYCODE_MAP.get(s) { - Ok(*code) + fn try_from(s: &str) -> core::result::Result { + if let Some(code) = Self::name_to_code(s) { + Ok(code) } else { Err(format!("invalid PhysKeyCode '{}'", s)) } @@ -1159,7 +1232,7 @@ impl TryFrom<&str> for PhysKeyCode { impl ToString for PhysKeyCode { fn to_string(&self) -> String { - if let Some(s) = INV_PHYSKEYCODE_MAP.get(self) { + if let Some(s) = self.to_name() { s.to_string() } else { format!("{:?}", self) @@ -1216,11 +1289,11 @@ impl Handled { } pub fn set_handled(&self) { - self.0.store(true, std::sync::atomic::Ordering::Relaxed); + self.0.store(true, core::sync::atomic::Ordering::Relaxed); } pub fn is_handled(&self) -> bool { - self.0.load(std::sync::atomic::Ordering::Relaxed) + self.0.load(core::sync::atomic::Ordering::Relaxed) } } @@ -2013,7 +2086,7 @@ impl Into for &WindowDecorations { impl TryFrom for WindowDecorations { type Error = String; - fn try_from(s: String) -> std::result::Result { + fn try_from(s: String) -> core::result::Result { let mut flags = Self::NONE; for ele in s.split('|') { let ele = ele.trim();