diff --git a/MIGRATION.md b/MIGRATION.md index 58f40c1..b628e45 100644 --- a/MIGRATION.md +++ b/MIGRATION.md @@ -5,7 +5,7 @@ Steps (This order is recommended so lsp doesn't scream at you lol) 1. Add the prelude! This new release includes traits! `use hyprland::prelude::*;` -2. Switch to the `HResult` Result type (`hyprland::shared::HResult`) +2. Switch to the `Result` type — it moved to the crate root: `use hyprland::Result;` (it was `hyprland::shared::HResult` in 0.2.5) 3. [Update your data fetcher functions to structs](#update-data-fetchers) 4. [Update your dispatch functions to structs](#update-dispatchers) 5. Switch all `String`s to `&str`s in your dispatchers diff --git a/README.md b/README.md index 8bfd21d..f637088 100644 --- a/README.md +++ b/README.md @@ -47,7 +47,7 @@ hyprland = { git = "https://github.com/hyprland-community/hyprland-rs", branch = ### What this crate provides -This crate provides 6 modules (+1 for shared things) +This crate provides 8 modules (+1 for shared things) - `data` for getting information on the compositor - `event_listener` which provides the `EventListener` struct for listening for events @@ -55,6 +55,8 @@ This crate provides 6 modules (+1 for shared things) - `keyword` for dealing with config option (aka keywords) - `config::binds` for changing binds (in future `config` might have config generation) - `ctl` for calling hyprctl commands +- `hyprpaper` for talking to hyprpaper +- `instance` for targeting a specific running Hyprland instance ## Example Usage diff --git a/src/ctl.rs b/src/ctl.rs index 77c670c..eb3db6f 100644 --- a/src/ctl.rs +++ b/src/ctl.rs @@ -142,7 +142,9 @@ pub mod output { backend: OutputBackends, name: Option<&str>, ) -> crate::Result<()> { - let name = name.unwrap_or_default(); + // Hyprland's syntax is `output create name=` - the + // `name=` prefix is part of the name, not a key we strip. + let name = name.map(|n| format!("name={n}")).unwrap_or_default(); instance.write_to_socket(command!(Empty, "output create {backend} {name}"))?; Ok(()) } @@ -166,7 +168,9 @@ pub mod output { backend: OutputBackends, name: Option<&str>, ) -> crate::Result<()> { - let name = name.unwrap_or_default(); + // Hyprland's syntax is `output create name=` - the + // `name=` prefix is part of the name, not a key we strip. + let name = name.map(|n| format!("name={n}")).unwrap_or_default(); instance .write_to_socket_async(command!(Empty, "output create {backend} {name}")) .await?; @@ -249,28 +253,28 @@ pub mod switch_xkb_layout { } } -/// Creates a error that Hyprland will display +/// Stuff related to setting an error message Hyprland displays pub mod set_error { use super::*; - /// Creates a error that Hyprland will display + /// Creates an error that Hyprland will display pub fn call(color: Color, msg: String) -> crate::Result<()> { instance_call(default_instance()?, color, msg) } - /// Creates a error that Hyprland will display + /// Creates an error that Hyprland will display pub fn instance_call(instance: &Instance, color: Color, msg: String) -> crate::Result<()> { instance.write_to_socket(command!(Empty, "seterror {color} {msg}"))?; Ok(()) } - /// Creates a error that Hyprland will display (async) + /// Creates an error that Hyprland will display (async) #[cfg(any(feature = "async-lite", feature = "tokio"))] pub async fn call_async(color: Color, msg: String) -> crate::Result<()> { instance_call_async(default_instance()?, color, msg).await } - /// Creates a error that Hyprland will display (async) + /// Creates an error that Hyprland will display (async) #[cfg(any(feature = "async-lite", feature = "tokio"))] pub async fn instance_call_async( instance: &Instance, @@ -328,7 +332,7 @@ pub mod notify { Ok(()) } - /// Creates a error that Hyprland will display (async) + /// Sends a notification to the user (async) #[cfg(any(feature = "async-lite", feature = "tokio"))] pub async fn call_async( icon: Icon, @@ -339,7 +343,7 @@ pub mod notify { instance_call_async(default_instance()?, icon, time, color, msg).await } - /// Creates a error that Hyprland will display (async) + /// Sends a notification to the user (async) #[cfg(any(feature = "async-lite", feature = "tokio"))] pub async fn instance_call_async( instance: &Instance, @@ -735,7 +739,7 @@ pub mod instance { pub struct Instance { /// instance name (9958d29...) in /run/user/$UID/hypr/$instance pub instance: String, - /// ??? + /// unix timestamp of when the instance started pub time: u64, /// pid of hyprland process pub pid: u32, @@ -744,6 +748,9 @@ pub mod instance { } /// Returns a list of running instances + /// + /// Named `instance_list` rather than `list` to avoid colliding with the + /// `list` functions in sibling modules when glob-imported. pub fn instance_list() -> crate::Result> { let buf = get_hypr_path()?; let entries = std::fs::read_dir(buf)?; diff --git a/src/data/mod.rs b/src/data/mod.rs index a3398db..cc9bb61 100644 --- a/src/data/mod.rs +++ b/src/data/mod.rs @@ -4,7 +4,7 @@ //! //! ## Usage //! -//! here is a example of every function in use! (blocking) +//! here is an example of every function in use! (blocking) //! ```rust //! use hyprland::data::*; //! use hyprland::prelude::*; diff --git a/src/data/regular.rs b/src/data/regular.rs index 7da7f1e..99adde2 100644 --- a/src/data/regular.rs +++ b/src/data/regular.rs @@ -622,12 +622,14 @@ impl From for AnimationStyle { if value.starts_with("popin") { let mut iter = value.split(' '); iter.next(); - AnimationStyle::PopIn({ - let mut str = iter.next().unwrap_or("100%").to_string(); - str.remove(str.len() - 1); - - str.parse().unwrap_or(100_u8) - }) + // Hyprland may emit a bare "popin " — an empty token here would make + // `remove(len - 1)` panic on an empty string. + let raw = iter.next().unwrap_or("100%"); + let str = raw + .strip_suffix('%') + .filter(|s| !s.is_empty()) + .unwrap_or("100"); + AnimationStyle::PopIn(str.parse().unwrap_or(100_u8)) } else { match value.as_str() { "slide" => AnimationStyle::Slide, @@ -819,3 +821,40 @@ create_data_struct!( holding_type: WorkspaceRuleset, doc: "This struct holds a vector of workspace rules per workspace" ); + +#[cfg(test)] +mod animation_tests { + use super::*; + + /// `"popin "` used to panic: the second token is empty and the old code did + /// `str.remove(str.len() - 1)` on it. + #[test] + fn popin_with_trailing_space_does_not_panic() { + let style = AnimationStyle::from("popin ".to_string()); + assert!(matches!(style, AnimationStyle::PopIn(100)), "got {style:?}"); + } + + #[test] + fn popin_bare_falls_back_to_full_scale() { + assert!(matches!( + AnimationStyle::from("popin".to_string()), + AnimationStyle::PopIn(100) + )); + } + + #[test] + fn popin_parses_the_percentage() { + assert!(matches!( + AnimationStyle::from("popin 87%".to_string()), + AnimationStyle::PopIn(87) + )); + } + + #[test] + fn empty_string_maps_to_none() { + assert!(matches!( + AnimationStyle::from("".to_string()), + AnimationStyle::None + )); + } +} diff --git a/src/dispatch.rs b/src/dispatch.rs index 2ad75aa..35684b8 100644 --- a/src/dispatch.rs +++ b/src/dispatch.rs @@ -12,7 +12,7 @@ //! //! Ok(()) //! } -//! ```` +//! ``` use crate::default_instance; use crate::dispatch::fmt::*; @@ -250,12 +250,11 @@ pub(super) mod fmt { #[inline(always)] pub(super) fn format_relative(int: i32, extra: &'_ str) -> String { - if int.is_positive() { + // `0` must keep the prefix (`m+0`), not collapse to a bare `+0` + if int >= 0 { format!("{extra}+{int}") - } else if int.is_negative() { - format!("{extra}-{}", int.abs()) } else { - "+0".to_owned() + format!("{extra}-{}", int.abs()) } } } @@ -805,7 +804,7 @@ pub(crate) fn gen_dispatch_str(cmd: DispatchType, dispatch: bool) -> crate::Resu ), CenterWindow => "centerwindow".to_string(), ResizeActive(pos) => format!("resizeactive{sep}{pos}"), - MoveActive(pos) => format!("moveactive {pos}"), + MoveActive(pos) => format!("moveactive{sep}{pos}"), ResizeWindowPixel(pos, win) => format!("resizewindowpixel{sep}{pos},{win}"), MoveWindowPixel(pos, win) => format!("movewindowpixel{sep}{pos},{win}"), CycleWindow(dir) => format!("cyclenext{sep}{dir}"), @@ -815,7 +814,7 @@ pub(crate) fn gen_dispatch_str(cmd: DispatchType, dispatch: bool) -> crate::Resu TagWindow(act, tag, None) => format!("tagwindow{sep}{act}{tag}"), FocusWindow(win) => format!("focuswindow{sep}{win}"), FocusMonitor(mon) => format!("focusmonitor{sep}{mon}"), - ChangeSplitRatio(fv) => format!("splitratio {fv}"), + ChangeSplitRatio(fv) => format!("splitratio{sep}{fv}"), ToggleOpaque => "toggleopaque".to_string(), MoveCursorToCorner(corner) => format!("movecursortocorner{sep}{}", corner.clone() as u8), MoveCursor(x, y) => format!("movecursor{sep}{x} {y}"), @@ -824,7 +823,7 @@ pub(crate) fn gen_dispatch_str(cmd: DispatchType, dispatch: bool) -> crate::Resu ForceRendererReload => "forcerendererreload".to_string(), MoveCurrentWorkspaceToMonitor(mon) => format!("movecurrentworkspacetomonitor{sep}{mon}"), MoveWorkspaceToMonitor(work, mon) => format!("moveworkspacetomonitor{sep}{work} {mon}"), - ToggleSpecialWorkspace(Some(name)) => format!("togglespecialworkspace {name}"), + ToggleSpecialWorkspace(Some(name)) => format!("togglespecialworkspace{sep}{name}"), ToggleSpecialWorkspace(None) => "togglespecialworkspace".to_string(), RenameWorkspace(id, name) => { format!( @@ -1006,3 +1005,200 @@ macro_rules! dispatch { $crate::dispatch::Dispatch::instance_call($instance, $crate::dispatch::DispatchType::$dis($($arg), *)) }; } + +#[cfg(test)] +#[allow(clippy::unwrap_used, clippy::expect_used)] +mod tests { + use super::{ + DispatchType, FirstEmpty, FloatValue, Position, WindowIdentifier, + WorkspaceIdentifierWithSpecial, WorkspaceOptions, gen_dispatch_str, + }; + + /// Hyprland reads a bind line as `CVarList(value, 4)` — MODS,KEY,DISPATCHER,ARGS + /// (`ConfigManager.cpp`, `handleBind`) — so only the dispatcher name must be + /// followed by `,`; the args keep their normal space-separated syntax. + /// On the socket the separator is a space. Assert both. + #[test] + fn separators_follow_the_target_syntax() { + let cases = [ + ( + DispatchType::MoveActive(Position::Delta(0, 50)), + "dispatch moveactive 0 50", + "moveactive,0 50", + ), + ( + DispatchType::ChangeSplitRatio(FloatValue::Relative(-0.05)), + "dispatch splitratio -0.05", + "splitratio,-0.05", + ), + ( + DispatchType::ToggleSpecialWorkspace(Some("scratch".to_owned())), + "dispatch togglespecialworkspace scratch", + "togglespecialworkspace,scratch", + ), + ]; + + for (dispatcher, socket, bind) in cases { + assert_eq!( + gen_dispatch_str(dispatcher.clone(), true).unwrap().data, + socket + ); + assert_eq!(gen_dispatch_str(dispatcher, false).unwrap().data, bind); + } + } + + /// `RelativeMonitor(0)` used to collapse to a bare `+0`, dropping the `m`. + #[test] + fn relative_identifiers_keep_their_prefix_at_zero() { + // `RelativeMonitor` is the workspace-side variant and keeps its `m`. + assert_eq!( + WorkspaceIdentifierWithSpecial::RelativeMonitor(0).to_string(), + "m+0", + "a bare +0 makes Hyprland read it as a relative workspace" + ); + assert_eq!( + WorkspaceIdentifierWithSpecial::RelativeMonitor(-2).to_string(), + "m-2" + ); + assert_eq!( + WorkspaceIdentifierWithSpecial::RelativeMonitor(3).to_string(), + "m+3" + ); + assert_eq!( + WorkspaceIdentifierWithSpecial::RelativeOpen(0).to_string(), + "e+0" + ); + assert_eq!( + WorkspaceIdentifierWithSpecial::RelativeMonitorIncludingEmpty(0).to_string(), + "r+0" + ); + assert_eq!( + WorkspaceIdentifierWithSpecial::Relative(0).to_string(), + "+0" + ); + } + + /// All four `FirstEmpty` combinations are accepted by Hyprland (`workspace + /// empty`, `empty m`, `empty n`, `empty mn` all return ok on 0.56.2). + #[test] + fn first_empty_combinations_are_all_valid() { + for (on_monitor, next, expected) in [ + (false, false, ""), + (true, false, "m"), + (false, true, "n"), + (true, true, "mn"), + ] { + let fe = FirstEmpty { on_monitor, next }; + assert_eq!(fe.to_string(), expected); + assert_eq!( + WorkspaceIdentifierWithSpecial::Empty(fe).to_string(), + format!("empty{expected}") + ); + } + } + + #[test] + fn toggle_special_without_a_name_has_no_arguments() { + assert_eq!( + gen_dispatch_str(DispatchType::ToggleSpecialWorkspace(None), true) + .unwrap() + .data, + "dispatch togglespecialworkspace" + ); + } + + #[test] + fn position_renders_both_axes() { + assert_eq!(Position::Delta(10, 20).to_string(), "10 20"); + assert_eq!(Position::Delta(-10, 20).to_string(), "-10 20"); + assert_eq!(Position::Delta(0, -50).to_string(), "0 -50"); + assert_eq!(Position::Exact(300, 400).to_string(), "exact 300 400"); + assert_eq!(Position::DeltaFraction(10, 20).to_string(), "10% 20%"); + assert_eq!(Position::DeltaFraction(-5, 25).to_string(), "-5% 25%"); + assert_eq!(Position::ExactFraction(10, 90).to_string(), "exact 10% 90%"); + } + + #[test] + fn move_and_resize_dispatchers_carry_both_axes() { + let cases = [ + ( + DispatchType::MoveActive(Position::Delta(0, 50)), + "dispatch moveactive 0 50", + ), + ( + DispatchType::MoveActive(Position::Delta(30, -30)), + "dispatch moveactive 30 -30", + ), + ( + DispatchType::MoveActive(Position::Exact(300, 400)), + "dispatch moveactive exact 300 400", + ), + ( + DispatchType::MoveActive(Position::DeltaFraction(0, 50)), + "dispatch moveactive 0% 50%", + ), + ( + DispatchType::MoveActive(Position::ExactFraction(25, 75)), + "dispatch moveactive exact 25% 75%", + ), + ( + DispatchType::ResizeActive(Position::Delta(0, 50)), + "dispatch resizeactive 0 50", + ), + ( + DispatchType::ResizeActive(Position::Exact(0, 400)), + "dispatch resizeactive exact 0 400", + ), + ( + DispatchType::MoveWindowPixel( + Position::Delta(5, -5), + WindowIdentifier::ActiveWindow, + ), + "dispatch movewindowpixel 5 -5,activewindow", + ), + ( + DispatchType::ResizeWindowPixel( + Position::Exact(10, 20), + WindowIdentifier::ActiveWindow, + ), + "dispatch resizewindowpixel exact 10 20,activewindow", + ), + ]; + + for (dispatcher, expected) in cases { + let label = format!("{dispatcher:?}"); + let Ok(generated) = gen_dispatch_str(dispatcher, true) else { + panic!("failed to generate a dispatch string for {label}"); + }; + assert_eq!(generated.data, expected); + } + } + + #[test] + fn workspace_options_match_their_variant() { + assert_eq!(WorkspaceOptions::AllPseudo.to_string(), "allpseudo"); + assert_eq!(WorkspaceOptions::AllFloat.to_string(), "allfloat"); + } + + #[test] + fn workspace_option_dispatcher_uses_the_matching_label() { + let cases = [ + ( + DispatchType::WorkspaceOption(WorkspaceOptions::AllPseudo), + "dispatch workspaceopt allpseudo", + ), + ( + DispatchType::WorkspaceOption(WorkspaceOptions::AllFloat), + "dispatch workspaceopt allfloat", + ), + ]; + + for (dispatcher, expected) in cases { + let label = format!("{dispatcher:?}"); + let Ok(generated) = gen_dispatch_str(dispatcher, true) else { + panic!("failed to generate a dispatch string for {label}"); + }; + assert_eq!(generated.data, expected); + } + } +} diff --git a/src/event_listener/shared.rs b/src/event_listener/shared.rs index 3445c30..0036f9b 100644 --- a/src/event_listener/shared.rs +++ b/src/event_listener/shared.rs @@ -523,6 +523,11 @@ pub struct UnknownEventData { impl UnknownEventData { /// Takes the amount of args, and splits the string correctly pub fn parse_args(self, count: usize) -> Vec { + // splitn(0, ..) panics — a 0-arg event (e.g. `configreloaded`) must yield + // the whole arg string, not a panic. + if count == 0 { + return vec![self.args]; + } self.args .splitn(count, ",") .map(|x| x.to_string()) @@ -889,7 +894,7 @@ pub(crate) fn event_parser(event: &str) -> crate::Result> { })), ParsedEventType::WindowClosed => Ok(Event::WindowClosed(Address::new(get![args;0]))), ParsedEventType::WindowMovedV2 => Ok(Event::WindowMoved(WindowMoveEvent { - window_address: Address::fmt_new(get![ref args;0]), + window_address: Address::new(get![ref args;0]), workspace_id: parse_int!(get![ref args;1], event: "WindowMoved"), workspace_name: parse_string_as_work(get![args;2]), })), @@ -913,15 +918,20 @@ pub(crate) fn event_parser(event: &str) -> crate::Result> { ParsedEventType::LayerOpened => Ok(Event::LayerOpened(get![args;0])), ParsedEventType::LayerClosed => Ok(Event::LayerClosed(get![args;0])), ParsedEventType::FloatStateChanged => { - let state = get![ref args;1] == "0"; // FIXME: does 0 mean it's floating? + // Hyprland sends `changefloatingmode>>{addr},{0|1}` where the second + // field is `CWindowTarget::floating()` — a bool, so `1` is floating. + let state = get![ref args;1] == "1"; Ok(Event::FloatStateChanged(WindowFloatEventData { address: Address::new(get![ref args;0]), floating: state, })) } ParsedEventType::Screencast => { + // The second field is a type formatted through a custom formatter that + // emits the strings "monitor" / "window" / "region" / "ERR NONE", + // never "1". It is compared as `== "1"`, so `monitor` was always false. let state = get![ref args;0] == "1"; - let owner = get![ref args;1] == "1"; + let owner = get![ref args;1] == "monitor"; Ok(Event::Screencast(ScreencastEventData { turning_on: state, monitor: owner, @@ -968,3 +978,50 @@ pub(crate) fn event_parser(event: &str) -> crate::Result> { Ok(events) } + +#[cfg(test)] +#[allow(clippy::unwrap_used, clippy::expect_used)] +mod tests { + use super::*; + + /// `changefloatingmode>>{addr},{0|1}` — the second field is + /// `CWindowTarget::floating()`, so `1` is floating. + #[test] + fn float_state_changed_reports_the_true_state() { + for (payload, expected) in [ + ("changefloatingmode>>55a,0", false), + ("changefloatingmode>>55a,1", true), + ] { + let events = event_parser(payload).unwrap(); + let Event::FloatStateChanged(data) = &events[0] else { + panic!("expected FloatStateChanged, got {:?}", events[0]); + }; + assert_eq!(data.floating, expected, "payload {payload}"); + } + } + + /// The screencast owner is formatted as a string, never "1". + #[test] + fn screencast_monitor_is_read_from_the_type_string() { + // `monitor` is the *type* of screencast, independent of on/off. + for (payload, expected) in [ + ("screencast>>1,monitor", true), + ("screencast>>0,monitor", true), + ("screencast>>1,window", false), + ("screencast>>1,region", false), + ("screencast>>1,ERR NONE", false), + ] { + let events = event_parser(payload).unwrap(); + let Event::Screencast(data) = &events[0] else { + panic!("expected Screencast, got {:?}", events[0]); + }; + assert_eq!(data.monitor, expected, "payload {payload}"); + } + } + + /// A 0-arg event used to reach `splitn(0, ",")`, which panics. + #[test] + fn zero_arg_events_do_not_panic() { + let _ = event_parser("configreloaded>>").unwrap(); + } +} diff --git a/src/keyword.rs b/src/keyword.rs index c2f91ce..583acd2 100644 --- a/src/keyword.rs +++ b/src/keyword.rs @@ -177,16 +177,22 @@ impl HyprColor { let u: u32 = (a << 24) | (r << 16) | (g << 8) | b; Some(Self::from_argb_u32(u)) } - // b16 parse (e.g., "rgba(FF00AA7F)") + // b16 parse — Hyprland writes 8 hex digits, e.g. "rgba(FF00AA7F)". + // 6 digits is accepted too, and means opaque. false => { let s = s.trim(); - if s.len() != 6 { + if s.len() != 6 && s.len() != 8 { return None; } let i = u32::from_str_radix(s, 16).ok()?; - let a = (i & 0xFF) << 24; - let i = (i >> 8) | a; - Some(Self::from_argb_u32(i)) + // 6 digits are rrggbb; Hyprland's own form is rrggbbaa. + let u = if s.len() == 6 { + (0xFFu32 << 24) | i + } else { + let a = (i & 0xFF) << 24; + (i >> 8) | a + }; + Some(Self::from_argb_u32(u)) } }) } @@ -411,6 +417,23 @@ impl TryFrom<&OptionRaw> for OptionValue { } OptionValue::Unknown(raw.json.to_string()) } + // `css` is a whitespace-separated gap string of 1, 2 or 4 ints + // (e.g. "3 3 3 3"), which is the same shape as `custom` + "css" => match_unknown!( + raw.json, + v.as_str().and_then(|s| Custom::try_from(s).ok()), + Custom + ), + // `gradient` is " deg" + "gradient" => match_unknown!( + raw.json, + v.as_str() + .and_then(|g| Custom::try_from(g).ok()) + .filter(|c| matches!(c, Custom::HyprGradient(_))), + Custom + ), + // `font_weight` arrives as an int (100, 200, ...) + "font_weight" => match_unknown!(raw.json, v.as_i64(), Int), _ => OptionValue::Unknown(raw.json.to_string()), }, None => OptionValue::Unknown(raw.json.to_string()), @@ -540,3 +563,93 @@ impl Keyword { Ok(keyword) } } + +#[cfg(test)] +#[allow(clippy::unwrap_used, clippy::expect_used)] +mod tests { + use super::*; + + /// Hyprland writes colours as `rgba(FF00AA7F)` — 8 hex digits. The old + /// parser only accepted 6, so it rejected its own documented example. + #[test] + fn hypr_color_parses_eight_digit_rgba() { + // round-trips: Hyprland writes rrggbbaa and Display emits the same 8 digits + let c = HyprColor::try_from_rgba_str("rgba(ff00aa7f)").expect("8-digit rgba"); + assert_eq!(c.to_string().to_lowercase(), "rgba(ff00aa7f)"); + // the crate's own documented example + assert!(HyprColor::try_from_rgba_str("rgba(b3ff1aee)").is_some()); + } + + #[test] + fn hypr_color_still_parses_six_digit_rgba_as_opaque() { + assert!(HyprColor::try_from_rgba_str("rgba(ff00aa)").is_some()); + } + + #[test] + fn hypr_color_parses_decimal_rgba() { + assert!(HyprColor::try_from_rgba_str("rgba(255,0,170,0.5)").is_some()); + } + + fn raw(payload: &str) -> OptionRaw { + serde_json::from_str(payload).unwrap() + } + + /// `bool` needs a new enum variant, which is a semver break, so it lands + /// in 0.5.0. Until then bool options stay `Unknown` rather than being + /// misrepresented as some other variant. + #[test] + fn option_value_still_reports_bool_as_unknown_in_0_4() { + assert!(matches!( + OptionValue::try_from(&raw( + r#"{"option":"misc:disable_hyprland_logo","set":true,"bool":true}"# + )) + .unwrap(), + OptionValue::Unknown(_) + )); + } + + /// `general:gaps_in` used to come back `Unknown`. + #[test] + fn option_value_parses_css() { + let v = OptionValue::try_from(&raw( + r#"{"option":"general:gaps_in","set":true,"css":"3 3 3 3"}"#, + )) + .unwrap(); + assert!( + matches!(v, OptionValue::Custom(Custom::HyprRect(_))), + "got {v:?}" + ); + } + + /// `decoration:shadow:color` used to come back `Unknown`. + #[test] + fn option_value_parses_gradient() { + let v = OptionValue::try_from(&raw( + r#"{"option":"decoration:shadow:color","set":true,"gradient":"rgba(ee1a1a1a) rgba(00ff00ff) 90deg"}"#, + )) + .unwrap(); + assert!( + matches!(v, OptionValue::Custom(Custom::HyprGradient(_))), + "got {v:?}" + ); + } + + #[test] + fn option_value_still_parses_the_original_types() { + assert!(matches!( + OptionValue::try_from(&raw( + r#"{"option":"general:border_size","set":true,"int":2}"# + )) + .unwrap(), + OptionValue::Int(2) + )); + } + + #[test] + fn unknown_type_stays_unknown() { + assert!(matches!( + OptionValue::try_from(&raw(r#"{"option":"x","set":true,"nonsense":1}"#)).unwrap(), + OptionValue::Unknown(_) + )); + } +} diff --git a/src/shared.rs b/src/shared.rs index ccb696f..ff15a58 100644 --- a/src/shared.rs +++ b/src/shared.rs @@ -14,11 +14,6 @@ use std::{env, fmt}; )] pub struct Address(String); impl Address { - #[inline(always)] - pub(crate) fn fmt_new(address: &str) -> Self { - // this way is faster than std::fmt - Self("0x".to_owned() + address) - } /// This creates a new address from a value that implements [ToString] pub fn new(string: T) -> Self { let str = string.to_string();