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:
1 parent
d4c8c10b39
commit
65fcaef13f
84 files changed
+12809
-1258
No files matched your search
@@ -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
@@ -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());
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
@@ -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.]);
|
||||
}
|
||||
}
|
||||
@@ -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"] {
|
||||
|
||||
@@ -6,6 +6,9 @@
|
||||
pub mod effects {
|
||||
/// Version 1 of the semantic surface effects protocol.
|
||||
pub mod v1 {
|
||||
/// Maximum regions and region opacities in one effects request.
|
||||
pub const MAX_REGIONS: usize = 32;
|
||||
|
||||
#[cfg(feature = "client")]
|
||||
pub use generated::client;
|
||||
#[cfg(feature = "server")]
|
||||
|
||||
@@ -27,11 +27,6 @@
|
||||
"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
|
||||
},
|
||||
"typography": {
|
||||
@@ -95,11 +90,6 @@
|
||||
"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
|
||||
},
|
||||
"typography": {
|
||||
|
||||
@@ -56,11 +56,6 @@ pub struct Geometry {
|
||||
pub focus_ring_width: f64,
|
||||
pub window_radius: f64,
|
||||
pub shell_radius: f64,
|
||||
pub top_bar_height: f64,
|
||||
pub top_bar_margin_top: i32,
|
||||
pub top_bar_margin_horizontal: i32,
|
||||
pub top_bar_window_gap: i32,
|
||||
pub panel_padding: f64,
|
||||
pub control_gap: f64,
|
||||
}
|
||||
|
||||
@@ -159,3 +154,23 @@ pub struct ResolvedTheme {
|
||||
pub accessibility: Accessibility,
|
||||
pub reduced_motion: bool,
|
||||
}
|
||||
|
||||
/// Accessibility takes precedence over a panel's authored opacity.
|
||||
pub fn effective_panel_opacity(inherited: f32, custom: Option<f32>, reduce_transparency: bool) -> f32 {
|
||||
if reduce_transparency {
|
||||
1.0
|
||||
} else {
|
||||
custom.unwrap_or(inherited)
|
||||
}
|
||||
}
|
||||
|
||||
impl ResolvedTheme {
|
||||
pub fn panel_opacity(&self, custom: Option<f32>) -> f32 {
|
||||
let inherited = if self.tokens.material.style == "translucent" {
|
||||
self.tokens.material.opacity as f32
|
||||
} else {
|
||||
1.0
|
||||
};
|
||||
effective_panel_opacity(inherited, custom, self.accessibility.reduce_transparency)
|
||||
}
|
||||
}
|
||||
@@ -8,9 +8,10 @@ rust-version.workspace = true
|
||||
[dependencies]
|
||||
jiff.workspace = true
|
||||
ferese-theme-model = { path = "../ferese-theme-model" }
|
||||
ferese-config = { path = "../ferese-config" }
|
||||
libcosmic = { workspace = true, features = ["a11y"] }
|
||||
|
||||
iced_accessibility = { git = "https://github.com/ferese-wm/libcosmic", tag = "ferese-v0.1.0" }
|
||||
iced_accessibility = { git = "https://github.com/ferese-wm/libcosmic", tag = "ferese-v0.1.1" }
|
||||
|
||||
[dev-dependencies]
|
||||
ferese-config = { path = "../ferese-config" }
|
||||
tokio = { version = "1", features = ["rt"] }
|
||||
@@ -8,7 +8,9 @@ mod geometry;
|
||||
pub mod icons;
|
||||
pub mod menus;
|
||||
mod palette;
|
||||
pub mod panel;
|
||||
mod typography;
|
||||
pub mod workspaces;
|
||||
|
||||
pub use button::accent_button;
|
||||
pub use contrast::{accent_color, accent_pair, apply, composite, contrast, foreground, luminance};
|
||||
|
||||
@@ -0,0 +1,475 @@
|
||||
//! Measure item representations and resolve panel allocation for shell views and previews.
|
||||
use cosmic::iced::advanced::{Clipboard, Layout, Shell, Widget, layout, mouse, renderer, widget};
|
||||
use cosmic::iced::{Event, Length, Rectangle, Size, Vector};
|
||||
use cosmic::{Element, Theme};
|
||||
use ferese_config::panel::layout::{Measurement, Resolution, resolve_with_gap};
|
||||
use ferese_config::panel::{ItemId, Panel, Representation};
|
||||
use std::borrow::Cow;
|
||||
|
||||
/// Group outlines never paint a second fill over the panel background.
|
||||
pub fn group_border(
|
||||
outline: cosmic::iced::Color,
|
||||
radius: impl Into<cosmic::iced::border::Radius>,
|
||||
enabled: bool,
|
||||
) -> cosmic::widget::container::Style {
|
||||
let mut style = cosmic::widget::container::Style::default();
|
||||
style.border.radius = radius.into();
|
||||
if enabled {
|
||||
style.border.width = 1.;
|
||||
style.border.color = outline;
|
||||
}
|
||||
style
|
||||
}
|
||||
|
||||
pub struct Sample<'a, M> {
|
||||
pub id: ItemId,
|
||||
pub representation: Representation,
|
||||
pub minimum: Option<f32>,
|
||||
pub view: Element<'a, M>,
|
||||
}
|
||||
|
||||
pub struct Spacing {
|
||||
pub overflow_decoration: f32,
|
||||
pub zone_gap: f32,
|
||||
}
|
||||
|
||||
impl From<f32> for Spacing {
|
||||
fn from(overflow_decoration: f32) -> Self {
|
||||
Self {
|
||||
overflow_decoration,
|
||||
zone_gap: 8.,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn frame<'a, M: 'a>(
|
||||
panel: Cow<'a, Panel>,
|
||||
samples: Vec<Sample<'a, M>>,
|
||||
spacing: impl Into<Spacing>,
|
||||
initial: Resolution,
|
||||
build: impl Fn(&Resolution) -> Element<'a, M> + 'a,
|
||||
changed: impl Fn(Resolution) -> M + 'a,
|
||||
) -> Element<'a, M> {
|
||||
let content = build(&initial);
|
||||
let spacing = spacing.into();
|
||||
Element::new(Adaptive {
|
||||
panel,
|
||||
samples,
|
||||
overflow_width: spacing.overflow_decoration,
|
||||
zone_gap: spacing.zone_gap,
|
||||
content,
|
||||
resolution: initial,
|
||||
build: Box::new(build),
|
||||
changed: Box::new(changed),
|
||||
})
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
struct State {
|
||||
published: Option<Resolution>,
|
||||
}
|
||||
type Build<'a, M> = Box<dyn Fn(&Resolution) -> Element<'a, M> + 'a>;
|
||||
struct Adaptive<'a, M> {
|
||||
panel: Cow<'a, Panel>,
|
||||
samples: Vec<Sample<'a, M>>,
|
||||
overflow_width: f32,
|
||||
zone_gap: f32,
|
||||
content: Element<'a, M>,
|
||||
resolution: Resolution,
|
||||
build: Build<'a, M>,
|
||||
changed: Box<dyn Fn(Resolution) -> M + 'a>,
|
||||
}
|
||||
|
||||
impl<M> Widget<M, Theme, cosmic::Renderer> for Adaptive<'_, M> {
|
||||
fn tag(&self) -> widget::tree::Tag {
|
||||
widget::tree::Tag::of::<State>()
|
||||
}
|
||||
fn state(&self) -> widget::tree::State {
|
||||
widget::tree::State::new(State::default())
|
||||
}
|
||||
fn children(&self) -> Vec<widget::Tree> {
|
||||
std::iter::once(widget::Tree::new(&self.content))
|
||||
.chain(self.samples.iter().map(|sample| widget::Tree::new(&sample.view)))
|
||||
.collect()
|
||||
}
|
||||
fn diff(&mut self, tree: &mut widget::Tree) {
|
||||
tree.children.truncate(self.samples.len() + 1);
|
||||
if tree.children.is_empty() {
|
||||
tree.children.push(widget::Tree::new(&self.content));
|
||||
}
|
||||
tree.children[0].diff(self.content.as_widget_mut());
|
||||
for (index, sample) in self.samples.iter_mut().enumerate() {
|
||||
if tree.children.len() == index + 1 {
|
||||
tree.children.push(widget::Tree::new(&sample.view));
|
||||
}
|
||||
tree.children[index + 1].diff(sample.view.as_widget_mut());
|
||||
}
|
||||
}
|
||||
fn size(&self) -> Size<Length> {
|
||||
Size::new(Length::Fill, Length::Fill)
|
||||
}
|
||||
fn layout(
|
||||
&mut self,
|
||||
tree: &mut widget::Tree,
|
||||
renderer: &cosmic::Renderer,
|
||||
limits: &layout::Limits,
|
||||
) -> layout::Node {
|
||||
let mut measurements: Vec<Measurement> = Vec::new();
|
||||
// Measure preferred content before imposing the panel's width. Otherwise
|
||||
// a clipped wide control can look as small as its compact alternative.
|
||||
let measurement_limits = layout::Limits::new(Size::ZERO, Size::new(f32::INFINITY, limits.max().height));
|
||||
for (index, sample) in self.samples.iter_mut().enumerate() {
|
||||
let node = sample
|
||||
.view
|
||||
.as_widget_mut()
|
||||
.layout(&mut tree.children[index + 1], renderer, &measurement_limits);
|
||||
let width = node.size().width;
|
||||
if let Some(measurement) = measurements.iter_mut().find(|measurement| measurement.id == sample.id) {
|
||||
measurement.alternatives.push((sample.representation, width));
|
||||
} else {
|
||||
measurements.push(Measurement {
|
||||
id: sample.id.clone(),
|
||||
alternatives: vec![(sample.representation, width)],
|
||||
minimum: sample.minimum,
|
||||
});
|
||||
}
|
||||
}
|
||||
let trigger = measurements
|
||||
.iter()
|
||||
.find(|measurement| measurement.id.0 == "_overflow")
|
||||
.map_or(0.0, |measurement| measurement.alternatives[0].1);
|
||||
let trigger = trigger.min((limits.max().width - self.overflow_width).max(0.0));
|
||||
self.resolution = resolve_with_gap(
|
||||
&self.panel,
|
||||
&measurements,
|
||||
limits.max().width,
|
||||
(self.overflow_width + trigger).min(limits.max().width),
|
||||
self.zone_gap,
|
||||
);
|
||||
self.resolution.overflow_trigger_width = trigger;
|
||||
self.content = (self.build)(&self.resolution);
|
||||
tree.children[0].diff(self.content.as_widget_mut());
|
||||
self.content
|
||||
.as_widget_mut()
|
||||
.layout(&mut tree.children[0], renderer, limits)
|
||||
}
|
||||
fn a11y_nodes(
|
||||
&self,
|
||||
layout: Layout<'_>,
|
||||
tree: &widget::Tree,
|
||||
cursor: mouse::Cursor,
|
||||
) -> iced_accessibility::A11yTree {
|
||||
self.content.as_widget().a11y_nodes(layout, &tree.children[0], cursor)
|
||||
}
|
||||
fn update(
|
||||
&mut self,
|
||||
tree: &mut widget::Tree,
|
||||
event: &Event,
|
||||
layout: Layout<'_>,
|
||||
cursor: mouse::Cursor,
|
||||
renderer: &cosmic::Renderer,
|
||||
clipboard: &mut dyn Clipboard,
|
||||
shell: &mut Shell<'_, M>,
|
||||
viewport: &Rectangle,
|
||||
) {
|
||||
self.content.as_widget_mut().update(
|
||||
&mut tree.children[0],
|
||||
event,
|
||||
layout,
|
||||
cursor,
|
||||
renderer,
|
||||
clipboard,
|
||||
shell,
|
||||
viewport,
|
||||
);
|
||||
let state = tree.state.downcast_mut::<State>();
|
||||
if matches!(event, Event::Window(cosmic::iced::window::Event::RedrawRequested(_)))
|
||||
&& state.published.as_ref() != Some(&self.resolution)
|
||||
{
|
||||
state.published = Some(self.resolution.clone());
|
||||
shell.publish((self.changed)(self.resolution.clone()));
|
||||
}
|
||||
}
|
||||
fn draw(
|
||||
&self,
|
||||
tree: &widget::Tree,
|
||||
renderer: &mut cosmic::Renderer,
|
||||
theme: &Theme,
|
||||
style: &renderer::Style,
|
||||
layout: Layout<'_>,
|
||||
cursor: mouse::Cursor,
|
||||
viewport: &Rectangle,
|
||||
) {
|
||||
self.content
|
||||
.as_widget()
|
||||
.draw(&tree.children[0], renderer, theme, style, layout, cursor, viewport);
|
||||
}
|
||||
fn mouse_interaction(
|
||||
&self,
|
||||
tree: &widget::Tree,
|
||||
layout: Layout<'_>,
|
||||
cursor: mouse::Cursor,
|
||||
viewport: &Rectangle,
|
||||
renderer: &cosmic::Renderer,
|
||||
) -> mouse::Interaction {
|
||||
self.content
|
||||
.as_widget()
|
||||
.mouse_interaction(&tree.children[0], layout, cursor, viewport, renderer)
|
||||
}
|
||||
fn operate(
|
||||
&mut self,
|
||||
tree: &mut widget::Tree,
|
||||
layout: Layout<'_>,
|
||||
renderer: &cosmic::Renderer,
|
||||
operation: &mut dyn widget::Operation,
|
||||
) {
|
||||
self.content
|
||||
.as_widget_mut()
|
||||
.operate(&mut tree.children[0], layout, renderer, operation);
|
||||
}
|
||||
fn overlay<'a>(
|
||||
&'a mut self,
|
||||
tree: &'a mut widget::Tree,
|
||||
layout: Layout<'a>,
|
||||
renderer: &cosmic::Renderer,
|
||||
viewport: &Rectangle,
|
||||
translation: Vector,
|
||||
) -> Option<cosmic::iced::advanced::overlay::Element<'a, M, Theme, cosmic::Renderer>> {
|
||||
self.content
|
||||
.as_widget_mut()
|
||||
.overlay(&mut tree.children[0], layout, renderer, viewport, translation)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use cosmic::iced::advanced::{clipboard, renderer::Headless};
|
||||
use cosmic::iced::{Font, Pixels, Point};
|
||||
use cosmic::widget::{button, text};
|
||||
use ferese_config::panel::OverflowPolicy;
|
||||
use ferese_config::panel::layout::Placement;
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
enum Probe {
|
||||
Resolved(Resolution),
|
||||
Click,
|
||||
MeasurementClick,
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn group_borders_do_not_add_a_fill_or_change_content_colors() {
|
||||
use cosmic::iced::Color;
|
||||
let outline = Color::from_rgb(0.4, 0.5, 0.6);
|
||||
let enabled = group_border(outline, [0., 0., 12., 16.], true);
|
||||
let disabled = group_border(outline, [0., 0., 12., 16.], false);
|
||||
assert!(enabled.background.is_none() && disabled.background.is_none());
|
||||
assert_eq!(enabled.border.width, 1.);
|
||||
assert_eq!(enabled.border.color, outline);
|
||||
assert_eq!(disabled.border.width, 0.);
|
||||
assert_eq!(disabled.border.radius, enabled.border.radius);
|
||||
assert!(enabled.text_color.is_none() && enabled.icon_color.is_none());
|
||||
assert!(disabled.text_color.is_none() && disabled.icon_color.is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn drawing_an_outlined_group_does_not_raise_panel_background_alpha() {
|
||||
use cosmic::iced::advanced::{Renderer, renderer};
|
||||
use cosmic::iced::{Color, widget as widgets};
|
||||
let runtime = tokio::runtime::Builder::new_current_thread()
|
||||
.enable_all()
|
||||
.build()
|
||||
.unwrap();
|
||||
let mut renderer = runtime
|
||||
.block_on(<cosmic::Renderer as Headless>::new(
|
||||
Font::default(),
|
||||
Pixels(14.),
|
||||
Some("tiny-skia"),
|
||||
))
|
||||
.unwrap();
|
||||
let bounds = Rectangle::new(Point::ORIGIN, Size::new(40., 40.));
|
||||
for opacity in [0., 0.5, 1.] {
|
||||
for border in [false, true] {
|
||||
renderer.reset(bounds);
|
||||
let group = cosmic::widget::container(widgets::Space::new().width(40).height(40)).class(
|
||||
cosmic::theme::Container::custom(move |_| group_border(Color::WHITE, 8., border)),
|
||||
);
|
||||
let mut view: Element<'_, ()> = cosmic::widget::container(group)
|
||||
.class(cosmic::theme::Container::custom(move |_| {
|
||||
crate::controls::surface_appearance(
|
||||
Color {
|
||||
a: opacity,
|
||||
..Color::WHITE
|
||||
},
|
||||
8.,
|
||||
)
|
||||
}))
|
||||
.into();
|
||||
let mut tree = widget::Tree::new(&view);
|
||||
let node =
|
||||
view.as_widget_mut()
|
||||
.layout(&mut tree, &renderer, &layout::Limits::new(Size::ZERO, bounds.size()));
|
||||
view.as_widget().draw(
|
||||
&tree,
|
||||
&mut renderer,
|
||||
&Theme::default(),
|
||||
&renderer::Style {
|
||||
text_color: Color::WHITE,
|
||||
icon_color: Color::WHITE,
|
||||
scale_factor: 1.,
|
||||
},
|
||||
Layout::new(&node),
|
||||
mouse::Cursor::Unavailable,
|
||||
&bounds,
|
||||
);
|
||||
let pixels = Headless::screenshot(&mut renderer, Size::new(40, 40), 1., Color::TRANSPARENT);
|
||||
let alpha = pixels[(20 * 40 + 20) * 4 + 3];
|
||||
assert!(
|
||||
i16::from(alpha).abs_diff((opacity * 255.).round() as i16) <= 1,
|
||||
"opacity={opacity}, border={border}, rendered alpha={alpha}"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn measured_widgets_adapt_publish_once_and_only_visible_controls_receive_input() {
|
||||
let runtime = tokio::runtime::Builder::new_current_thread()
|
||||
.enable_all()
|
||||
.build()
|
||||
.unwrap();
|
||||
let renderer = runtime
|
||||
.block_on(<cosmic::Renderer as Headless>::new(
|
||||
Font::default(),
|
||||
Pixels(14.),
|
||||
Some("tiny-skia"),
|
||||
))
|
||||
.unwrap();
|
||||
let mut panel = Panel::default();
|
||||
panel.start.groups.clear();
|
||||
panel.center.groups.clear();
|
||||
panel.end.groups.retain(|group| group.id.0 == "time");
|
||||
let id = ItemId("clock".into());
|
||||
let mut tree = None;
|
||||
for (width, always) in [(500., false), (75., false), (100., true), (500., false)] {
|
||||
panel.end.groups[0].items[0].overflow = if always {
|
||||
OverflowPolicy::Always
|
||||
} else {
|
||||
OverflowPolicy::Auto
|
||||
};
|
||||
let samples = [
|
||||
(Representation::Wide, "Wednesday, 7 October · 14:35"),
|
||||
(Representation::Compact, "14:35"),
|
||||
(Representation::Icon, "+"),
|
||||
]
|
||||
.into_iter()
|
||||
.map(|(representation, label)| Sample {
|
||||
id: id.clone(),
|
||||
representation,
|
||||
minimum: None,
|
||||
view: button::custom(text(label).wrapping(cosmic::iced::widget::text::Wrapping::None))
|
||||
.height(28)
|
||||
.on_press(Probe::MeasurementClick)
|
||||
.into(),
|
||||
})
|
||||
.chain(std::iter::once(Sample {
|
||||
id: ItemId("_overflow".into()),
|
||||
representation: Representation::Icon,
|
||||
minimum: None,
|
||||
view: button::custom(text("+"))
|
||||
.height(28)
|
||||
.on_press(Probe::MeasurementClick)
|
||||
.into(),
|
||||
}))
|
||||
.collect();
|
||||
let id = id.clone();
|
||||
let mut view = frame(
|
||||
Cow::Borrowed(&panel),
|
||||
samples,
|
||||
0.,
|
||||
Resolution::default(),
|
||||
move |resolution| {
|
||||
let width = match resolution.items.get(&id) {
|
||||
Some(Placement::Visible { width, .. }) => *width,
|
||||
_ => resolution.overflow_trigger_width,
|
||||
};
|
||||
button::custom(text("+"))
|
||||
.width(width)
|
||||
.height(28)
|
||||
.on_press(Probe::Click)
|
||||
.into()
|
||||
},
|
||||
Probe::Resolved,
|
||||
);
|
||||
let tree = tree.get_or_insert_with(|| widget::Tree::new(&view));
|
||||
tree.diff(&mut view);
|
||||
let viewport = Rectangle::new(Point::ORIGIN, Size::new(width, 28.));
|
||||
let limits = layout::Limits::new(Size::ZERO, viewport.size());
|
||||
let node = view.as_widget_mut().layout(tree, &renderer, &limits);
|
||||
let mut messages = Vec::new();
|
||||
for _ in 0..4 {
|
||||
view.as_widget_mut().update(
|
||||
tree,
|
||||
&Event::Window(cosmic::iced::window::Event::RedrawRequested(std::time::Instant::now())),
|
||||
Layout::new(&node),
|
||||
mouse::Cursor::Unavailable,
|
||||
&renderer,
|
||||
&mut clipboard::Null,
|
||||
&mut Shell::new(&mut messages),
|
||||
&viewport,
|
||||
);
|
||||
}
|
||||
assert_eq!(messages.len(), 1);
|
||||
let Probe::Resolved(resolution) = &messages[0] else {
|
||||
panic!("expected measured resolution")
|
||||
};
|
||||
assert!(resolution.fits(width));
|
||||
if always {
|
||||
assert_eq!(resolution.overflow, [ItemId("clock".into())]);
|
||||
} else if width == 500. {
|
||||
assert!(matches!(
|
||||
resolution.items.get(&ItemId("clock".into())),
|
||||
Some(Placement::Visible {
|
||||
representation: Representation::Wide,
|
||||
..
|
||||
})
|
||||
));
|
||||
} else {
|
||||
assert!(matches!(
|
||||
resolution.items.get(&ItemId("clock".into())),
|
||||
Some(Placement::Visible {
|
||||
representation: Representation::Compact | Representation::Icon,
|
||||
..
|
||||
})
|
||||
));
|
||||
}
|
||||
for event in [
|
||||
mouse::Event::ButtonPressed(mouse::Button::Left),
|
||||
mouse::Event::ButtonReleased(mouse::Button::Left),
|
||||
] {
|
||||
view.as_widget_mut().update(
|
||||
tree,
|
||||
&Event::Mouse(event),
|
||||
Layout::new(&node),
|
||||
mouse::Cursor::Available(Point::new(5., 10.)),
|
||||
&renderer,
|
||||
&mut clipboard::Null,
|
||||
&mut Shell::new(&mut messages),
|
||||
&viewport,
|
||||
);
|
||||
}
|
||||
assert_eq!(
|
||||
messages
|
||||
.iter()
|
||||
.filter(|message| matches!(message, Probe::Click))
|
||||
.count(),
|
||||
1
|
||||
);
|
||||
assert!(
|
||||
!messages
|
||||
.iter()
|
||||
.any(|message| matches!(message, Probe::MeasurementClick))
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,323 @@
|
||||
use std::borrow::Cow;
|
||||
|
||||
use cosmic::iced::{Alignment, Color, Length};
|
||||
use cosmic::widget::{Space, container, row};
|
||||
use cosmic::{Element, theme};
|
||||
use ferese_config::panel::WorkspaceStyle;
|
||||
|
||||
use crate::Palette;
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct Workspace<'a> {
|
||||
pub name: Cow<'a, str>,
|
||||
pub index: u32,
|
||||
pub window_count: u32,
|
||||
pub active: bool,
|
||||
pub visible_elsewhere: bool,
|
||||
}
|
||||
|
||||
pub fn width(style: WorkspaceStyle) -> f32 {
|
||||
match style {
|
||||
WorkspaceStyle::Numbers | WorkspaceStyle::Dots => 24.,
|
||||
WorkspaceStyle::Tabs => 48.,
|
||||
WorkspaceStyle::WindowStacks => 32.,
|
||||
WorkspaceStyle::AppIcons => 48.,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn tooltip_label(workspace: &Workspace<'_>) -> String {
|
||||
let name = if workspace.name.is_empty() || workspace.name == workspace.index.to_string() {
|
||||
String::new()
|
||||
} else {
|
||||
format!(" · {}", workspace.name)
|
||||
};
|
||||
format!(
|
||||
"Workspace {}{name} · {} {}{}",
|
||||
workspace.index,
|
||||
workspace.window_count,
|
||||
if workspace.window_count == 1 {
|
||||
"window"
|
||||
} else {
|
||||
"windows"
|
||||
},
|
||||
if workspace.active { " · Active" } else { "" },
|
||||
)
|
||||
}
|
||||
|
||||
pub fn indicator<'a, M: 'a>(
|
||||
style: WorkspaceStyle,
|
||||
workspace: Workspace<'a>,
|
||||
palette: Palette,
|
||||
font: cosmic::font::Font,
|
||||
height: f32,
|
||||
progress: f32,
|
||||
apps: Vec<Element<'a, M>>,
|
||||
) -> Element<'a, M> {
|
||||
let progress = progress.clamp(0., 1.);
|
||||
let occupied = workspace.window_count > 0;
|
||||
let neutral = if occupied { palette.text } else { palette.muted };
|
||||
let foreground = crate::mix(neutral, palette.accent, progress);
|
||||
let content: Element<'a, M> = match style {
|
||||
WorkspaceStyle::Numbers | WorkspaceStyle::Tabs => {
|
||||
let label = if style == WorkspaceStyle::Tabs && !workspace.name.trim().is_empty() {
|
||||
workspace.name.into_owned()
|
||||
} else {
|
||||
workspace.index.to_string()
|
||||
};
|
||||
|
||||
crate::text(label, font)
|
||||
.size(if style == WorkspaceStyle::Tabs { 11 } else { 12 })
|
||||
.width(width(style) - 8.)
|
||||
.align_x(cosmic::iced::alignment::Horizontal::Center)
|
||||
.wrapping(cosmic::iced::widget::text::Wrapping::None)
|
||||
.ellipsize(cosmic::iced::widget::text::Ellipsize::End(
|
||||
cosmic::iced::advanced::text::EllipsizeHeightLimit::Lines(1),
|
||||
))
|
||||
.class(theme::Text::Color(foreground))
|
||||
.into()
|
||||
}
|
||||
WorkspaceStyle::Dots => container(Space::new())
|
||||
.width(6. + 10. * progress)
|
||||
.height(6)
|
||||
.class(theme::Container::custom(move |_| {
|
||||
let mut paint = crate::controls::surface_appearance(
|
||||
foreground.scale_alpha(if occupied { 0.65 + 0.35 * progress } else { progress }),
|
||||
3.,
|
||||
);
|
||||
paint.border.width = 1.;
|
||||
paint.border.color = foreground.scale_alpha(if occupied { 0.65 } else { 0.55 });
|
||||
paint
|
||||
}))
|
||||
.into(),
|
||||
WorkspaceStyle::WindowStacks => {
|
||||
let back = match workspace.window_count {
|
||||
0 | 1 => "",
|
||||
2 => "<path d=\"M6 4h13a2 2 0 0 1 2 2v9\"/>",
|
||||
_ => "<path d=\"M6 4h13a2 2 0 0 1 2 2v9M9 1h13a2 2 0 0 1 2 2v9\"/>",
|
||||
};
|
||||
let svg = format!(
|
||||
"<svg xmlns=\"http://www.w3.org/2000/svg\" viewBox=\"0 0 26 22\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"1.4\" stroke-linejoin=\"round\">{back}<rect x=\"2\" y=\"7\" width=\"16\" height=\"12\" rx=\"2.5\"/>{}</svg>",
|
||||
if occupied { "<path d=\"M2 11h16\"/>" } else { "" }
|
||||
);
|
||||
|
||||
cosmic::widget::icon::from_svg_bytes(crate::icons::tint_svg(svg.as_bytes(), foreground, foreground))
|
||||
.symbolic(false)
|
||||
.icon()
|
||||
.size(20)
|
||||
.class(theme::Svg::custom(|_| cosmic::iced::widget::svg::Style { color: None }))
|
||||
.into()
|
||||
}
|
||||
WorkspaceStyle::AppIcons => {
|
||||
let mut icons = row::with_capacity(2).spacing(3).align_y(Alignment::Center);
|
||||
|
||||
if apps.is_empty() {
|
||||
icons = icons.push(crate::icons::tinted(crate::icons::OVERVIEW, 16, foreground));
|
||||
} else {
|
||||
for app in apps.into_iter().take(2) {
|
||||
icons = icons.push(app);
|
||||
}
|
||||
}
|
||||
icons.into()
|
||||
}
|
||||
};
|
||||
|
||||
let face = container(content).center_x(width(style)).center_y(height);
|
||||
let face: Element<'a, M> = if style == WorkspaceStyle::Dots {
|
||||
face.into()
|
||||
} else {
|
||||
let marker = container(Space::new())
|
||||
.width(10)
|
||||
.height(2)
|
||||
.class(crate::controls::surface(foreground.scale_alpha(progress), 1.));
|
||||
cosmic::iced::widget::stack![
|
||||
face,
|
||||
container(marker)
|
||||
.width(Length::Fill)
|
||||
.height(Length::Fill)
|
||||
.align_x(cosmic::iced::alignment::Horizontal::Center)
|
||||
.align_y(cosmic::iced::alignment::Vertical::Bottom)
|
||||
.padding([1, 0]),
|
||||
]
|
||||
.into()
|
||||
};
|
||||
|
||||
container(face)
|
||||
.width(width(style))
|
||||
.height(height)
|
||||
.clip_to_border(true)
|
||||
.class(theme::Container::custom(move |_| {
|
||||
let fill = if style == WorkspaceStyle::Dots {
|
||||
Color::TRANSPARENT
|
||||
} else if progress > 0. {
|
||||
palette.accent.scale_alpha(0.16 * progress)
|
||||
} else if style == WorkspaceStyle::Tabs || occupied && style == WorkspaceStyle::Numbers {
|
||||
palette.text.scale_alpha(0.045)
|
||||
} else {
|
||||
Color::TRANSPARENT
|
||||
};
|
||||
|
||||
let mut paint = crate::controls::surface_appearance(fill, palette.radius.min(8.));
|
||||
|
||||
if workspace.visible_elsewhere {
|
||||
paint.border.width = 1.;
|
||||
paint.border.color = palette.accent.scale_alpha(0.55);
|
||||
}
|
||||
paint
|
||||
}))
|
||||
.into()
|
||||
}
|
||||
|
||||
pub fn sample<'a, M: 'a>(
|
||||
style: WorkspaceStyle,
|
||||
palette: Palette,
|
||||
font: cosmic::font::Font,
|
||||
height: f32,
|
||||
) -> Element<'a, M> {
|
||||
let mut samples = row::with_capacity(3).spacing(1).align_y(Alignment::Center);
|
||||
|
||||
for (index, count, active) in [(1, 2, true), (2, 1, false), (3, 0, false)] {
|
||||
let apps = if style == WorkspaceStyle::AppIcons && count > 0 {
|
||||
let mut apps = vec![crate::icons::tinted(crate::icons::SETTINGS, 16, palette.text).into()];
|
||||
|
||||
if count > 1 {
|
||||
apps.push(crate::icons::tinted(crate::icons::FERESE, 16, palette.accent).into());
|
||||
}
|
||||
|
||||
apps
|
||||
} else {
|
||||
Vec::new()
|
||||
};
|
||||
|
||||
samples = samples.push(indicator(
|
||||
style,
|
||||
Workspace {
|
||||
name: Cow::Owned(index.to_string()),
|
||||
index,
|
||||
window_count: count,
|
||||
active,
|
||||
visible_elsewhere: false,
|
||||
},
|
||||
palette,
|
||||
font,
|
||||
height,
|
||||
if active { 1. } else { 0. },
|
||||
apps,
|
||||
));
|
||||
}
|
||||
samples.into()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use cosmic::iced::advanced::{Layout, Renderer, layout, renderer, renderer::Headless, widget::Tree};
|
||||
use cosmic::iced::{Font, Pixels, Rectangle, Size, mouse};
|
||||
|
||||
#[test]
|
||||
fn indicators_keep_their_allocation_and_active_shape_in_every_style() {
|
||||
let runtime = tokio::runtime::Builder::new_current_thread()
|
||||
.enable_all()
|
||||
.build()
|
||||
.unwrap();
|
||||
let mut renderer = runtime
|
||||
.block_on(<cosmic::Renderer as Headless>::new(
|
||||
Font::default(),
|
||||
Pixels(14.),
|
||||
Some("tiny-skia"),
|
||||
))
|
||||
.unwrap();
|
||||
let palette = Palette::from_resolved(&ferese_config::theme::default_theme());
|
||||
let theme = palette.native_theme();
|
||||
for style in WorkspaceStyle::ALL {
|
||||
for height in [20., 28., 36.] {
|
||||
let bounds = Rectangle::with_size(Size::new(width(style), height));
|
||||
let mut active_alpha = Vec::new();
|
||||
let mut inactive_alpha = Vec::new();
|
||||
for (count, progress, name) in [
|
||||
(0, 0., ""),
|
||||
(1, 0., "1"),
|
||||
(3, 0., "Design and development"),
|
||||
(3, 0.5, "Design and development"),
|
||||
(3, 1., "Design and development"),
|
||||
] {
|
||||
let apps = (0..count.min(2))
|
||||
.map(|_| crate::icons::tinted(crate::icons::SETTINGS, 16, palette.text).into())
|
||||
.collect();
|
||||
let mut view: Element<'_, ()> = indicator(
|
||||
style,
|
||||
Workspace {
|
||||
name: name.into(),
|
||||
index: 1,
|
||||
window_count: count,
|
||||
active: progress == 1.,
|
||||
visible_elsewhere: false,
|
||||
},
|
||||
palette,
|
||||
Font::default(),
|
||||
height,
|
||||
progress,
|
||||
apps,
|
||||
);
|
||||
let mut tree = Tree::new(&view);
|
||||
let node = view.as_widget_mut().layout(
|
||||
&mut tree,
|
||||
&renderer,
|
||||
&layout::Limits::new(Size::ZERO, bounds.size()),
|
||||
);
|
||||
assert_eq!(
|
||||
node.bounds().size(),
|
||||
bounds.size(),
|
||||
"{style:?}, height={height}, count={count}, progress={progress}"
|
||||
);
|
||||
renderer.reset(bounds);
|
||||
view.as_widget().draw(
|
||||
&tree,
|
||||
&mut renderer,
|
||||
&theme,
|
||||
&renderer::Style {
|
||||
text_color: palette.text,
|
||||
icon_color: palette.text,
|
||||
scale_factor: 1.,
|
||||
},
|
||||
Layout::new(&node),
|
||||
mouse::Cursor::Unavailable,
|
||||
&bounds,
|
||||
);
|
||||
let pixels = Headless::screenshot(
|
||||
&mut renderer,
|
||||
Size::new(width(style) as u32, height as u32),
|
||||
1.,
|
||||
Color::TRANSPARENT,
|
||||
);
|
||||
let alpha: Vec<_> = pixels.chunks_exact(4).map(|p| p[3]).collect();
|
||||
assert!(alpha.iter().any(|a| *a > 0), "{style:?} rendered empty");
|
||||
if count == 3 && progress == 0. {
|
||||
inactive_alpha = alpha;
|
||||
} else if progress == 1. {
|
||||
active_alpha = alpha;
|
||||
}
|
||||
}
|
||||
assert_ne!(
|
||||
active_alpha, inactive_alpha,
|
||||
"{style:?} needs an active shape that survives removal of color"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hover_details_include_names_and_pluralize_window_counts() {
|
||||
let mut workspace = Workspace {
|
||||
name: "Design".into(),
|
||||
index: 2,
|
||||
window_count: 1,
|
||||
active: true,
|
||||
visible_elsewhere: false,
|
||||
};
|
||||
assert_eq!(tooltip_label(&workspace), "Workspace 2 · Design · 1 window · Active");
|
||||
workspace.name = "2".into();
|
||||
workspace.window_count = 0;
|
||||
workspace.active = false;
|
||||
assert_eq!(tooltip_label(&workspace), "Workspace 2 · 0 windows");
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user