Add editable panels and refine shell settings (#18)

* Integrate panel composition, adaptive sizing, and overflow

* Add instance editing controls to panel settings

* Add panel group editing and measured composition preview

* Reorganize panel settings and add drag-and-drop item editing

* Simplify panel settings and place inspectors beside the editor

* Refine Panel & Shell settings, previews, and panel rendering

* Organize settings navigation and modernize packaged panel config

* Support top and bottom panels and refine shell surfaces

Add edge-aware settings, previews, popup placement, notifications, margins, and corner rendering. Preserve translucency in notification and dialog controls, and tighten spacing around the clock and display-mode icon.

* Add workspace styles and fix Settings text rendering

* Make panel allocation independent of measurement order

* Normalize panel item settings and visibility

* Move shell geometry into each panel

* Add independent group surfaces and finalize panel configuration

* Keep panel fit checks and restoration consistent with allocation

* Reject unknown panel item options and namespace metadata

* Reject invalid shell startup configuration and remove old radius fields

* Discover workspace application icons in a background task

* Remove the panel architecture document and improve reference prose

* Let panel media fill available space and improve Settings scrolling

* Preserve panel labels across clipped GPU rendering

* Use matching alpine lake wallpapers for light and dark modes

* Fix panel accessibility and popup lifecycle

Apply Reduce Transparency to panel opacity in the shell, compositor, and
Settings preview. Reject unknown theme tokens before snapshot substitution
and validate the current geometry fields in both consumers.

Dismiss popovers and workspace tooltips after panel layout changes. Handle
bar pointer exits directly and recover workspace hover after reentry without
repeated motion updates. Cover the transitions with regression tests and
update the wallpaper dimensions check for the bundled lake defaults.

* Use tagged Ferese toolkit fixes

* Fix center-only panel spacing and headless text rendering

* Bundle native 4K abstract wallpapers for both appearances

* Dismiss workspace tooltips before captured pointer dispatch

* Verify installed JPEG wallpapers when replacing a release
This commit is contained in:
Samuel Onoja authored and GitHub committed 2026-10-10 18:50:37 +01:00
1 parent d4c8c10b39
commit 65fcaef13f
84 files changed
+12809 -1258

No files matched your search

+5 -6
View File
@@ -47,7 +47,6 @@ pub struct StickyNote {
pub opacity: f32,
pub padding: f32,
pub gap: f32,
pub radius: f32,
pub alignment: Alignment,
}
@@ -73,7 +72,6 @@ impl Default for StickyNote {
opacity: 0.9,
padding: 20.,
gap: 8.,
radius: 16.,
alignment: Alignment::Left,
}
}
@@ -122,7 +120,6 @@ impl StickyNote {
("opacity", self.opacity, 0., 1.),
("padding", self.padding, 0., 64.),
("gap", self.gap, 0., 64.),
("radius", self.radius, 0., 128.),
] {
if !value.is_finite() || !(min..=max).contains(&value) {
return invalid(name);
@@ -208,7 +205,6 @@ pub struct Clock {
pub gap: f32,
pub padding: f32,
pub background: Option<String>,
pub radius: f32,
}
impl Default for Clock {
@@ -238,7 +234,6 @@ impl Default for Clock {
gap: 4.,
padding: 12.,
background: None,
radius: 16.,
}
}
}
@@ -279,7 +274,6 @@ impl Clock {
("opacity", self.opacity, 0., 1.),
("gap", self.gap, 0., 64.),
("padding", self.padding, 0., 64.),
("radius", self.radius, 0., 128.),
] {
if !value.is_finite() || !(min..=max).contains(&value) {
return invalid(name);
@@ -314,6 +308,11 @@ impl Clock {
mod tests {
use super::*;
#[test]
fn widgets_reject_removed_radius_options() {
assert!(crate::from_str::<DesktopWidgets>("clock { radius 12; }").is_err());
assert!(crate::from_str::<DesktopWidgets>("note id=\"note\" { radius 12; }").is_err());
}
#[test]
fn notes_reject_duplicate_ids_and_unbounded_content() {
let note = StickyNote::default();
note.validate().unwrap();
+113 -20
View File
@@ -1,6 +1,7 @@
pub mod desktop;
pub mod families;
pub mod notifications;
pub mod panel;
pub mod presets;
pub mod theme;
@@ -15,27 +16,16 @@ pub const DEFAULT_MATERIAL_OPACITY: f64 = 0.78;
#[derive(Clone, Copy, Debug, Default, serde::Deserialize, serde::Serialize, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub enum BarLayout {
pub enum PanelPreset {
#[default]
Continuous,
Islands,
}
pub const fn default_bar_island_padding() -> f32 {
pub const fn default_island_padding() -> f32 {
4.0
}
pub fn deserialize_bar_island_padding<'de, D: serde::Deserializer<'de>>(deserializer: D) -> Result<f32, D::Error> {
let padding = <f32 as serde::Deserialize>::deserialize(deserializer)?;
if !padding.is_finite() || !(0.0..=32.0).contains(&padding) {
return Err(serde::de::Error::custom(
"bar-island-padding must be between 0 and 32 logical pixels",
));
}
Ok(padding)
}
#[derive(Debug)]
pub struct Error(String);
@@ -69,7 +59,7 @@ pub fn default_wallpaper_for(appearance: theme::Appearance) -> &'static str {
static DARK: std::sync::OnceLock<String> = std::sync::OnceLock::new();
let (slot, name) = match appearance {
theme::Appearance::Light => (&LIGHT, "ferese-wallpaper-light.png"),
theme::Appearance::Dark => (&DARK, "ferese-wallpaper-dark.jpg"),
theme::Appearance::Dark => (&DARK, "ferese-wallpaper-dark.png"),
};
slot.get_or_init(|| {
let path = std::env::current_exe()
@@ -97,6 +87,9 @@ fn field(name: &str, parent: &str) -> String {
"output-profile" => "output_profiles".into(),
"output" => "outputs".into(),
"note" => "notes".into(),
"panel" => "panels".into(),
"group" => "groups".into(),
"item" => "items".into(),
_ => name.replace('-', "_"),
}
}
@@ -104,9 +97,13 @@ fn field(name: &str, parent: &str) -> String {
fn is_records(key: &str, parent: &str) -> bool {
matches!(
(parent, key),
("", "bindings" | "window_rules" | "output_profiles" | "autostart")
| ("output_profiles", "outputs")
(
"",
"bindings" | "window_rules" | "output_profiles" | "autostart" | "panels"
) | ("output_profiles", "outputs")
| ("desktop_widgets", "notes")
| ("start" | "center" | "end", "groups")
| ("groups", "items")
)
}
@@ -114,7 +111,7 @@ fn is_array(key: &str, parent: &str) -> bool {
parent == "commands"
|| matches!(
key,
"command" | "position" | "width_presets" | "xkb_options" | "settings_command" | "outputs"
"command" | "position" | "padding" | "width_presets" | "xkb_options" | "settings_command" | "outputs"
)
}
@@ -190,7 +187,7 @@ fn node_value(node: &KdlNode, key: &str, parent: &str) -> Result<Value, Error> {
"bindings" => &["keys", "action", "argument"],
"output_profiles" => &["name"],
"outputs" => &["match"],
"notes" => &["id"],
"notes" | "panels" | "groups" | "items" => &["id"],
"autostart" => &[],
"window_rules" => &[],
_ => unreachable!(),
@@ -364,6 +361,12 @@ impl Document {
}
let mut candidate = self.clone();
let (name, parents) = path.rsplit_once('.').map_or((path, ""), |(p, n)| (n, p));
if unset_property(&mut candidate.doc, &path.split('.').collect::<Vec<_>>(), "")? {
format_document(&mut candidate.doc);
candidate.refresh()?;
*self = candidate;
return Ok(());
}
let doc = section_mut(
&mut candidate.doc,
&parents.split('.').filter(|s| !s.is_empty()).collect::<Vec<_>>(),
@@ -546,12 +549,99 @@ fn section_mut<'a>(doc: &'a mut KdlDocument, parts: &[&str], parent: &str) -> Re
section_mut(child, &parts[used..], key)
}
/// Scalar settings in record nodes can be KDL properties rather than children.
fn unset_property(doc: &mut KdlDocument, parts: &[&str], parent: &str) -> Result<bool, Error> {
if parts.len() < 2 {
return Ok(false);
}
let key = parts[0];
let record = is_records(key, parent);
let used = if record { 2 } else { 1 };
let index = if record {
parts
.get(1)
.and_then(|part| part.parse::<usize>().ok())
.ok_or_else(|| Error("Record index missing".into()))?
} else {
0
};
let Some(node) = doc
.nodes_mut()
.iter_mut()
.filter(|node| field(node.name().value(), parent) == key)
.nth(index)
else {
return Ok(false);
};
if parts.len() == used + 1
&& let Some(index) = node
.entries()
.iter()
.position(|entry| entry.name().is_some_and(|name| field(name.value(), key) == parts[used]))
{
let entry = node.entries_mut().remove(index);
if let Some(format) = entry.format() {
let comments = [&format.leading, &format.trailing]
.into_iter()
.filter(|part| part.contains("//") || part.contains("/*"))
.cloned()
.collect::<String>();
if !comments.is_empty() {
let mut format = node.format().cloned().unwrap_or_default();
format.leading.push_str(&comments);
node.set_format(format);
}
}
return Ok(true);
}
if let Some(children) = node.children_mut() {
unset_property(children, &parts[used..], key)
} else {
Ok(false)
}
}
fn set_in(doc: &mut KdlDocument, parts: &[&str], parent: &str, value: Value) -> Result<(), Error> {
if parts.is_empty() {
return Err(Error("Missing setting path".into()));
}
let key = parts[0];
if parts.len() == 1 && is_records(key, parent) {
let records = value
.as_array()
.ok_or_else(|| Error("Expected a list of records".into()))?;
let mut nodes = records
.iter()
.map(|value| value_node(key, value, parent))
.collect::<Result<Vec<_>, _>>()?;
let at = doc
.nodes()
.iter()
.position(|node| field(node.name().value(), parent) == key)
.unwrap_or(doc.nodes().len());
let mut comments = String::new();
for node in doc
.nodes()
.iter()
.filter(|node| field(node.name().value(), parent) == key)
{
collect_comments(node, &mut comments);
}
doc.nodes_mut().retain(|node| field(node.name().value(), parent) != key);
if let Some(first) = nodes.first_mut() {
first.set_format(kdl::KdlNodeFormat {
leading: comments,
..Default::default()
});
} else if !comments.is_empty() {
let mut format = doc.format().cloned().unwrap_or_default();
format.trailing.push_str(&comments);
doc.set_format(format);
}
doc.nodes_mut().splice(at..at, nodes);
return Ok(());
}
let i = node_index(doc, key, parent);
if parts.len() == 1 {
@@ -588,7 +678,7 @@ fn set_in(doc: &mut KdlDocument, parts: &[&str], parent: &str, value: Value) ->
"bindings" => &["keys", "action", "argument"],
"outputs" => &["match"],
"output_profiles" => &["name"],
"notes" => &["id"],
"notes" | "panels" | "groups" | "items" => &["id"],
_ => &[],
};
let position = positions.iter().position(|p| *p == rest[0]);
@@ -681,6 +771,9 @@ fn node_name(key: &str, parent: &str) -> String {
"output_profiles" => "output-profile".into(),
"outputs" => "output".into(),
"notes" => "note".into(),
"panels" => "panel".into(),
"groups" => "group".into(),
"items" => "item".into(),
_ => key.replace('_', "-"),
}
}
@@ -694,7 +787,7 @@ fn value_node(key: &str, value: &Value, parent: &str) -> Result<KdlNode, Error>
"bindings" => &["keys", "action", "argument"],
"output_profiles" => &["name"],
"outputs" => &["match"],
"notes" => &["id"],
"notes" | "panels" | "groups" | "items" => &["id"],
_ => &[],
};
let mut child = KdlDocument::new();
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,69 @@
use serde::{Deserialize, Serialize};
/// Logical dimensions owned by a panel, independent of its color theme or edge.
#[derive(Clone, Copy, Debug, PartialEq, Deserialize, Serialize)]
#[serde(default, deny_unknown_fields)]
pub struct PanelGeometry {
pub height: f32,
pub edge_margin: i32,
pub side_margins: i32,
pub window_clearance: i32,
pub inner_padding: f32,
}
impl Default for PanelGeometry {
fn default() -> Self {
Self {
height: 28.,
edge_margin: 0,
side_margins: 0,
window_clearance: 0,
inner_padding: 12.,
}
}
}
impl PanelGeometry {
pub fn validate(self) -> Result<(), String> {
if !self.height.is_finite()
|| !(24. ..=128.).contains(&self.height)
|| !self.inner_padding.is_finite()
|| !(0. ..=64.).contains(&self.inner_padding)
|| [self.edge_margin, self.side_margins, self.window_clearance]
.into_iter()
.any(|value| !(0..=4096).contains(&value))
{
return Err("panel height must be 24..128, inner padding 0..64, and margins/clearance 0..4096".into());
}
Ok(())
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn invalid_geometry_rejects_nonfinite_dimensions_and_negative_clearances() {
for geometry in [
PanelGeometry {
height: f32::NAN,
..Default::default()
},
PanelGeometry {
edge_margin: -1,
..Default::default()
},
PanelGeometry {
height: 12.,
..Default::default()
},
PanelGeometry {
inner_padding: f32::INFINITY,
..Default::default()
},
] {
assert!(geometry.validate().is_err());
}
}
}
+688
View File
@@ -0,0 +1,688 @@
//! Measured panel allocation. This module has no frame timing or service ownership.
use super::{ItemId, OverflowPolicy, Panel, Representation, Zone};
use std::collections::BTreeMap;
#[derive(Clone, Debug)]
pub struct Measurement {
pub id: ItemId,
pub alternatives: Vec<(Representation, f32)>,
pub minimum: Option<f32>,
}
#[derive(Clone, Debug, PartialEq)]
pub enum Placement {
Visible { representation: Representation, width: f32 },
Overflow,
}
#[derive(Clone, Debug, Default, PartialEq)]
pub struct Resolution {
pub items: BTreeMap<ItemId, Placement>,
pub overflow: Vec<ItemId>,
pub zone_widths: [f32; 3],
/// Separation used when allocating these zones.
pub zone_gap: f32,
pub forced_overflow: bool,
pub overflow_trigger_width: f32,
/// Width needed by the smallest visible representations before automatic overflow.
pub minimum_width: f32,
}
fn zone_width(panel: &Panel, zone: &Zone, items: &BTreeMap<ItemId, Placement>) -> f32 {
let mut groups = Vec::new();
for group in &zone.groups {
let mut widths = Vec::new();
for item in &group.items {
if let Some(Placement::Visible { width, .. }) = items.get(&item.id)
&& *width > 0.0
{
if !widths.is_empty() {
widths.push(item.gap_before.unwrap_or(group.spacing));
}
widths.push(*width);
}
}
if !widths.is_empty() {
let padding = 2.0 * f32::from(group.padding[1]);
let island = if panel.resolved_surface(group) == super::GroupSurface::Island {
2.0 * group.island_padding
} else {
0.0
};
groups.push(widths.iter().sum::<f32>() + padding + island);
}
}
groups.iter().sum::<f32>() + zone.spacing * groups.len().saturating_sub(1) as f32
}
impl Resolution {
fn update_widths(&mut self, panel: &Panel, overflow_width: f32) {
self.zone_widths = [
zone_width(panel, &panel.start, &self.items),
zone_width(panel, &panel.center, &self.items),
zone_width(panel, &panel.end, &self.items),
];
if !self.overflow.is_empty() {
self.zone_widths[2] += overflow_width
+ if self.zone_widths[2] > 0.0 {
panel.end.spacing
} else {
0.0
};
}
}
fn required_width(&self) -> f32 {
self.required_width_with_gap(self.zone_gap)
}
fn required_width_with_gap(&self, gap: f32) -> f32 {
let [start, center, end] = self.zone_widths;
if center > 0.0 {
let side = start.max(end);
center + if side > 0.0 { 2.0 * (side + gap) } else { 0.0 }
} else {
start + end + if start > 0.0 && end > 0.0 { gap } else { 0.0 }
}
}
pub fn fits(&self, available: f32) -> bool {
self.required_width() <= available
}
/// Clamp a requested inset independently for each output. Content may still
/// overflow on an output too small to fit it even without an inset.
pub fn side_margin(&self, requested: i32, output_width: i32, padding: f32) -> i32 {
let maximum = ((output_width as f32 - 2. * padding - self.minimum_width) / 2.)
.floor()
.max(0.);
requested.max(0).min(maximum as i32)
}
}
pub fn resolve(panel: &Panel, measurements: &[Measurement], available: f32, overflow_width: f32) -> Resolution {
resolve_with_gap(panel, measurements, available, overflow_width, 8.)
}
/// Reserve separation between zones while keeping the center on the panel midpoint.
pub fn resolve_with_gap(
panel: &Panel,
measurements: &[Measurement],
available: f32,
overflow_width: f32,
zone_gap: f32,
) -> Resolution {
let available = available.max(0.0);
let zone_gap = zone_gap.max(0.);
let fits = |resolution: &Resolution| resolution.fits(available);
let mut result = Resolution {
zone_gap,
..Resolution::default()
};
let ordered: Vec<_> = [&panel.start, &panel.center, &panel.end]
.into_iter()
.flat_map(|zone| &zone.groups)
.flat_map(|group| &group.items)
.collect();
let measurements: BTreeMap<_, _> = measurements.iter().map(|measured| (&measured.id, measured)).collect();
// Allocation policy follows composition, never the renderer's sample order.
// Lower priorities yield first; definition order breaks equal-priority ties.
let mut candidates: Vec<_> = ordered.iter().enumerate().collect();
candidates.sort_by_key(|(index, item)| (item.priority, *index));
for item in &ordered {
let Some(measured) = measurements.get(&item.id) else {
continue;
};
let Some(&(representation, width)) = measured.alternatives.first() else {
continue;
};
if item.overflow == OverflowPolicy::Always {
result.items.insert(item.id.clone(), Placement::Overflow);
result.overflow.push(item.id.clone());
} else {
result
.items
.insert(item.id.clone(), Placement::Visible { representation, width });
}
}
result.update_widths(panel, overflow_width);
let mut minimum = result.clone();
for measured in measurements.values() {
if let Some(Placement::Visible { width, .. }) = minimum.items.get_mut(&measured.id) {
for (_, alternative) in &measured.alternatives {
*width = width.min(*alternative);
}
if let Some(flexible) = measured.minimum {
*width = width.min(flexible);
}
}
}
minimum.update_widths(panel, overflow_width);
result.minimum_width = minimum.required_width();
// Flexible content yields space without changing the stored item preference.
for (_, item) in &candidates {
let Some(measured) = measurements.get(&item.id).filter(|measured| measured.minimum.is_some()) else {
continue;
};
if fits(&result) {
break;
}
let Some(Placement::Visible { representation, width }) = result.items.get(&measured.id).cloned() else {
continue;
};
let minimum = measured.minimum.unwrap().min(width);
result.items.insert(
measured.id.clone(),
Placement::Visible {
representation,
width: minimum,
},
);
result.update_widths(panel, overflow_width);
}
for (_, item) in &candidates {
if fits(&result) {
break;
}
let Some(measured) = measurements.get(&item.id) else {
continue;
};
for &(representation, width) in measured.alternatives.iter().skip(1) {
if let Some(Placement::Visible { width: previous, .. }) = result.items.get(&item.id)
&& width < *previous
{
result
.items
.insert(item.id.clone(), Placement::Visible { representation, width });
result.update_widths(panel, overflow_width);
if fits(&result) {
break;
}
}
}
}
// Never is honored whenever the mandatory minimums fit. On physically smaller
// surfaces, retain access through overflow instead of silently clipping actions.
for force in [false, true] {
for (_, item) in &candidates {
if fits(&result) {
break;
}
if item.overflow == OverflowPolicy::Never && !force {
continue;
}
if matches!(result.items.get(&item.id), Some(Placement::Visible { width, .. }) if *width > 0.0) {
result.items.insert(item.id.clone(), Placement::Overflow);
result.overflow.push(item.id.clone());
result.forced_overflow |= force && item.overflow == OverflowPolicy::Never;
result.update_widths(panel, overflow_width);
}
}
}
// A reduction on the shorter side can leave unused room after the other
// side shrinks. Restore preferred representations before expanding titles.
for (_, item) in candidates.iter().rev() {
let Some(measured) = measurements.get(&item.id) else {
continue;
};
let Some(previous @ Placement::Visible { representation, .. }) = result.items.get(&item.id).cloned() else {
continue;
};
for &(candidate, width) in measured
.alternatives
.iter()
.take_while(|(candidate, _)| *candidate != representation)
{
result.items.insert(
item.id.clone(),
Placement::Visible {
representation: candidate,
width: measured.minimum.map_or(width, |minimum| minimum.min(width)),
},
);
result.update_widths(panel, overflow_width);
if fits(&result) {
break;
}
result.items.insert(item.id.clone(), previous.clone());
}
}
result.update_widths(panel, overflow_width);
// Restore the most protected flexible items first, reversing the yield order.
for (_, item) in candidates.iter().rev() {
let Some(measured) = measurements.get(&item.id).filter(|measured| measured.minimum.is_some()) else {
continue;
};
let Some(Placement::Visible {
representation,
width: minimum,
}) = result.items.get(&measured.id).cloned()
else {
continue;
};
let Some(maximum) = measured
.alternatives
.iter()
.find_map(|(candidate, width)| (*candidate == representation).then_some(*width))
else {
continue;
};
let mut low = minimum;
let mut high = maximum;
for _ in 0..20 {
let width = (low + high) * 0.5;
result
.items
.insert(measured.id.clone(), Placement::Visible { representation, width });
result.update_widths(panel, overflow_width);
if fits(&result) { low = width } else { high = width }
}
result.items.insert(
measured.id.clone(),
Placement::Visible {
representation,
width: low,
},
);
}
result
.overflow
.sort_by_key(|id| ordered.iter().position(|item| &item.id == id).unwrap());
result.update_widths(panel, overflow_width);
result
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn a_center_only_item_keeps_its_preferred_size_without_side_gaps() {
use super::super::{Group, Item, ItemKind};
let mut panel = Panel::default();
panel.start.groups.clear();
panel.end.groups.clear();
panel.center.groups = vec![Group::new(
"center",
vec![Item::new("media", ItemKind::Media)],
[0, 0],
0.,
)];
let measurements = [Measurement {
id: ItemId("media".into()),
alternatives: vec![
(Representation::Wide, 40.),
(Representation::Compact, 24.),
(Representation::Icon, 12.),
],
minimum: None,
}];
for gap in [0., 8., 32.] {
for available in [40., 48.] {
let resolution = resolve_with_gap(&panel, &measurements, available, 24., gap);
assert_eq!(
resolution.items[&ItemId("media".into())],
Placement::Visible {
representation: Representation::Wide,
width: 40.
}
);
assert!(resolution.overflow.is_empty());
assert!(resolution.fits(available));
}
}
}
#[test]
fn center_collision_spacing_applies_only_to_occupied_sides() {
for (widths, required) in [
([0., 40., 0.], 40.),
([20., 40., 0.], 96.),
([0., 40., 20.], 96.),
([20., 40., 30.], 116.),
([20., 0., 30.], 58.),
([0., 0., 30.], 30.),
] {
let resolution = Resolution {
zone_widths: widths,
zone_gap: 8.,
..Default::default()
};
assert!(resolution.fits(required));
assert!(!resolution.fits(required - 1.));
}
}
#[test]
fn a_crowded_opposite_zone_does_not_leave_media_compacted_in_unused_space() {
use super::super::{Group, Item, ItemKind};
let mut panel = Panel::default();
panel.start.groups = vec![Group::new(
"navigation",
vec![
Item::new("overview", ItemKind::Overview),
Item::new("media", ItemKind::Media),
],
[0, 0],
0.,
)];
panel.center.groups = vec![Group::new(
"title",
vec![Item::new("title", ItemKind::FocusedWindow)],
[0, 0],
0.,
)];
panel.end.groups = vec![Group::new(
"status",
vec![Item::new("clock", ItemKind::Clock)],
[0, 0],
0.,
)];
let measured = vec![
Measurement {
id: ItemId("overview".into()),
alternatives: vec![(Representation::Icon, 28.)],
minimum: None,
},
Measurement {
id: ItemId("media".into()),
alternatives: vec![
(Representation::Wide, 180.),
(Representation::Compact, 100.),
(Representation::Icon, 28.),
],
minimum: None,
},
Measurement {
id: ItemId("title".into()),
alternatives: vec![(Representation::Wide, 48.)],
minimum: Some(48.),
},
Measurement {
id: ItemId("clock".into()),
alternatives: vec![
(Representation::Wide, 340.),
(Representation::Compact, 240.),
(Representation::Icon, 140.),
],
minimum: None,
},
];
for mirrored in [false, true] {
if mirrored {
std::mem::swap(&mut panel.start, &mut panel.end);
}
let resolution = resolve(&panel, &measured, 550., 32.);
assert!(resolution.fits(550.));
assert_eq!(
resolution.items[&ItemId("media".into())],
Placement::Visible {
representation: Representation::Wide,
width: 180.
}
);
assert_eq!(
resolution.items[&ItemId("clock".into())],
Placement::Visible {
representation: Representation::Compact,
width: 240.
}
);
}
let mut measured = measured;
measured[1].alternatives[0].1 = 400.;
measured[1].minimum = Some(112.);
for mirrored in [false, true] {
if mirrored {
std::mem::swap(&mut panel.start, &mut panel.end);
}
let resolution = resolve(&panel, &measured, 550., 32.);
assert!(resolution.fits(550.));
assert!(
matches!(resolution.items[&ItemId("media".into())], Placement::Visible { representation: Representation::Wide, width } if width > 200. && width < 400.),
"flexible media must expand into the unused room beside the center"
);
}
}
#[test]
fn fits_uses_the_gap_that_was_resolved() {
let panel = Panel::default();
let measured = measurements(&panel);
for gap in [0., 2., 16., 48.] {
let result = resolve_with_gap(&panel, &measured, 2400., 32., gap);
assert_eq!(result.zone_gap, gap);
let required = result.required_width_with_gap(gap);
assert!(result.fits(required));
assert!(!result.fits(required - 1.));
}
}
#[test]
fn flexible_restoration_stays_within_the_selected_representation() {
let mut panel = Panel::default();
panel.start.groups.clear();
panel.center.groups.clear();
panel.end.groups.retain(|group| group.id.0 == "time");
let mut clock = super::super::Item::new("clock", super::super::ItemKind::Clock);
clock.overflow = OverflowPolicy::Never;
clock.priority = 0;
let audio = super::super::Item::new("audio", super::super::ItemKind::Audio);
panel.end.groups[0].items = vec![clock, audio];
let result = resolve(
&panel,
&[
Measurement {
id: ItemId("clock".into()),
alternatives: vec![(Representation::Wide, 80.), (Representation::Compact, 40.)],
minimum: Some(60.),
},
Measurement {
id: ItemId("audio".into()),
alternatives: vec![(Representation::Icon, 100.)],
minimum: None,
},
],
96.,
32.,
);
assert_eq!(
result.items[&ItemId("clock".into())],
Placement::Visible {
representation: Representation::Compact,
width: 40.
}
);
assert_eq!(result.overflow, [ItemId("audio".into())]);
assert!(result.fits(96.));
}
#[test]
fn allocation_is_independent_of_measurement_order_even_for_flexible_items() {
let panel = Panel::default();
let mut measured = measurements(&panel);
for measurement in &mut measured {
measurement.minimum = Some(24.);
}
for width in [2400., 1400., 1000., 800., 400., 80., 32.] {
let expected = resolve_with_gap(&panel, &measured, width, 32., 16.);
for _ in 0..measured.len() {
measured.rotate_left(1);
assert_eq!(resolve_with_gap(&panel, &measured, width, 32., 16.), expected);
measured.reverse();
assert_eq!(resolve_with_gap(&panel, &measured, width, 32., 16.), expected);
measured.reverse();
}
}
}
fn measurements(panel: &Panel) -> Vec<Measurement> {
[&panel.start, &panel.center, &panel.end]
.into_iter()
.flat_map(|zone| &zone.groups)
.flat_map(|group| &group.items)
.map(|item| Measurement {
id: item.id.clone(),
alternatives: vec![
(Representation::Wide, 80.0),
(Representation::Compact, 40.0),
(Representation::Icon, 24.0),
],
minimum: matches!(item.kind, crate::panel::ItemKind::FocusedWindow).then_some(48.0),
})
.collect()
}
#[test]
fn narrow_panels_adapt_deterministically_and_keep_every_item_reachable() {
for background in [crate::PanelPreset::Continuous, crate::PanelPreset::Islands] {
let panel = Panel::from_preset(background);
let measured = measurements(&panel);
for width in [2400., 1200., 800., 400., 160., 80., 32.] {
let resolution = resolve(&panel, &measured, width, 32.);
assert!(resolution.fits(width));
assert_eq!(resolution, resolve(&panel, &measured, width, 32.));
assert_eq!(resolution.items.len(), measured.len());
for id in &resolution.overflow {
assert_eq!(resolution.items.get(id), Some(&Placement::Overflow));
}
if width >= 400. {
assert!(!resolution.forced_overflow);
}
}
}
}
#[test]
fn decoration_and_borders_do_not_change_background_arrangement_or_allocation() {
for background in [crate::PanelPreset::Continuous, crate::PanelPreset::Islands] {
let mut panel = Panel::from_preset(background);
let measurements = measurements(&panel);
let plain = resolve(&panel, &measurements, 1000., 32.);
assert!(!panel.border);
panel.border = true;
panel.background_opacity = Some(0.4);
assert_eq!(resolve(&panel, &measurements, 1000., 32.), plain);
assert_eq!(panel.preset(), Some(background));
}
}
#[test]
fn side_margins_stop_before_overflow_and_use_each_outputs_logical_width() {
let panel = Panel::default();
let measurements = measurements(&panel);
let full = resolve(&panel, &measurements, 4000., 32.);
assert!(full.minimum_width < full.required_width());
for output_width in [1600, 2400, 3840] {
for requested in [0, 32, 400, 4096] {
let margin = full.side_margin(requested, output_width, 12.);
let available = output_width as f32 - 2. * (margin as f32 + 12.);
let result = resolve(&panel, &measurements, available, 32.);
assert!(result.overflow.is_empty(), "output {output_width}, margin {margin}");
assert!(result.fits(available));
assert!(margin <= requested);
}
}
assert!(full.side_margin(4096, 3840, 12.) > full.side_margin(4096, 1600, 12.));
assert_eq!(full.side_margin(4096, 100, 12.), 0);
assert!(
!resolve(&panel, &measurements, 76., 32.).overflow.is_empty(),
"physical output shortage still uses existing overflow"
);
}
#[test]
fn margin_limit_includes_group_padding_and_authored_overflow_without_dependence_on_current_surface_width() {
let mut panel = Panel::default();
panel.end.groups[0].items[0].overflow = OverflowPolicy::Always;
let measurements = measurements(&panel);
let full = resolve(&panel, &measurements, 4000., 32.);
let narrow = resolve(&panel, &measurements, 100., 32.);
assert_eq!(full.minimum_width, narrow.minimum_width);
let margin = full.side_margin(4096, 2400, 12.);
let result = resolve(&panel, &measurements, 2400. - 2. * (margin as f32 + 12.), 32.);
assert_eq!(result.overflow, full.overflow);
let original = full.minimum_width;
panel.end.groups[0].padding[1] += 10;
let padded = resolve(&panel, &measurements, 4000., 32.);
assert!(padded.minimum_width > original);
assert!(padded.side_margin(4096, 2400, 12.) < margin);
}
#[test]
fn asymmetric_sides_reserve_a_real_screen_center() {
let panel = Panel::default();
let resolution = resolve(&panel, &measurements(&panel), 1500., 32.);
let [start, center, end] = resolution.zone_widths;
assert!(end > start);
assert!(start + 8. <= (1500. - center) * 0.5);
assert!((1500. + center) * 0.5 + 8. <= 1500. - end);
}
#[test]
fn always_overflow_is_reserved_and_unavailable_items_are_not_allocated() {
let mut panel = Panel::default();
panel.end.groups[0].items[2].overflow = OverflowPolicy::Always;
let mut measured = measurements(&panel);
measured.remove(3);
let resolution = resolve(&panel, &measured, 2000., 32.);
assert!(!resolution.items.contains_key(&ItemId("media".into())));
assert_eq!(resolution.overflow, [ItemId("network".into())]);
}
#[test]
fn priority_controls_displacement_and_expansion_restores_requested_sizes() {
let mut panel = Panel::default();
panel.start.groups.clear();
panel.center.groups.clear();
panel.end.groups.retain(|group| group.id.0 == "time");
let mut first = panel.end.groups[0].items[0].clone();
first.id = ItemId("low".into());
first.priority = 0;
let mut second = first.clone();
second.id = ItemId("high".into());
second.priority = 100;
let mut third = first.clone();
third.id = ItemId("middle".into());
third.priority = 50;
panel.end.groups[0].items = vec![first, second, third];
let measured: Vec<_> = panel.end.groups[0]
.items
.iter()
.map(|item| Measurement {
id: item.id.clone(),
alternatives: vec![(Representation::Wide, 50.)],
minimum: None,
})
.collect();
let initial = panel.clone();
let small = resolve(&panel, &measured, 150., 32.);
assert_eq!(small.overflow, [ItemId("low".into())]);
assert!(small.fits(150.));
for width in [200., 150., 40., 200.] {
let result = resolve(&panel, &measured, width, 32.);
assert!(result.fits(width));
if width == 200. {
assert!(result.overflow.is_empty());
assert!(result.items.values().all(|placement| matches!(placement, Placement::Visible { representation: Representation::Wide, width } if *width == 50.)));
}
assert_eq!(panel, initial, "resolution must not rewrite configuration intent");
}
}
#[test]
fn only_island_groups_reserve_island_padding() {
let mut panel = Panel::from_preset(crate::PanelPreset::Islands);
let measured = measurements(&panel);
let initial = resolve(&panel, &measured, 2400., 32.);
let title_padding = 2. * panel.center.groups[0].island_padding;
panel.center.groups[0].surface = Some(super::super::GroupSurface::None);
let plain = resolve(&panel, &measured, 2400., 32.);
assert_eq!(plain.zone_widths[1], initial.zone_widths[1] - title_padding);
assert_eq!(plain.zone_widths[0], initial.zone_widths[0]);
assert_eq!(plain.zone_widths[2], initial.zone_widths[2]);
panel.center.groups[0].surface = Some(super::super::GroupSurface::Inset);
assert_eq!(resolve(&panel, &measured, 2400., 32.), plain);
// A parent panel fill cannot change a group's allocation policy.
panel.surface = super::super::PanelSurface::Solid;
assert_eq!(resolve(&panel, &measured, 2400., 32.), plain);
}
}
+157
View File
@@ -0,0 +1,157 @@
use serde::{Deserialize, Deserializer, Serialize, Serializer};
/// Corner radii, clockwise from top-left, in logical pixels.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct CornerRadii(pub [f32; 4]);
impl CornerRadii {
pub fn uniform(radius: f32) -> Self {
Self([radius; 4])
}
pub fn validate(self) -> Result<(), String> {
if self.0.iter().all(|value| value.is_finite() && *value >= 0.) {
Ok(())
} else {
Err("corner radii must be finite, nonnegative pixel values".into())
}
}
/// A panel touching the top edge must cover its top corners.
pub fn at_top_edge(mut self, touching: bool) -> Self {
if touching {
self.0[0] = 0.;
self.0[1] = 0.;
}
self
}
pub fn at_edge(mut self, edge: super::Edge, touching: bool) -> Self {
if touching {
match edge {
super::Edge::Top => self = self.at_top_edge(true),
super::Edge::Bottom => {
self.0[2] = 0.;
self.0[3] = 0.;
}
}
}
self
}
pub fn max(self) -> f32 {
self.0.into_iter().fold(0., f32::max)
}
/// Keep every corner within half the shorter surface dimension.
pub fn clamped(self, width: f32, height: f32) -> Self {
let limit = width.min(height).max(0.) / 2.;
Self(self.0.map(|value| value.min(limit)))
}
}
impl std::str::FromStr for CornerRadii {
type Err = String;
fn from_str(source: &str) -> Result<Self, Self::Err> {
let values: Vec<f32> = source
.split_whitespace()
.map(|part| {
let number = if part == "0" {
part
} else {
part.strip_suffix("px").ok_or("use pixel values such as 4px")?
};
number.parse::<f32>().map_err(|_| "invalid corner radius")
})
.collect::<Result<_, _>>()
.map_err(str::to_owned)?;
let radii = match values.as_slice() {
[a] => [*a; 4],
[a, b] => [*a, *b, *a, *b],
[a, b, c] => [*a, *b, *c, *b],
[a, b, c, d] => [*a, *b, *c, *d],
_ => return Err("enter one to four pixel values, clockwise from top-left".into()),
};
let result = Self(radii);
result.validate()?;
Ok(result)
}
}
impl std::fmt::Display for CornerRadii {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let [a, b, c, d] = self.0;
if a == b && b == c && c == d {
write!(f, "{a}px")
} else if a == c && b == d {
write!(f, "{a}px {b}px")
} else if b == d {
write!(f, "{a}px {b}px {c}px")
} else {
write!(f, "{a}px {b}px {c}px {d}px")
}
}
}
impl Serialize for CornerRadii {
fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
serializer.collect_str(self)
}
}
impl<'de> Deserialize<'de> for CornerRadii {
fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
String::deserialize(deserializer)?
.parse()
.map_err(serde::de::Error::custom)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn css_shorthand_expands_clockwise_and_round_trips() {
for (source, expected) in [
("4px", [4.; 4]),
("4px 8px", [4., 8., 4., 8.]),
("4px 8px 12px", [4., 8., 12., 8.]),
("4px 8px 12px 16px", [4., 8., 12., 16.]),
("0 2.5px", [0., 2.5, 0., 2.5]),
] {
let radii: CornerRadii = source.parse().unwrap();
assert_eq!(radii.0, expected);
let value = serde_json::to_value(radii).unwrap();
assert_eq!(serde_json::from_value::<CornerRadii>(value).unwrap(), radii);
}
}
#[test]
fn docking_squares_only_the_top_corners_without_changing_the_override() {
let radii = CornerRadii([4., 8., 12., 16.]);
assert_eq!(radii.at_top_edge(true).0, [0., 0., 12., 16.]);
assert_eq!(radii.at_top_edge(false), radii);
assert_eq!(radii.at_edge(super::super::Edge::Bottom, true).0, [4., 8., 0., 0.]);
assert_eq!(radii.at_edge(super::super::Edge::Bottom, false), radii);
assert_eq!(radii.0, [4., 8., 12., 16.]);
}
#[test]
fn invalid_values_are_rejected_and_large_radii_clamp_to_surface_size() {
for source in [
"",
"4",
"4%",
"-4px",
"NaNpx",
"infpx",
"4px / 8px",
"1px 2px 3px 4px 5px",
] {
assert!(source.parse::<CornerRadii>().is_err(), "{source}");
}
assert_eq!(CornerRadii([4., 40., 0., 18.]).clamped(100., 28.).0, [4., 14., 0., 14.]);
}
}
+80 -39
View File
@@ -207,8 +207,7 @@ pub fn default_tokens() -> Tokens {
"accent":"#3D7BE6", "on_accent":"#FFFFFF", "border":"#FFFFFF18", "shadow":"#00000055"},
"material":{"style":"solid","opacity":0.78,"blur_radius":12.0,"tint_strength":0.5},
"geometry":{"border_width":1.0,"focus_ring_width":2.0,"window_radius":14.0,"shell_radius":14.0,
"top_bar_height":28.0,"top_bar_margin_top":0,"top_bar_margin_horizontal":0,
"top_bar_window_gap":0,"panel_padding":12.0,"control_gap":12.0},
"control_gap":12.0},
"typography":{"font_family":"Inter"},
"background":{"path":crate::default_wallpaper(),"lock_path":null,"mode":"fill"},
"surface":{"bar":{"background":"#111821","text_primary":"#F4F7FB","text_muted":"#8793A2"}},
@@ -384,17 +383,6 @@ pub fn resolve_with_context(
.map(|preset| preset.gradient_end)
.filter(|end| *end != authored_accent);
let mut explicit_surfaces = std::collections::HashSet::new();
if root
.get("geometry")
.and_then(|value| value.get("shell_radius"))
.is_none()
&& let Some(radius) = document
.get("appearance.corner_radius")
.and_then(Value::as_f64)
.or_else(|| document.get("theme.geometry.top_bar_radius").and_then(Value::as_f64))
{
tokens.geometry.shell_radius = radius;
}
let mut value = token_value(&tokens)?;
for file in [&policy.file, &selection.file].into_iter().flatten() {
let path = theme_path(directory, file);
@@ -418,16 +406,16 @@ pub fn resolve_with_context(
explicit_surfaces.insert(role);
}
}
merge(&mut value, layer, "", &mut warnings, false)?;
merge(&mut value, layer, "", false)?;
}
merge(&mut value, &root, "", &mut warnings, true)?;
merge(&mut value, &root, "", true)?;
let mut overrides = selection.overrides.clone();
if !split && policy.family.is_some() {
for key in ["colors", "surface"] {
overrides.remove(key);
}
}
merge(&mut value, &Value::Object(overrides.clone()), "", &mut warnings, false)?;
merge(&mut value, &Value::Object(overrides.clone()), "", false)?;
tokens = serde_json::from_value(value).map_err(|e| e.to_string())?;
for layer in [&root, &Value::Object(overrides.clone())] {
for role in ["surface_raised", "application_background"] {
@@ -516,13 +504,21 @@ fn token_value(tokens: &Tokens) -> Result<Value, String> {
Ok(value)
}
fn merge(
target: &mut Value,
layer: &Value,
prefix: &str,
warnings: &mut Vec<String>,
inline: bool,
) -> Result<(), String> {
/// Check authored tokens before replacing them with a runtime theme snapshot.
pub fn validate_overrides(document: &Document) -> Result<(), String> {
let Some(root) = document.get("theme") else {
return Ok(());
};
let policy: Policy = serde_json::from_value(root.clone()).map_err(|error| error.to_string())?;
let mut tokens = token_value(&default_tokens())?;
merge(&mut tokens, root, "", true)?;
for selection in [&policy.light, &policy.dark] {
merge(&mut tokens, &Value::Object(selection.overrides.clone()), "", false)?;
}
Ok(())
}
fn merge(target: &mut Value, layer: &Value, prefix: &str, inline: bool) -> Result<(), String> {
let map = layer
.as_object()
.ok_or_else(|| format!("theme {prefix} must be a section"))?;
@@ -545,23 +541,19 @@ fn merge(
{
continue;
}
if prefix == "geometry" && key == "top_bar_radius" {
continue;
}
let path = if prefix.is_empty() {
key.clone()
} else {
format!("{prefix}.{key}")
};
let Some(current) = target.get_mut(key) else {
warnings.push(format!("Unknown theme token: {path}"));
continue;
return Err(format!("Unknown theme token: {path}"));
};
if current.is_null() && path.ends_with(".gradient") && value.is_object() {
*current = json!({"from": "#3D7BE6", "to": "#3D7BE6", "angle": 0.0});
}
if current.is_object() {
merge(current, value, &path, warnings, inline)?;
merge(current, value, &path, inline)?;
} else {
*current = value.clone();
}
@@ -719,9 +711,6 @@ fn validate(tokens: &Tokens) -> Result<(), String> {
if !["fill", "fit"].contains(&tokens.background.mode.as_str()) {
return Err("Unknown wallpaper mode".into());
}
if tokens.geometry.top_bar_height <= 0. {
return Err("top-bar-height must be positive".into());
}
if tokens.typography.font_family.len() > 128 {
return Err("font-family exceeds 128 bytes".into());
}
@@ -910,7 +899,7 @@ pub fn import_family(id: &str, source: &str) -> Result<ImportedFamily, String> {
appearance,
)?;
let mut value = token_value(&base)?;
merge(&mut value, layer, "", &mut warnings, false)?;
merge(&mut value, layer, "", false)?;
let tokens: Tokens = serde_json::from_value(value).map_err(|e| e.to_string())?;
validate(&tokens)?;
warnings.extend(authored_warnings(&tokens));
@@ -922,7 +911,7 @@ pub fn import_family(id: &str, source: &str) -> Result<ImportedFamily, String> {
}
for key in root.as_object().ok_or("Theme file must be a section")?.keys() {
if !matches!(key.as_str(), "name" | "light" | "dark") {
warnings.push(format!("Unknown theme token: {key}"));
return Err(format!("Unknown theme token: {key}"));
}
}
let [light, dark] = variants;
@@ -1295,7 +1284,7 @@ mod tests {
&document,
Path::new("/tmp"),
"2026-09-30T12:00:00Z".parse().unwrap(),
|_| Ok(r##"theme { name "Test"; light { colors { accent "#8F5300"; }; future-token 2; }; }"##.into()),
|_| Ok(r##"theme { name "Test"; light { colors { accent "#8F5300"; }; }; }"##.into()),
)
.unwrap();
assert_eq!(resolved.theme.requested_accent, "#8F5300");
@@ -1307,7 +1296,6 @@ mod tests {
assert_eq!(imported.name, "Test");
assert!(imported.dark.is_none());
assert!(resolved.files.contains(&PathBuf::from("/tmp/test.kdl")));
assert!(resolved.warnings.iter().any(|warning| warning.contains("future_token")));
assert!(
resolve(&document, Path::new("/tmp"), Timestamp::now(), |_| Ok(
r#"theme { light { colors { accent "invalid"; }; }; }"#.into()
@@ -1397,7 +1385,7 @@ mod tests {
}
#[test]
fn partial_files_merge_per_token_and_unknown_tokens_warn() {
fn partial_files_merge_per_token() {
let doc = Document::parse(
"theme { file \"themes/shared.kdl\"; light { file \"themes/light.kdl\"; }; mode \"light\"; }",
)
@@ -1405,7 +1393,7 @@ mod tests {
let result = resolve(&doc, Path::new("/config/ferese"), Timestamp::now(), |path| {
match path.to_str().unwrap() {
"/config/ferese/themes/shared.kdl" => {
Ok("colors { accent \"#12AABB\"; text-primary \"#182234\"; }; future-token 1".into())
Ok("colors { accent \"#12AABB\"; text-primary \"#182234\"; }".into())
}
"/config/ferese/themes/light.kdl" => Ok("theme { colors { accent \"#315090\"; }; }".into()),
_ => panic!("wrong relative path"),
@@ -1415,10 +1403,63 @@ mod tests {
assert_eq!(result.theme.requested_accent, "#315090");
assert_eq!(result.theme.tokens.colors.text_primary, "#182234");
assert_eq!(result.files.len(), 2);
assert!(result.warnings.iter().any(|s| s.contains("future_token")));
assert!(candidate("theme { colors { accent \"invalid\"; }; }").is_err());
}
#[test]
fn unknown_theme_tokens_are_rejected_in_every_authored_layer() {
for key in [
"top-bar-radius",
"top-bar-height",
"top-bar-margin-top",
"top-bar-margin-horizontal",
"top-bar-window-clearance",
"shell-raduis",
] {
for section in ["", "light", "dark"] {
let geometry = format!("geometry {{ {key} 8; }}");
let layer = if section.is_empty() {
geometry
} else {
format!("{section} {{ {geometry}; }}")
};
let document = Document::parse(&format!("theme {{ {layer}; }}")).unwrap();
assert!(
validate_overrides(&document)
.unwrap_err()
.contains(&key.replace('-', "_"))
);
assert!(
candidate(&document.to_string())
.err()
.unwrap()
.contains(&key.replace('-', "_"))
);
}
}
let document = Document::parse("theme { file \"bad.kdl\"; }").unwrap();
assert!(
resolve(&document, Path::new("/tmp"), Timestamp::now(), |_| Ok(
"future-token 1".into()
))
.err()
.unwrap()
.contains("future_token")
);
assert!(
import_family("bad", "theme { light { geometry { top-bar-radius 8; }; }; }")
.err()
.unwrap()
.contains("geometry.top_bar_radius")
);
assert!(
import_family("bad", "theme { name Test; future-token 1; light {}; }")
.err()
.unwrap()
.contains("future_token")
);
}
#[test]
fn accessibility_matrix_resolves_contrast_materials_and_accent() {
for mode in ["light", "dark"] {