use std::sync::Arc;
use super::{
IconChoice, icons, names,
recipe::{Case, Interaction, Name, Recipe, ResolvedPart, ResolvedRecipe, Selector},
select::px,
shared::{fading, glyph, one_line},
theme::{Themed, current_theme},
};
pub use crate::node::WindowControl;
use crate::{
app::{
ctx::Ctx,
events::MouseEvent,
theme::{BorderSize, PaletteColor, RadiusSize, Theme},
window::WindowHandle,
},
components::{self, ChromeBorderPolicy, ChromeTitleBar, Column, ResizeHandlePolicy, Row, Stack, WindowChromeMode},
layout::{Alignment, layout_kind::Justify, text_style::FontWeight},
node::{BackgroundColor, Element, border::Border, color::Color, dimension::Dimension},
};
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum WindowPlatform {
Windows,
Macos,
Gnome,
Kde,
}
names!(WindowPlatform {
Windows => "windows",
Macos => "macos",
Gnome => "gnome",
Kde => "kde",
});
impl WindowPlatform {
pub fn current() -> Self {
if cfg!(target_os = "windows") {
Self::Windows
} else if cfg!(target_os = "macos") {
Self::Macos
} else {
let desktop = std::env::var("XDG_CURRENT_DESKTOP").unwrap_or_default();
if desktop.to_ascii_uppercase().contains("KDE") {
Self::Kde
} else {
Self::Gnome
}
}
}
pub const ALL: [Self; 4] = [Self::Windows, Self::Macos, Self::Gnome, Self::Kde];
pub fn controls_at_start(self) -> bool {
self == Self::Macos
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum WindowChromePart {
Root,
Bar,
Line,
Icon,
Title,
Balance,
Controls,
Minimize,
Maximize,
Close,
MinimizeGlyph,
MaximizeGlyph,
CloseGlyph,
}
names!(WindowChromePart {
Root => "root",
Bar => "bar",
Line => "line",
Icon => "icon",
Title => "title",
Balance => "balance",
Controls => "controls",
Minimize => "minimize",
Maximize => "maximize",
Close => "close",
MinimizeGlyph => "minimize_glyph",
MaximizeGlyph => "maximize_glyph",
CloseGlyph => "close_glyph",
});
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum WindowChromeState {
Inactive,
Maximized,
Tabs,
}
names!(WindowChromeState {
Inactive => "inactive",
Maximized => "maximized",
Tabs => "tabs",
});
pub type WindowChromeRenderer = Arc<dyn Fn(WindowChromeView) -> Element + Send + Sync>;
type Handler = Arc<dyn Fn() + Send + Sync>;
#[derive(Clone)]
pub struct WindowControls {
minimizable: bool,
maximizable: bool,
minimize_label: Arc<str>,
maximize_label: Arc<str>,
restore_label: Arc<str>,
close_label: Arc<str>,
on_close: Vec<Handler>,
}
impl Default for WindowControls {
fn default() -> Self {
Self::new()
}
}
impl WindowControls {
pub fn new() -> Self {
Self {
minimizable: true,
maximizable: true,
minimize_label: super::current_locale().navigation.minimize.clone(),
maximize_label: super::current_locale().navigation.maximize.clone(),
restore_label: super::current_locale().navigation.restore.clone(),
close_label: super::current_locale().common.close.clone(),
on_close: Vec::new(),
}
}
pub fn minimizable(mut self, minimizable: bool) -> Self {
self.minimizable = minimizable;
self
}
pub fn maximizable(mut self, maximizable: bool) -> Self {
self.maximizable = maximizable;
self
}
pub fn minimize_label(mut self, label: &str) -> Self {
self.minimize_label = Arc::from(label);
self
}
pub fn maximize_label(mut self, label: &str) -> Self {
self.maximize_label = Arc::from(label);
self
}
pub fn restore_label(mut self, label: &str) -> Self {
self.restore_label = Arc::from(label);
self
}
pub fn close_label(mut self, label: &str) -> Self {
self.close_label = Arc::from(label);
self
}
pub fn on_close(mut self, handler: impl Fn() + Send + Sync + 'static) -> Self {
self.on_close.push(Arc::new(handler));
self
}
}
pub struct WindowChrome {
platform: Option<WindowPlatform>,
icon: WindowChromeIcon,
title: Option<Arc<str>>,
label: Option<Arc<str>>,
leading: Option<Element>,
trailing: Option<Element>,
tabs: Option<Element>,
controls: WindowControls,
content: Option<Element>,
overlays: Vec<Element>,
mode: WindowChromeMode,
resize_handles: ResizeHandlePolicy,
border: ChromeBorderPolicy,
states: Vec<Name>,
rules: Recipe,
forced: Option<Interaction>,
id: Option<Arc<str>>,
key: Option<Arc<str>>,
}
impl Default for WindowChrome {
fn default() -> Self {
Self::new()
}
}
impl WindowChrome {
pub fn new() -> Self {
Self {
platform: None,
icon: WindowChromeIcon::Window,
title: None,
label: None,
leading: None,
trailing: None,
tabs: None,
controls: WindowControls::new(),
content: None,
overlays: Vec::new(),
mode: WindowChromeMode::PlatformDefault,
resize_handles: ResizeHandlePolicy::PlatformDefault,
border: ChromeBorderPolicy::PlatformDefault,
states: Vec::new(),
rules: Recipe::new(),
forced: None,
id: None,
key: None,
}
}
pub fn platform(mut self, platform: WindowPlatform) -> Self {
self.platform = Some(platform);
self
}
pub fn icon(mut self, icon: impl Into<WindowChromeIcon>) -> Self {
self.icon = icon.into();
self
}
pub fn title(mut self, title: &str) -> Self {
self.title = Some(Arc::from(title));
self
}
pub fn label(mut self, label: &str) -> Self {
self.label = Some(Arc::from(label));
self
}
pub fn leading(mut self, element: impl Into<Element>) -> Self {
self.leading = Some(element.into());
self
}
pub fn trailing(mut self, element: impl Into<Element>) -> Self {
self.trailing = Some(element.into());
self
}
pub fn tabs(mut self, tabs: impl Into<Element>) -> Self {
self.tabs = Some(tabs.into());
self
}
pub fn controls(mut self, controls: WindowControls) -> Self {
self.controls = controls;
self
}
pub fn content(mut self, content: impl Into<Element>) -> Self {
self.content = Some(content.into());
self
}
pub fn overlay(mut self, overlay: impl Into<Element>) -> Self {
self.overlays.push(overlay.into());
self
}
pub fn overlays(mut self, overlays: impl IntoIterator<Item = impl Into<Element>>) -> Self {
self.overlays.extend(overlays.into_iter().map(Into::into));
self
}
pub fn mode(mut self, mode: WindowChromeMode) -> Self {
self.mode = mode;
self
}
pub fn resize_handles(mut self, handles: ResizeHandlePolicy) -> Self {
self.resize_handles = handles;
self
}
pub fn border(mut self, border: ChromeBorderPolicy) -> Self {
self.border = border;
self
}
pub fn state(mut self, state: impl Into<Name>, on: bool) -> Self {
let state = state.into();
self.states.retain(|held| *held != state);
if on {
self.states.push(state);
}
self
}
pub fn style(mut self, part: impl Into<Name>, style: impl FnOnce(super::PartStyle) -> super::PartStyle) -> Self {
self.rules = self.rules.base(part, style);
self
}
pub fn rules(mut self, rules: &Recipe) -> Self {
self.rules = self.rules.extend(rules);
self
}
pub fn force(mut self, interaction: Option<Interaction>) -> Self {
self.forced = interaction;
self
}
pub fn id(mut self, id: impl Into<Arc<str>>) -> Self {
self.id = Some(id.into());
self
}
pub fn key(mut self, key: impl Into<Arc<str>>) -> Self {
self.key = Some(key.into());
self
}
fn view(self, theme: &Theme, window: Option<WindowHandle>) -> (WindowChromeView, Option<Element>) {
let platform = self.platform.unwrap_or_else(WindowPlatform::current);
let (inactive, maximized) = match &window {
Some(window) => (!window.is_focused, window.is_maximized),
None => (
self.states.contains(&Name::from(WindowChromeState::Inactive)),
self.states.contains(&Name::from(WindowChromeState::Maximized)),
),
};
let case = Case {
variant: Some(platform.into()),
size: None,
density: None,
breakpoint: super::current_breakpoint(),
states: self.states.clone(),
}
.state(WindowChromeState::Inactive, inactive)
.state(WindowChromeState::Maximized, maximized)
.state(WindowChromeState::Tabs, self.tabs.is_some());
let tabbed = self.tabs.is_some();
let shown_in = window
.as_ref()
.map(WindowHandle::state)
.or_else(super::theme::current_window);
let icon = self.icon.shown(shown_in.as_ref());
let view = WindowChromeView {
platform,
icon,
title: self.title,
label: self.label,
leading: self.leading,
trailing: self.trailing,
tabs: self.tabs,
controls: self.controls,
inactive,
maximized,
tabbed,
recipe: theme
.resolve::<WindowChrome>(&case, Some(&self.rules))
.owned_by(self.id.as_ref()),
forced: self.forced,
window,
id: self.id,
key: self.key,
};
(view, self.content)
}
fn bar_in(view: WindowChromeView) -> Element {
let theme = view.theme().clone();
match theme.renderer::<WindowChrome>() {
Some(renderer) => renderer(view),
None => view.render(),
}
}
pub fn mount(mut self, ctx: &mut Ctx) -> Element {
let theme = ctx.theme().clone();
let window = ctx.window();
if let Some(title) = &self.title
&& window.title().as_deref() != Some(&**title)
{
window.set_title(title.to_string());
}
let content = self.content.take().unwrap_or_default();
let overlays = std::mem::take(&mut self.overlays);
let (mode, handles, border) = (self.mode, self.resize_handles, self.border.clone());
let height = self.bar_height(&theme);
let chrome = Arc::new(std::sync::Mutex::new(Some(self)));
let title_bar = ChromeTitleBar::new()
.height(height)
.background(BackgroundColor::Color(Color::new(0, 0, 0, 0)))
.border_bottom(None)
.draw(move |window, _height| {
let Some(chrome) = chrome.lock().expect("the chrome is held").take() else {
return Element::new();
};
let (view, _) = chrome.view(&theme, Some(window.clone()));
Self::bar_in(view)
});
components::WindowChrome::new()
.mode(mode)
.resize_handles(handles)
.border(border)
.title_bar(title_bar)
.content(content)
.overlays(overlays)
.mount(ctx)
}
pub fn build(self, theme: &Theme) -> Element {
let (view, content) = self.view(theme, None);
let root = view.part(WindowChromePart::Root);
let bar = Self::bar_in(view);
let mut window = Column::new().align_items(Alignment::Stretch).part(&root).child(bar);
if let Some(content) = content {
window = window.child(content);
}
window.into()
}
}
impl From<WindowChrome> for Element {
fn from(chrome: WindowChrome) -> Self {
chrome.build(¤t_theme())
}
}
impl WindowChrome {
fn bar_height(&self, theme: &Theme) -> f32 {
let platform = self.platform.unwrap_or_else(WindowPlatform::current);
let tabs = self.tabs.is_some();
let case = Case {
variant: Some(platform.into()),
size: None,
density: None,
breakpoint: super::current_breakpoint(),
states: self.states.clone(),
}
.state(WindowChromeState::Tabs, tabs);
let bar = theme
.resolve::<WindowChrome>(&case, Some(&self.rules))
.part(WindowChromePart::Bar)
.rest();
px(bar.height, theme).unwrap_or_else(|| board_bar_height(platform, tabs))
}
}
fn board_bar_height(platform: WindowPlatform, tabs: bool) -> f32 {
match (platform, tabs) {
(WindowPlatform::Windows | WindowPlatform::Macos, false) => 36.0,
(WindowPlatform::Windows | WindowPlatform::Macos, true) => 40.0,
(WindowPlatform::Gnome, _) => 44.0,
(WindowPlatform::Kde, false) => 32.0,
(WindowPlatform::Kde, true) => 38.0,
}
}
#[derive(Clone, Default)]
pub enum WindowChromeIcon {
#[default]
Window,
Glyph(Name),
#[cfg(feature = "raster")]
Image(crate::images::ImageData),
None,
}
impl std::fmt::Debug for WindowChromeIcon {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::Window => f.write_str("Window"),
Self::Glyph(name) => f.debug_tuple("Glyph").field(name).finish(),
#[cfg(feature = "raster")]
Self::Image(image) => write!(f, "Image({}x{})", image.width(), image.height()),
Self::None => f.write_str("None"),
}
}
}
impl PartialEq for WindowChromeIcon {
fn eq(&self, other: &Self) -> bool {
match (self, other) {
(Self::Window, Self::Window) | (Self::None, Self::None) => true,
(Self::Glyph(a), Self::Glyph(b)) => a == b,
#[cfg(feature = "raster")]
(Self::Image(a), Self::Image(b)) => a.id() == b.id(),
_ => false,
}
}
}
impl WindowChromeIcon {
fn shown(self, window: Option<&crate::app::window::Window>) -> Option<Self> {
match self {
Self::Window => {
#[cfg(feature = "raster")]
if let Some(image) = window.and_then(|window| {
window.track_access();
window.icon_image()
}) {
return Some(Self::Image(image));
}
#[cfg(not(feature = "raster"))]
let _ = window;
Some(Self::Glyph(Name::from(icons::BOX)))
}
Self::None => None,
icon => Some(icon),
}
}
}
impl From<&str> for WindowChromeIcon {
fn from(name: &str) -> Self {
Self::Glyph(Name::from(name))
}
}
impl From<Name> for WindowChromeIcon {
fn from(name: Name) -> Self {
Self::Glyph(name)
}
}
impl From<Option<Name>> for WindowChromeIcon {
fn from(name: Option<Name>) -> Self {
name.map_or(Self::None, Self::Glyph)
}
}
impl From<IconChoice> for WindowChromeIcon {
fn from(choice: IconChoice) -> Self {
choice.0.into()
}
}
#[cfg(feature = "raster")]
impl From<crate::images::ImageData> for WindowChromeIcon {
fn from(image: crate::images::ImageData) -> Self {
Self::Image(image)
}
}
pub struct WindowChromeView {
pub platform: WindowPlatform,
pub icon: Option<WindowChromeIcon>,
pub title: Option<Arc<str>>,
pub label: Option<Arc<str>>,
pub inactive: bool,
pub maximized: bool,
pub tabbed: bool,
pub recipe: ResolvedRecipe,
leading: Option<Element>,
trailing: Option<Element>,
tabs: Option<Element>,
controls: WindowControls,
forced: Option<Interaction>,
window: Option<WindowHandle>,
id: Option<Arc<str>>,
key: Option<Arc<str>>,
}
impl WindowChromeView {
pub fn part(&self, part: impl Into<Name>) -> ResolvedPart {
self.recipe.part(part)
}
pub fn theme(&self) -> &Theme {
self.recipe.theme()
}
pub fn has_tabs(&self) -> bool {
self.tabbed
}
pub fn bar(&self) -> Row {
let part = self.part(WindowChromePart::Bar);
let mut bar = Row::new()
.width(Dimension::Pct(100.0))
.align_items(if self.has_tabs() {
Alignment::End
} else {
Alignment::Center
})
.part(&part)
.describe("a11y_role", "group");
if let Some(name) = self.label.as_ref().or(self.title.as_ref()) {
bar = bar.describe("a11y_name", name.clone());
}
if let Some(id) = &self.id {
bar = bar.id(id.clone());
}
if let Some(key) = &self.key {
bar = bar.key(key.clone());
}
bar
}
pub fn over_line(&self, bar: Row) -> Element {
if !self.has_tabs() {
return bar.into();
}
let mut line = Row::new()
.width(Dimension::Pct(100.0))
.part(&self.part(WindowChromePart::Line));
if let Some(id) = &self.id {
line = line.id(format!("{id}-line"));
}
let mut layers = Stack::new().width(Dimension::Pct(100.0)).child(
Column::new()
.absolute(0.0, 0.0, Dimension::Pct(100.0), Dimension::Pct(100.0))
.justify(Justify::End)
.child(line),
);
if let Some(fill) = self.part(WindowChromePart::Bar).rest().background.clone() {
layers = layers.background(fill);
}
layers.child(bar.background(Color::new(0, 0, 0, 0))).into()
}
#[allow(deprecated)]
pub fn icon(&self) -> Option<Element> {
let part = self.part(WindowChromePart::Icon).unnamed();
let drawn = match self.icon.clone()? {
WindowChromeIcon::Glyph(name) => glyph(&part, name, false),
#[cfg(feature = "raster")]
WindowChromeIcon::Image(image) => Row::new()
.part(&part)
.child(
components::Image::new(image)
.contain()
.width(Dimension::Pct(100.0))
.height(Dimension::Pct(100.0)),
)
.into(),
WindowChromeIcon::Window | WindowChromeIcon::None => return None,
};
let mut icon = Column::new()
.justify(Justify::Center)
.height(Dimension::Pct(100.0))
.child(drawn);
if let Some(id) = &self.id {
icon = icon.id(format!("{id}-icon"));
}
Some(icon.into())
}
pub fn title(&self) -> Option<Element> {
let title = self.title.as_ref()?;
let part = self.part(WindowChromePart::Title).unnamed();
let centred = self.platform != WindowPlatform::Windows;
let mut row = Row::new()
.flex_full(1.0, 1.0, Some(0.0))
.min_width(0.0)
.align_items(Alignment::Center)
.justify(if centred { Justify::Center } else { Justify::Start })
.child(one_line(&part, title));
if let Some(id) = &self.id {
row = row.id(format!("{id}-title"));
}
Some(row.into())
}
pub fn tab_lead(&mut self, with_icon: bool) -> Option<Element> {
let icon = if with_icon { self.icon() } else { None };
let title = self.title.clone().map(|title| {
let part = self.part(WindowChromePart::Title).unnamed();
let mut row = Row::new()
.flex_shrink(1.0)
.min_width(0.0)
.max_width(TAB_LEAD_TITLE_MAX)
.align_items(Alignment::Center)
.child(one_line(&part, &title));
if let Some(id) = &self.id {
row = row.id(format!("{id}-title"));
}
Element::from(row)
});
if icon.is_none() && title.is_none() {
return None;
}
let gap = self.part(WindowChromePart::Bar).rest().gap.unwrap_or_default();
Some(
Row::new()
.height(Dimension::Pct(100.0))
.align_items(Alignment::Center)
.spacing(gap)
.flex_shrink(1.0)
.min_width(0.0)
.padding_right(gap)
.with_children([icon, title].into_iter().flatten())
.into(),
)
}
pub fn balance(&self) -> Element {
Row::new().part(&self.part(WindowChromePart::Balance)).into()
}
fn own(element: Element) -> Element {
Row::new()
.align_items(Alignment::Center)
.on_mouse_down(|event: MouseEvent| event.stop_propagation())
.child(element)
.into()
}
pub fn leading(&mut self) -> Option<Element> {
self.leading.take().map(Self::own)
}
pub fn trailing(&mut self) -> Option<Element> {
self.trailing.take().map(Self::own)
}
pub fn tabs(&mut self) -> Option<Element> {
let tabs = self.tabs.take()?;
Some(
Column::new()
.height(Dimension::Pct(100.0))
.justify(Justify::End)
.flex_full(0.0, 1.0, None)
.min_width(0.0)
.child(tabs)
.into(),
)
}
pub fn drag_room(&self) -> Element {
Row::new().flex(1.0).into()
}
pub fn control(&self, kind: WindowControl) -> Element {
let (part, glyph_part, name, label) = match kind {
WindowControl::Minimize => (
WindowChromePart::Minimize,
WindowChromePart::MinimizeGlyph,
self.minimize_icon(),
self.controls.minimize_label.clone(),
),
WindowControl::Maximize => (
WindowChromePart::Maximize,
WindowChromePart::MaximizeGlyph,
self.maximize_icon(),
if self.maximized {
self.controls.restore_label.clone()
} else {
self.controls.maximize_label.clone()
},
),
WindowControl::Close => (
WindowChromePart::Close,
WindowChromePart::CloseGlyph,
icons::CLOSE,
self.controls.close_label.clone(),
),
};
let forced = self
.forced
.filter(|_| kind == WindowControl::Close || self.platform == WindowPlatform::Macos);
let mut button = components::Button::empty()
.justify(Justify::Center)
.align_items(Alignment::Center)
.part(&self.part(part).forced(forced))
.interaction_group(self.platform != WindowPlatform::Macos)
.describe("a11y_role", "button")
.describe("a11y_name", label)
.on_mouse_down(|event: MouseEvent| event.stop_propagation())
.child(glyph(&self.part(glyph_part).forced(forced), Name::new(name), false));
if let Some(id) = &self.id {
let which = match kind {
WindowControl::Minimize => "minimize",
WindowControl::Maximize => "maximize",
WindowControl::Close => "close",
};
button = button.id(format!("{id}-{which}"));
}
if let Some(window) = self.window.clone() {
let (maximized, on_close) = (self.maximized, self.controls.on_close.clone());
button = button.window_control(kind).on_click(move |event: MouseEvent| {
match kind {
WindowControl::Minimize => window.set_minimized(true),
WindowControl::Maximize if window.is_full_screen => window.set_full_screen(false),
WindowControl::Maximize => window.set_maximized(!maximized),
WindowControl::Close => {
for handler in &on_close {
handler();
}
window.request_close();
}
}
event.stop_propagation();
});
} else if kind == WindowControl::Close {
let on_close = self.controls.on_close.clone();
button = button.on_click(move |_| {
for handler in &on_close {
handler();
}
});
}
if self.window.as_ref().is_some_and(|window| window.native_controls) {
button = button.opacity(0.0);
}
button.into()
}
fn minimize_icon(&self) -> &'static str {
match self.platform {
WindowPlatform::Kde => icons::CHEVRON_DOWN,
_ => icons::MINUS,
}
}
fn maximize_icon(&self) -> &'static str {
match (self.platform, self.maximized) {
(WindowPlatform::Kde, _) => icons::CHEVRON_UP,
(WindowPlatform::Macos, _) => icons::PLUS,
(_, true) => icons::COPY,
(_, false) => icons::SQUARE,
}
}
pub fn controls(&self) -> Element {
if self.platform == WindowPlatform::Macos && self.window.as_ref().is_some_and(|window| window.is_full_screen) {
return Row::new().into();
}
let order: &[WindowControl] = if self.platform.controls_at_start() {
&[WindowControl::Close, WindowControl::Minimize, WindowControl::Maximize]
} else {
&[WindowControl::Minimize, WindowControl::Maximize, WindowControl::Close]
};
let mut row = Row::new()
.align_items(Alignment::Center)
.part(&self.part(WindowChromePart::Controls))
.interaction_group(self.platform == WindowPlatform::Macos);
for kind in order {
let shown = match kind {
WindowControl::Minimize => self.controls.minimizable,
WindowControl::Maximize => self.controls.maximizable,
WindowControl::Close => true,
};
if shown {
row = row.child(self.control(*kind));
}
}
let align = match (self.platform, self.has_tabs()) {
(WindowPlatform::Windows, true) => Justify::Start,
_ => Justify::Center,
};
Column::new()
.height(Dimension::Pct(100.0))
.justify(align)
.child(row)
.into()
}
pub fn windows(mut self) -> Element {
let mut bar = self.bar();
if self.has_tabs() {
bar = bar.with_children(
[
self.tab_lead(true),
self.leading(),
self.tabs(),
Some(self.drag_room()),
self.trailing(),
]
.into_iter()
.flatten(),
);
} else {
let gap = self.part(WindowChromePart::Bar).rest().gap.unwrap_or_default();
let start = Row::new()
.align_items(Alignment::Center)
.spacing(gap)
.flex_full(1.0, 1.0, Some(0.0))
.min_width(0.0)
.with_children([self.icon(), self.leading(), self.title()].into_iter().flatten());
bar = bar.child(start).with_children(self.trailing());
}
self.over_line(bar.child(self.controls()))
}
pub fn macos(mut self) -> Element {
let mut bar = self.bar().child(self.controls());
if self.has_tabs() {
bar = bar.with_children(
[
self.tab_lead(false),
self.leading(),
self.tabs(),
Some(self.drag_room()),
self.trailing(),
]
.into_iter()
.flatten(),
);
} else {
bar = bar
.with_children(self.leading())
.with_children(self.title().or_else(|| Some(self.drag_room())))
.with_children(self.trailing())
.child(self.balance());
}
self.over_line(bar)
}
pub fn gnome(mut self) -> Element {
let mut bar = self.bar();
if self.has_tabs() {
bar = bar.with_children(
[
self.tab_lead(false),
self.leading(),
self.tabs(),
Some(self.drag_room()),
self.trailing(),
]
.into_iter()
.flatten(),
);
} else {
bar = bar
.child(self.balance())
.with_children(self.leading())
.with_children(self.title().or_else(|| Some(self.drag_room())))
.with_children(self.trailing());
}
self.over_line(bar.child(self.controls()))
}
pub fn kde(mut self) -> Element {
let mut bar = self.bar();
if self.has_tabs() {
bar = bar.with_children(
[
self.tab_lead(true),
self.leading(),
self.tabs(),
Some(self.drag_room()),
self.trailing(),
]
.into_iter()
.flatten(),
);
} else {
let icon = self.icon();
let start = Row::new()
.align_items(Alignment::Center)
.part(&self.part(WindowChromePart::Balance))
.with_children(icon);
bar = bar
.child(start)
.with_children(self.leading())
.with_children(self.title().or_else(|| Some(self.drag_room())))
.with_children(self.trailing());
}
self.over_line(bar.child(self.controls()))
}
pub fn render(self) -> Element {
match self.platform {
WindowPlatform::Windows => self.windows(),
WindowPlatform::Macos => self.macos(),
WindowPlatform::Gnome => self.gnome(),
WindowPlatform::Kde => self.kde(),
}
}
}
impl crate::ui::Styled for WindowChrome {
type Component = Self;
fn rules(self, rules: &crate::ui::Recipe) -> Self {
Self::rules(self, rules)
}
fn state(self, state: impl Into<crate::ui::Name>, on: bool) -> Self {
Self::state(self, state, on)
}
}
const TAB_LEAD_TITLE_MAX: f32 = 220.0;
impl Themed for WindowChrome {
const NAME: &'static str = "window_chrome";
type Renderer = WindowChromeRenderer;
fn parts() -> crate::ui::Declared {
WindowChromePart::declared()
}
fn states() -> crate::ui::Declared {
WindowChromeState::declared()
}
fn recipe() -> Recipe {
use PaletteColor::{
Background, Destructive, DestructiveForeground, DestructiveHover, Foreground, Input, MutedForeground,
SecondaryHover, StateHover, StatePressed,
};
use WindowChromePart::{
Balance, Bar, Close, CloseGlyph, Controls, Icon, Line, Maximize, MaximizeGlyph, Minimize, MinimizeGlyph, Root,
Title,
};
use WindowPlatform::{Gnome, Kde, Macos, Windows};
let on = |platform: WindowPlatform| Selector::new().variant(platform);
let control = [Minimize, Maximize, Close];
let glyphs = [MinimizeGlyph, MaximizeGlyph, CloseGlyph];
let mut recipe = Recipe::new()
.base(Root, |s| {
s.background(Background)
.border(Border::inside(BorderSize::Sm, PaletteColor::Border))
.radius(RadiusSize::Lg)
})
.base(Bar, |s| {
s.background(PaletteColor::Bar)
.underline(Border::inside(BorderSize::Sm, PaletteColor::Border))
.gap(8.0)
})
.base(Icon, |s| s.square(16.0).foreground(Foreground))
.base(Title, |s| {
s.font_size(13.0).weight(FontWeight::Medium).foreground(Foreground)
})
.base(MinimizeGlyph, |s| s.foreground(Foreground))
.base(MaximizeGlyph, |s| s.foreground(Foreground))
.base(CloseGlyph, |s| s.foreground(Foreground))
.state(WindowChromeState::Inactive, Title, |s| s.foreground(MutedForeground))
.state(WindowChromeState::Inactive, Icon, |s| s.foreground(MutedForeground))
.state(WindowChromeState::Inactive, MinimizeGlyph, |s| {
s.foreground(MutedForeground)
})
.state(WindowChromeState::Inactive, MaximizeGlyph, |s| {
s.foreground(MutedForeground)
})
.state(WindowChromeState::Inactive, CloseGlyph, |s| {
s.foreground(MutedForeground)
})
.state(WindowChromeState::Tabs, Bar, |s| {
s.underline(Border::inside(0.0, PaletteColor::Border))
})
.base(Line, |s| s.height(1.0).background(PaletteColor::Border))
.when(on(Windows), Bar, |s| s.height(36.0).padding_start(12.0))
.when(on(Windows).state(WindowChromeState::Tabs), Bar, |s| {
s.height(40.0).padding_start(8.0)
})
.when(on(Windows), Root, |s| s.radius(RadiusSize::Lg))
.when(on(Windows), MinimizeGlyph, |s| s.square(16.0))
.when(on(Windows), MaximizeGlyph, |s| s.square(12.0))
.when(on(Windows).state(WindowChromeState::Maximized), MaximizeGlyph, |s| {
s.square(13.0)
})
.when(on(Windows), CloseGlyph, |s| s.square(16.0))
.when(on(Macos), Bar, |s| s.height(36.0).padding_x(12.0))
.when(on(Macos).state(WindowChromeState::Tabs), Bar, |s| {
s.height(40.0).padding_start(12.0).padding_end(8.0).gap(14.0)
})
.when(on(Macos), Root, |s| s.radius(RadiusSize::Xl))
.when(on(Macos), Title, |s| s.weight(FontWeight::SemiBold))
.when(on(Macos), Balance, |s| s.width(52.0))
.when(on(Macos), Controls, |s| s.gap(8.0))
.when(on(Gnome), Bar, |s| s.height(44.0).padding_x(10.0))
.when(on(Gnome).state(WindowChromeState::Tabs), Bar, |s| {
s.padding_start(8.0).padding_end(10.0)
})
.when(on(Gnome), Root, |s| s.radius(RadiusSize::Xl))
.when(on(Gnome), Title, |s| s.weight(FontWeight::SemiBold))
.when(on(Gnome), Balance, |s| s.width(88.0))
.when(on(Gnome), Controls, |s| s.gap(8.0))
.when(on(Gnome), MinimizeGlyph, |s| s.square(14.0))
.when(on(Gnome), MaximizeGlyph, |s| s.square(10.0))
.when(on(Gnome), CloseGlyph, |s| s.square(14.0))
.when(on(Kde), Bar, |s| s.height(32.0).padding_start(8.0).padding_end(6.0))
.when(on(Kde).state(WindowChromeState::Tabs), Bar, |s| s.height(38.0))
.when(on(Kde), Root, |s| s.radius(RadiusSize::Md))
.when(on(Kde), Title, |s| s.weight(FontWeight::Normal))
.when(on(Kde), Balance, |s| s.width(78.0))
.when(on(Kde), Controls, |s| s.gap(6.0))
.when(on(Kde), MinimizeGlyph, |s| s.square(16.0))
.when(on(Kde), MaximizeGlyph, |s| s.square(16.0))
.when(on(Kde), CloseGlyph, |s| s.square(14.0));
for part in control {
recipe = recipe
.when(on(Windows), part, |s| fading(s.width(46.0).height(36.0)))
.when(on(Windows).hovered(), part, |s| s.background(SecondaryHover))
.when(on(Windows).pressed(), part, |s| s.background(SecondaryHover))
.when(on(Macos), part, |s| {
s.square(12.0)
.radius(RadiusSize::Full)
.border(Border::inside(0.5, Color::from_hex("#0000001F")))
})
.when(on(Macos).state(WindowChromeState::Inactive), part, |s| {
s.background(Input)
})
.when(on(Gnome), part, |s| {
fading(s.square(24.0).radius(RadiusSize::Full).background(SecondaryHover))
})
.when(on(Gnome).hovered(), part, |s| s.veil(StateHover))
.when(on(Gnome).pressed(), part, |s| s.veil(StatePressed))
.when(on(Kde), part, |s| fading(s.square(22.0).radius(RadiusSize::Full)))
.when(on(Kde).hovered(), part, |s| s.background(SecondaryHover))
.when(on(Kde).pressed(), part, |s| {
s.background(SecondaryHover).veil(StatePressed)
});
}
for part in glyphs {
recipe = recipe
.when(on(Macos), part, |s| {
s.square(8.0).foreground(Color::from_hex("#00000099")).opacity(0.0)
})
.when(on(Macos).within().hovered(), part, |s| {
s.opacity(1.0).foreground(Color::from_hex("#00000099"))
})
.when(on(Macos).within().pressed(), part, |s| {
s.opacity(1.0).foreground(Color::from_hex("#00000099"))
});
}
recipe
.when(on(Windows).hovered(), Close, |s| s.background(Destructive))
.when(on(Windows).pressed(), Close, |s| s.background(DestructiveHover))
.when(on(Gnome).hovered(), Close, |s| {
s.background(Destructive).veil(Color::new(0, 0, 0, 0))
})
.when(on(Gnome).pressed(), Close, |s| {
s.background(DestructiveHover).veil(Color::new(0, 0, 0, 0))
})
.when(on(Kde).hovered(), Close, |s| s.background(Destructive))
.when(on(Kde).pressed(), Close, |s| {
s.background(DestructiveHover).veil(Color::new(0, 0, 0, 0))
})
.when(Selector::new().within().hovered(), CloseGlyph, |s| {
s.foreground(DestructiveForeground)
})
.when(Selector::new().within().pressed(), CloseGlyph, |s| {
s.foreground(DestructiveForeground)
})
.when(on(Macos), Minimize, |s| s.background(Color::from_hex("#FEBC2E")))
.when(on(Macos), Maximize, |s| s.background(Color::from_hex("#28C840")))
.when(on(Macos), Close, |s| s.background(Color::from_hex("#FF5F57")))
.when(on(Macos).state(WindowChromeState::Inactive), Minimize, |s| {
s.background(Input)
})
.when(on(Macos).state(WindowChromeState::Inactive), Maximize, |s| {
s.background(Input)
})
.when(on(Macos).state(WindowChromeState::Inactive), Close, |s| {
s.background(Input)
})
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::{
app::{App, Tree, component::Component, events::MouseButton, window::WindowCommand},
components::Rect,
};
struct Host;
impl Component for Host {
type Props = ();
fn create(_ctx: &mut Ctx) -> Self {
Self
}
fn render(&self, ctx: &mut Ctx) -> impl Into<Element> {
WindowChrome::new()
.platform(WindowPlatform::Windows)
.title("Notes")
.mode(WindowChromeMode::AlwaysCustom)
.id("bar")
.leading(Rect::new(120.0, 24.0).id("menus"))
.content(Rect::new(800.0, 564.0))
.mount(ctx)
}
}
struct Tabbed;
impl Component for Tabbed {
type Props = ();
fn create(_ctx: &mut Ctx) -> Self {
Self
}
fn render(&self, ctx: &mut Ctx) -> impl Into<Element> {
let selected = ctx.signal(1_u32);
let tabs = super::super::WindowTabs::new(
selected,
[
super::super::WindowTab::new(1, "blur.rs").id("blur"),
super::super::WindowTab::new(2, "theme.rs").id("theme"),
],
)
.mount(ctx);
WindowChrome::new()
.platform(WindowPlatform::Windows)
.mode(WindowChromeMode::AlwaysCustom)
.id("bar")
.tabs(tabs)
.content(Rect::new(800.0, 560.0))
.mount(ctx)
}
}
#[test]
fn a_press_on_a_tab_is_the_tabs_and_the_room_they_leave_drags_the_window() {
let mut app = App::new();
let mut tree = Tree::new();
tree.resize(800, 600);
tree.mount_root::<Tabbed>(&mut app, ());
tree.pass_headless(&mut app);
tree.pass_headless(&mut app);
let _ = tree.window().take_commands();
let (x, y) = centre(&mut tree, "theme");
let tab = tree
.get_element_by_id_mut("theme")
.and_then(|element| element.bounds())
.unwrap();
assert_eq!(tab.y + tab.height, 40.0);
let commands = press(&mut tree, &mut app, x, y, MouseButton::Left);
assert!(!commands.contains(&WindowCommand::StartDrag), "{commands:?}");
let commands = press(&mut tree, &mut app, 600.0, 20.0, MouseButton::Left);
assert!(commands.contains(&WindowCommand::StartDrag), "{commands:?}");
}
struct Iconed;
impl Component for Iconed {
type Props = u8;
fn create(_ctx: &mut Ctx) -> Self {
Self
}
fn render(&self, ctx: &mut Ctx) -> impl Into<Element> {
let chrome = WindowChrome::new()
.platform(WindowPlatform::Windows)
.mode(WindowChromeMode::AlwaysCustom)
.id("bar")
.title("Notes")
.content(Rect::new(800.0, 564.0));
let chrome = match *ctx.props::<u8>() {
0 => chrome,
1 => chrome.icon(icons::FILE_CODE),
_ => chrome.icon(None),
};
chrome.mount(ctx)
}
}
fn icon_tags(tree: &Tree) -> Option<Vec<String>> {
use crate::node::element::ElementRef as Seen;
fn find<'a>(element: Seen<'a>, id: &str) -> Option<Seen<'a>> {
if element.id() == Some(id) {
return Some(element);
}
element.children().into_iter().find_map(|child| find(child, id))
}
fn tags(element: Seen<'_>, into: &mut Vec<String>) {
into.push(element.tag_name().to_owned());
for child in element.children() {
tags(child, into);
}
}
let icon = find(tree.root()?, "bar-icon")?;
let mut into = Vec::new();
tags(icon, &mut into);
Some(into)
}
fn red_icon() -> crate::app::window::WindowIcon {
crate::app::window::WindowIcon::from_rgba([255, 0, 0, 255].repeat(16 * 16), 16, 16)
}
#[cfg(feature = "raster")]
#[test]
fn the_bar_shows_the_windows_icon_and_follows_it() {
let mut app = App::new();
let mut tree = Tree::new();
tree.resize(800, 600);
tree.mount_root::<Iconed>(&mut app, 0);
tree.pass_headless(&mut app);
let tags = icon_tags(&tree).expect("an icon");
assert!(!tags.iter().any(|tag| tag == "Image"), "{tags:?}");
tree.window().handle().set_icon(red_icon());
tree.pass_headless(&mut app);
let tags = icon_tags(&tree).expect("an icon");
assert!(tags.iter().any(|tag| tag == "Image"), "{tags:?}");
let icon = tree
.get_element_by_id_mut("bar-icon")
.and_then(|element| element.bounds())
.unwrap();
assert_eq!(icon.width, 16.0);
tree.window().handle().set_icon(None);
tree.pass_headless(&mut app);
let tags = icon_tags(&tree).expect("an icon");
assert!(!tags.iter().any(|tag| tag == "Image"), "{tags:?}");
}
#[test]
fn a_glyph_or_none_is_shown_in_place_of_the_windows_icon() {
for (shown, has_icon) in [(1, true), (2, false)] {
let mut app = App::new();
let mut tree = Tree::new();
tree.resize(800, 600);
tree.window().handle().set_icon(red_icon());
tree.mount_root::<Iconed>(&mut app, shown);
tree.pass_headless(&mut app);
let tags = icon_tags(&tree);
assert_eq!(tags.is_some(), has_icon, "{shown}: {tags:?}");
assert!(!tags.unwrap_or_default().iter().any(|tag| tag == "Image"));
}
}
#[cfg(feature = "raster")]
#[test]
fn the_icon_is_the_windows_image_a_glyph_or_none() {
let theme = Theme::new();
let tree = Tree::new();
let handle = || Some(tree.window().handle());
let shown = |chrome: WindowChrome, window| chrome.view(&theme, window).0.icon;
assert_eq!(
shown(WindowChrome::new(), handle()),
Some(WindowChromeIcon::Glyph(Name::from(icons::BOX)))
);
tree.window().handle().set_icon(red_icon());
let (Some(WindowChromeIcon::Image(first)), Some(WindowChromeIcon::Image(again))) = (
shown(WindowChrome::new(), handle()),
shown(WindowChrome::new(), handle()),
) else {
panic!("the window's image");
};
assert_eq!((first.width(), first.height(), first.id()), (16, 16, again.id()));
assert_eq!(
shown(WindowChrome::new().icon(icons::FILE_CODE), handle()),
Some(WindowChromeIcon::Glyph(Name::from(icons::FILE_CODE)))
);
assert_eq!(shown(WindowChrome::new().icon(None), handle()), None);
let logo = crate::images::ImageData::from_rgba(vec![0; 4 * 4], 2, 2);
assert_eq!(
shown(WindowChrome::new().icon(logo.clone()), handle()),
Some(WindowChromeIcon::Image(logo))
);
assert_eq!(
shown(WindowChrome::new(), None),
Some(WindowChromeIcon::Glyph(Name::from(icons::BOX)))
);
}
fn window() -> (Tree, App) {
let mut app = App::new();
let mut tree = Tree::new();
tree.resize(800, 600);
tree.mount_root::<Host>(&mut app, ());
tree.pass_headless(&mut app);
tree.pass_headless(&mut app);
let _ = tree.window().take_commands();
(tree, app)
}
fn press(tree: &mut Tree, app: &mut App, x: f32, y: f32, button: MouseButton) -> Vec<WindowCommand> {
tree.mouse_move(x, y);
tree.mouse_down(x, y, button);
tree.mouse_up(x, y, button);
tree.pass_headless(app);
tree.window().take_commands()
}
fn centre(tree: &mut Tree, id: &str) -> (f32, f32) {
let rect = tree
.get_element_by_id_mut(id)
.and_then(|element| element.bounds())
.expect(id);
(rect.x + rect.width / 2.0, rect.y + rect.height / 2.0)
}
#[test]
fn the_controls_act_on_the_window_and_do_not_drag_it() {
let (mut tree, mut app) = window();
let (x, y) = centre(&mut tree, "bar-minimize");
assert_eq!(
press(&mut tree, &mut app, x, y, MouseButton::Left),
[WindowCommand::SetMinimized(true)]
);
let (x, y) = centre(&mut tree, "bar-maximize");
assert_eq!(
press(&mut tree, &mut app, x, y, MouseButton::Left),
[WindowCommand::SetMaximized(true)]
);
let (x, y) = centre(&mut tree, "bar-close");
let commands = press(&mut tree, &mut app, x, y, MouseButton::Left);
assert!(
matches!(commands.as_slice(), [WindowCommand::RequestClose(_)]),
"the window is asked to close: {commands:?}"
);
}
#[test]
fn the_bar_drags_the_window_and_a_right_press_shows_the_systems_menu() {
let (mut tree, mut app) = window();
assert_eq!(
press(&mut tree, &mut app, 500.0, 18.0, MouseButton::Left),
[WindowCommand::StartDrag]
);
assert_eq!(
press(&mut tree, &mut app, 500.0, 18.0, MouseButton::Right),
[WindowCommand::ShowSystemMenu]
);
let (x, y) = centre(&mut tree, "menus");
let commands = press(&mut tree, &mut app, x, y, MouseButton::Left);
assert!(commands.is_empty(), "{commands:?}");
}
#[test]
fn the_window_knows_its_controls_where_nothing_covers_them() {
let (mut tree, _app) = window();
for (id, control) in [
("bar-minimize", WindowControl::Minimize),
("bar-maximize", WindowControl::Maximize),
("bar-close", WindowControl::Close),
] {
let (x, y) = centre(&mut tree, id);
assert_eq!(tree.window_control_at(x, y), Some(control), "{id}");
}
for id in ["bar-title", "menus"] {
let (x, y) = centre(&mut tree, id);
assert_eq!(tree.window_control_at(x, y), None, "{id}");
}
let (x, _) = centre(&mut tree, "bar-maximize");
assert_eq!(tree.window_control_at(x, 1.0), None);
assert_eq!(tree.window_control_at(x, 6.0), Some(WindowControl::Maximize));
}
#[test]
fn a_maximized_window_has_its_controls_up_to_its_edges() {
let (mut tree, mut app) = window();
tree.window().set_maximized(true);
tree.pass_headless(&mut app);
tree.pass_headless(&mut app);
let _ = tree.window().take_commands();
assert_eq!(tree.window_control_at(799.0, 0.0), Some(WindowControl::Close));
let (x, _) = centre(&mut tree, "bar-maximize");
assert_eq!(tree.window_control_at(x, 0.0), Some(WindowControl::Maximize));
let commands = press(&mut tree, &mut app, 799.0, 0.0, MouseButton::Left);
assert!(
matches!(commands.as_slice(), [WindowCommand::RequestClose(_)]),
"a press in the corner asks the window to close: {commands:?}"
);
}
#[test]
fn a_picture_of_a_window_has_no_controls_of_the_window() {
let mut app = App::new();
let mut tree = Tree::new();
tree.resize(800, 600);
tree.set_root(
WindowChrome::new()
.platform(WindowPlatform::Windows)
.title("Notes")
.id("picture"),
);
tree.pass_headless(&mut app);
for id in ["picture-minimize", "picture-maximize", "picture-close"] {
let (x, y) = centre(&mut tree, id);
assert_eq!(tree.window_control_at(x, y), None, "{id}");
}
}
#[test]
fn the_bar_is_drawn_as_the_window_is() {
let (mut tree, mut app) = window();
tree.window().set_maximized(true);
tree.window().set_focused(false);
tree.pass_headless(&mut app);
tree.pass_headless(&mut app);
let _ = tree.window().take_commands();
crate::node::with_tooling! {
let name = tree
.get_element_by_id_mut("bar-maximize")
.and_then(|element| element.description("a11y_name"));
assert_eq!(name.as_deref(), Some("Restore"));
}
let (x, y) = centre(&mut tree, "bar-maximize");
assert_eq!(
press(&mut tree, &mut app, x, y, MouseButton::Left),
[WindowCommand::SetMaximized(false)]
);
}
}