Unify theme sizing and spacing on Base UI metrics

- Read only mode, accent, accessibility, and native window material from the OS.
- Replace platform palettes, metrics, type ramps, borders, and elevations with unified tokens.
- Align controls, overlays, and data rows with Base UI sizing.
This commit is contained in:
2026-11-16 18:27:44 +07:00
parent 745a01d7af
commit b08516211c
32 changed files with 518 additions and 1761 deletions
+2 -7
View File
@@ -150,7 +150,6 @@ impl RenderOnce for Alert {
let metrics = theme.sizes.resolve(Size::Medium); let metrics = theme.sizes.resolve(Size::Medium);
let icon_size = metrics.icon_size; let icon_size = metrics.icon_size;
let dense_icon_size = metrics.dense_icon_size; let dense_icon_size = metrics.dense_icon_size;
let caption_size = metrics.caption_size;
let content = v_flex() let content = v_flex()
.flex_1() .flex_1()
@@ -171,7 +170,7 @@ impl RenderOnce for Alert {
}; };
alert.child( alert.child(
div() div()
.text_size(caption_size) .text_size(metrics.text_size)
.text_color(color) .text_color(color)
.child(message), .child(message),
) )
@@ -189,11 +188,7 @@ impl RenderOnce for Alert {
match self.presentation { match self.presentation {
AlertStyle::Overlay => { AlertStyle::Overlay => {
let surface = theme.colors.surface; let surface = theme.colors.surface;
let border = if theme.borders.overlays { let border = theme.colors.border;
theme.colors.border
} else {
surface
};
div() div()
.id(self.id.clone()) .id(self.id.clone())
+21 -23
View File
@@ -7,7 +7,7 @@ use gpui::{
StyleRefinement, Styled as _, Window, canvas, relative, transparent_black, StyleRefinement, Styled as _, Window, canvas, relative, transparent_black,
}; };
use gpui_native_icons::Icon; use gpui_native_icons::Icon;
use gpui_native_theme::{ActiveTheme as _, BORDER_WIDTH, Size}; use gpui_native_theme::{ActiveTheme as _, Size};
use gpui_native_utils::{focus_ring, record_anchor_bounds}; use gpui_native_utils::{focus_ring, record_anchor_bounds};
use std::rc::Rc; use std::rc::Rc;
@@ -207,10 +207,8 @@ impl RenderOnce for Button {
let theme = cx.theme(); let theme = cx.theme();
let colors = theme.colors; let colors = theme.colors;
let ramps = theme.ramps; let ramps = theme.ramps;
let borders = theme.borders;
let metrics = theme.sizes.resolve(self.size); let metrics = theme.sizes.resolve(self.size);
let show_border = borders.buttons && self.variant != ButtonVariant::Ghost;
let on_click = self.on_click; let on_click = self.on_click;
let a11y_label = self.a11y_label.or_else(|| self.label.clone()); let a11y_label = self.a11y_label.or_else(|| self.label.clone());
let is_icon_only = self.icon.is_some() && self.label.is_none() && self.children.is_empty(); let is_icon_only = self.icon.is_some() && self.label.is_none() && self.children.is_empty();
@@ -224,10 +222,10 @@ impl RenderOnce for Button {
ramps.primary.pressed, ramps.primary.pressed,
), ),
ButtonVariant::Secondary => ( ButtonVariant::Secondary => (
Some(colors.secondary), Some(colors.surface),
colors.secondary_foreground, colors.foreground,
ramps.secondary.hover, colors.muted,
ramps.secondary.pressed, colors.muted_hover,
), ),
ButtonVariant::Ghost => ( ButtonVariant::Ghost => (
None, None,
@@ -243,17 +241,23 @@ impl RenderOnce for Button {
), ),
}; };
let (border, hover_border, pressed_border) = if show_border { let (border, hover_border, pressed_border) = match self.variant {
(colors.border, colors.border, colors.border) ButtonVariant::Primary => (
} else { ramps.primary.base,
match background { ramps.primary.hover,
Some(fill) => (fill, hover, pressed), ramps.primary.pressed,
None => ( ),
ButtonVariant::Secondary => (colors.border, colors.border, colors.border),
ButtonVariant::Ghost => (
transparent_black(), transparent_black(),
transparent_black(), transparent_black(),
transparent_black(), transparent_black(),
), ),
} ButtonVariant::Destructive => (
ramps.destructive.base,
ramps.destructive.hover,
ramps.destructive.pressed,
),
}; };
h_flex() h_flex()
@@ -267,16 +271,10 @@ impl RenderOnce for Button {
ButtonSide::Left => button.justify_start(), ButtonSide::Left => button.justify_start(),
ButtonSide::Right => button.justify_end(), ButtonSide::Right => button.justify_end(),
}) })
.h(metrics.control_height + BORDER_WIDTH * 2.0) .h(metrics.control_height)
.when(is_icon_only, |button| { .when(is_icon_only, |button| button.w(metrics.control_height))
button.w(metrics.control_height + BORDER_WIDTH * 2.0)
})
.when(!is_icon_only && self.padded, |button| { .when(!is_icon_only && self.padded, |button| {
button button.px(metrics.padding_x)
.when(self.icon.is_some(), |button| {
button.px(metrics.dense_padding_x)
})
.when(self.icon.is_none(), |button| button.px(metrics.padding_x))
}) })
.line_height(relative(1.0)) .line_height(relative(1.0))
.rounded(theme.radius.control) .rounded(theme.radius.control)
+1 -1
View File
@@ -123,7 +123,7 @@ impl RenderOnce for Checkbox {
h_flex() h_flex()
.id(self.id) .id(self.id)
.gap_1p5() .gap_2()
.text_size(metrics.text_size) .text_size(metrics.text_size)
.refine_style(&self.style) .refine_style(&self.style)
.when_some(self.debug_selector, |checkbox, selector| { .when_some(self.debug_selector, |checkbox, selector| {
+4 -8
View File
@@ -17,7 +17,7 @@ use gpui::{
}; };
use gpui_native_icons::{IconRole, icon}; use gpui_native_icons::{IconRole, icon};
use gpui_native_theme::ActiveTheme as _; use gpui_native_theme::ActiveTheme as _;
use gpui_native_theme::{BORDER_WIDTH, POPUP_MAX_HEIGHT, Size}; use gpui_native_theme::{POPUP_MAX_HEIGHT, Size};
use gpui_native_utils::ResultLogErr as _; use gpui_native_utils::ResultLogErr as _;
use crate::common::{OVERLAY_LAYER, Sizable, StyledExt as _, h_flex, v_flex}; use crate::common::{OVERLAY_LAYER, Sizable, StyledExt as _, h_flex, v_flex};
@@ -479,16 +479,11 @@ where
let theme = cx.theme(); let theme = cx.theme();
let metrics = theme.sizes.resolve(self.size); let metrics = theme.sizes.resolve(self.size);
let panel_border = if theme.borders.overlays {
theme.colors.border
} else {
theme.colors.surface
};
( (
metrics, metrics,
theme.colors, theme.colors,
theme.radius, theme.radius,
panel_border, theme.colors.border,
theme.spacing.unit, theme.spacing.unit,
theme.elevations.popover.shadows(), theme.elevations.popover.shadows(),
) )
@@ -587,7 +582,7 @@ where
h_flex() h_flex()
.absolute() .absolute()
.right(metrics.dense_padding_x) .right(metrics.dense_padding_x)
.top((metrics.input_height + BORDER_WIDTH * 2.0 - icon_size) / 2.) .top((metrics.input_height - icon_size) / 2.)
.child(chevron), .child(chevron),
) )
.when(open, |wrapper| { .when(open, |wrapper| {
@@ -618,6 +613,7 @@ where
.gap_2() .gap_2()
.px_2() .px_2()
.py_1() .py_1()
.min_h(metrics.control_height)
.rounded(radius.sm) .rounded(radius.sm)
.when(highlighted, |row| row.bg(colors.muted)) .when(highlighted, |row| row.bg(colors.muted))
.when(!highlighted, |row| row.hover(|row| row.bg(colors.muted))) .when(!highlighted, |row| row.hover(|row| row.bg(colors.muted)))
+2 -5
View File
@@ -337,11 +337,7 @@ impl Render for CommandPaletteState {
theme.colors, theme.colors,
theme.radius, theme.radius,
theme.sizes.resolve(Size::default()), theme.sizes.resolve(Size::default()),
if theme.borders.overlays { theme.colors.border,
theme.colors.border
} else {
theme.colors.surface
},
theme.elevations.dialog.shadows(), theme.elevations.dialog.shadows(),
) )
}; };
@@ -370,6 +366,7 @@ impl Render for CommandPaletteState {
.gap_2() .gap_2()
.px_2() .px_2()
.py_1() .py_1()
.min_h(metrics.control_height)
.rounded(radius.sm) .rounded(radius.sm)
.when(highlighted, |row| row.bg(colors.muted)) .when(highlighted, |row| row.bg(colors.muted))
.when(!highlighted, |row| row.hover(|row| row.bg(colors.muted))) .when(!highlighted, |row| row.hover(|row| row.bg(colors.muted)))
+4 -8
View File
@@ -160,11 +160,7 @@ impl RenderOnce for Dialog {
let theme = cx.theme(); let theme = cx.theme();
( (
theme.colors.overlay, theme.colors.overlay,
if theme.borders.overlays { theme.colors.border,
theme.colors.border
} else {
theme.colors.surface
},
theme.colors.foreground, theme.colors.foreground,
theme.colors.surface, theme.colors.surface,
theme.radius.overlay, theme.radius.overlay,
@@ -207,11 +203,11 @@ impl RenderOnce for Dialog {
.role(role) .role(role)
.aria_label(label) .aria_label(label)
.when_some(self.min_width, |panel, width| panel.min_w(width)) .when_some(self.min_width, |panel, width| panel.min_w(width))
.when(self.min_width.is_none(), |panel| panel.min_w_80()) .when(self.min_width.is_none(), |panel| panel.min_w_96())
.max_w(relative(0.9)) .max_w(relative(0.9))
.when_some(height, |panel, height| panel.h(height)) .when_some(height, |panel, height| panel.h(height))
.p_4() .p_4()
.gap_3() .gap_4()
.bg(surface) .bg(surface)
.text_color(foreground) .text_color(foreground)
.rounded(radius) .rounded(radius)
@@ -278,7 +274,7 @@ impl RenderOnce for Dialog {
}) })
}) })
.when_some(actions, |panel, actions| { .when_some(actions, |panel, actions| {
panel.child(div().flex().justify_end().gap_2().children(actions)) panel.child(div().flex().justify_end().gap_3().children(actions))
}) })
.child( .child(
canvas(|_, _, _| {}, { canvas(|_, _, _| {}, {
+12 -16
View File
@@ -11,7 +11,7 @@ use gpui::{
div, relative, div, relative,
}; };
use gpui_native_icons::{Icon, IconRole, icon}; use gpui_native_icons::{Icon, IconRole, icon};
use gpui_native_theme::{ActiveTheme as _, BORDER_WIDTH, Size}; use gpui_native_theme::{ActiveTheme as _, Size};
use gpui_native_utils::{focus_handle, focus_ring}; use gpui_native_utils::{focus_handle, focus_ring};
use crate::button::ButtonVariant; use crate::button::ButtonVariant;
@@ -186,7 +186,6 @@ impl RenderOnce for DropdownMenu {
let radius = theme.radius.control; let radius = theme.radius.control;
let ring = colors.ring; let ring = colors.ring;
let show_border = theme.borders.buttons && self.variant != ButtonVariant::Ghost;
let (panel_chrome, enter_duration) = MenuChrome::read(cx); let (panel_chrome, enter_duration) = MenuChrome::read(cx);
let (background, foreground, hover, pressed) = match self.variant { let (background, foreground, hover, pressed) = match self.variant {
@@ -197,10 +196,10 @@ impl RenderOnce for DropdownMenu {
ramps.primary.pressed, ramps.primary.pressed,
), ),
ButtonVariant::Secondary => ( ButtonVariant::Secondary => (
Some(colors.secondary), Some(colors.surface),
colors.secondary_foreground, colors.foreground,
ramps.secondary.hover, colors.muted,
ramps.secondary.pressed, colors.muted_hover,
), ),
ButtonVariant::Ghost => ( ButtonVariant::Ghost => (
None, None,
@@ -216,10 +215,11 @@ impl RenderOnce for DropdownMenu {
), ),
}; };
let border = if show_border { let border = match self.variant {
colors.border ButtonVariant::Primary => ramps.primary.base,
} else { ButtonVariant::Secondary => colors.border,
background.unwrap_or_else(gpui::transparent_black) ButtonVariant::Ghost => gpui::transparent_black(),
ButtonVariant::Destructive => ramps.destructive.base,
}; };
let split = self.on_click.is_some(); let split = self.on_click.is_some();
@@ -269,11 +269,7 @@ impl RenderOnce for DropdownMenu {
.role(Role::Button) .role(Role::Button)
.when_some(a11y_label, |zone, label| zone.aria_label(label)) .when_some(a11y_label, |zone, label| zone.aria_label(label))
.aria_expanded(self.open) .aria_expanded(self.open)
.px(if split && self.icon.is_none() { .px(metrics.padding_x)
metrics.padding_x
} else {
metrics.dense_padding_x
})
.when(split, |zone| zone.rounded_l(radius)) .when(split, |zone| zone.rounded_l(radius))
.when(!split, |zone| { .when(!split, |zone| {
zone.rounded(radius) zone.rounded(radius)
@@ -375,7 +371,7 @@ impl RenderOnce for DropdownMenu {
); );
let trigger = h_flex() let trigger = h_flex()
.h(metrics.control_height + BORDER_WIDTH * 2.0) .h(metrics.control_height)
.rounded(radius) .rounded(radius)
.border_1() .border_1()
.border_color(border) .border_color(border)
+2 -2
View File
@@ -5,7 +5,7 @@ use gpui::{
AnyElement, App, ElementId, InteractiveElement as _, IntoElement, ParentElement, RenderOnce, AnyElement, App, ElementId, InteractiveElement as _, IntoElement, ParentElement, RenderOnce,
Role, SharedString, StatefulInteractiveElement as _, StyleRefinement, Styled, Window, div, Role, SharedString, StatefulInteractiveElement as _, StyleRefinement, Styled, Window, div,
}; };
use gpui_native_theme::ActiveTheme as _; use gpui_native_theme::{ActiveTheme as _, TextRole, Typeset as _};
use crate::common::{StyledExt, h_flex, v_flex}; use crate::common::{StyledExt, h_flex, v_flex};
@@ -99,7 +99,7 @@ impl RenderOnce for Field {
let id = id.clone(); let id = id.clone();
move || format!("{id}-label") move || format!("{id}-label")
}) })
.text_size(metrics.text_size) .typeset(TextRole::Headline, cx)
.child(self.label.clone()); .child(self.label.clone());
let control = h_flex() let control = h_flex()
+5 -15
View File
@@ -16,8 +16,7 @@ use gpui::{
}; };
use gpui_native_icons::IconRole; use gpui_native_icons::IconRole;
use gpui_native_theme::{ use gpui_native_theme::{
ActiveTheme as _, BORDER_WIDTH, CARET_WIDTH, ColorTokens, Size, UNDERLINE_WIDTH, ActiveTheme as _, CARET_WIDTH, ColorTokens, Size, UNDERLINE_WIDTH, WHEEL_LINE_HEIGHT,
WHEEL_LINE_HEIGHT,
}; };
use gpui_native_utils::focus_ring; use gpui_native_utils::focus_ring;
@@ -1991,7 +1990,7 @@ impl RenderOnce for Input {
let recording = focused && !self.disabled && !self.state.read(cx).is_read_only(); let recording = focused && !self.disabled && !self.state.read(cx).is_read_only();
let small = theme.sizes.resolve(Size::Small); let small = theme.sizes.resolve(Size::Small);
let docked_height = small.control_height + BORDER_WIDTH * 2.0; let docked_height = small.control_height;
let edge_inset = ((metrics.input_height - docked_height) / 2.0).max(Pixels::ZERO); let edge_inset = ((metrics.input_height - docked_height) / 2.0).max(Pixels::ZERO);
let vertical_inset = metrics.dense_padding_x * 0.5; let vertical_inset = metrics.dense_padding_x * 0.5;
@@ -2014,7 +2013,7 @@ impl RenderOnce for Input {
let field_height = line_height.map_or(metrics.input_height, |line_height| { let field_height = line_height.map_or(metrics.input_height, |line_height| {
line_height * self.rows as f32 + vertical_inset * 2.0 line_height * self.rows as f32 + vertical_inset * 2.0
}) + BORDER_WIDTH * 2.0; });
let fallback_label = self let fallback_label = self
.a11y_label .a11y_label
@@ -2154,22 +2153,13 @@ impl RenderOnce for Input {
.text_size(metrics.text_size) .text_size(metrics.text_size)
.text_color(colors.foreground) .text_color(colors.foreground)
.border_1() .border_1()
.border_color(if theme.borders.fields { .border_color(colors.border)
colors.border
} else {
colors.input
})
.refine_style(&self.style) .refine_style(&self.style)
.when(self.disabled, |input| input.opacity(0.5)) .when(self.disabled, |input| input.opacity(0.5))
.when(!self.disabled, |input| { .when(!self.disabled, |input| {
input.track_focus(&focus_handle).tab_stop(true) input.track_focus(&focus_handle).tab_stop(true)
}) })
.when(focused && !theme.borders.focus_ring, |input| { .when(focused, |input| input.shadow(focus_ring(colors.ring)))
input.border_color(colors.ring)
})
.when(focused && theme.borders.focus_ring, |input| {
input.shadow(focus_ring(colors.ring))
})
.when_some(self.prefix, |input, prefix| { .when_some(self.prefix, |input, prefix| {
input.child(edge_zone("input-prefix", prefix)) input.child(edge_zone("input-prefix", prefix))
}) })
+2 -13
View File
@@ -171,7 +171,6 @@ impl FluentBuilder for MenuItem {}
pub(crate) struct MenuChrome { pub(crate) struct MenuChrome {
surface: gpui::Hsla, surface: gpui::Hsla,
border: gpui::Hsla, border: gpui::Hsla,
panel_border: gpui::Hsla,
foreground: gpui::Hsla, foreground: gpui::Hsla,
muted_foreground: gpui::Hsla, muted_foreground: gpui::Hsla,
muted_hover: gpui::Hsla, muted_hover: gpui::Hsla,
@@ -214,11 +213,6 @@ impl MenuChrome {
Self { Self {
surface: theme.colors.surface, surface: theme.colors.surface,
border: theme.colors.border, border: theme.colors.border,
panel_border: if theme.borders.overlays {
theme.colors.border
} else {
theme.colors.surface
},
foreground: theme.colors.foreground, foreground: theme.colors.foreground,
muted_foreground: theme.colors.muted_foreground, muted_foreground: theme.colors.muted_foreground,
muted_hover: theme.colors.muted_hover, muted_hover: theme.colors.muted_hover,
@@ -697,12 +691,7 @@ fn menu_panel(
.text_color(params.chrome.foreground) .text_color(params.chrome.foreground)
.rounded(params.chrome.radius_overlay) .rounded(params.chrome.radius_overlay)
.border_1() .border_1()
// A flyout overlaps its parent, so it always wears a visible border. .border_color(params.chrome.border)
.border_color(if params.is_flyout {
params.chrome.border
} else {
params.chrome.panel_border
})
.shadow(params.chrome.shadow.clone()) .shadow(params.chrome.shadow.clone())
.overflow_hidden() .overflow_hidden()
.on_mouse_down_out({ .on_mouse_down_out({
@@ -963,7 +952,7 @@ fn row_shell(
.items_center() .items_center()
.gap_2() .gap_2()
.min_h(chrome.menu_item_height) .min_h(chrome.menu_item_height)
.px(chrome.spacing_unit * 2.0) .px(chrome.spacing_unit * 4.0)
.text_size(chrome.text_size) .text_size(chrome.text_size)
.line_height(relative(1.0)) .line_height(relative(1.0))
.rounded(chrome.radius_sm) .rounded(chrome.radius_sm)
+1 -5
View File
@@ -107,11 +107,7 @@ impl RenderOnce for Popover {
theme.radius, theme.radius,
theme.elevations.popover.shadows(), theme.elevations.popover.shadows(),
theme.motion.overlay, theme.motion.overlay,
if theme.borders.overlays { theme.colors.border,
theme.colors.border
} else {
theme.colors.surface
},
theme.spacing.unit, theme.spacing.unit,
) )
}; };
+1 -1
View File
@@ -189,7 +189,7 @@ where
h_flex() h_flex()
.id(radio.id) .id(radio.id)
.gap_1p5() .gap_2()
.role(Role::RadioButton) .role(Role::RadioButton)
.when_some(a11y_label, |row, label| row.aria_label(label)) .when_some(a11y_label, |row, label| row.aria_label(label))
.aria_toggled(Toggled::from(is_selected)) .aria_toggled(Toggled::from(is_selected))
+2 -2
View File
@@ -164,7 +164,7 @@ where
let track_height = metrics.strip_height; let track_height = metrics.strip_height;
let track_inset = metrics.plate_inset; let track_inset = metrics.plate_inset;
let horizontal_padding = metrics.dense_padding_x; let horizontal_padding = metrics.dense_padding_x;
let text_size = metrics.caption_size; let text_size = metrics.text_size;
let icon_size = metrics.icon_size; let icon_size = metrics.icon_size;
let selected_index = self let selected_index = self
@@ -218,7 +218,7 @@ where
h_flex() h_flex()
.id((ElementId::from("segment"), segment.label.clone())) .id((ElementId::from("segment"), segment.label.clone()))
.gap_1p5() .gap_2()
.justify_center() .justify_center()
.cursor_pointer() .cursor_pointer()
.h_full() .h_full()
+8 -21
View File
@@ -7,7 +7,7 @@ use gpui::{
Window, canvas, Window, canvas,
}; };
use gpui_native_icons::{Icon, IconRole, icon}; use gpui_native_icons::{Icon, IconRole, icon};
use gpui_native_theme::{ActiveTheme as _, BORDER_WIDTH, Size}; use gpui_native_theme::{ActiveTheme as _, Size};
use gpui_native_utils::{focus_handle, focus_ring}; use gpui_native_utils::{focus_handle, focus_ring};
use crate::common::{Sizable, StyledExt, h_flex}; use crate::common::{Sizable, StyledExt, h_flex};
@@ -182,8 +182,6 @@ where
let muted_foreground = theme.colors.muted_foreground; let muted_foreground = theme.colors.muted_foreground;
let radius = theme.radius.control; let radius = theme.radius.control;
let icon_size = metrics.dense_icon_size; let icon_size = metrics.dense_icon_size;
let fields_bordered = theme.borders.fields;
let focus_ring_on = theme.borders.focus_ring;
let label = self let label = self
.a11y_label .a11y_label
@@ -209,18 +207,8 @@ where
let is_open = *open.read(cx); let is_open = *open.read(cx);
let open_for_items = open.clone(); let open_for_items = open.clone();
let (rest_border, hover_border) = if fields_bordered { let rest_border = border;
( let hover_border = border;
if is_open && !focus_ring_on {
ring
} else {
border
},
border,
)
} else {
(input, muted)
};
let selected_index = self.selected.as_ref().and_then(|value| { let selected_index = self.selected.as_ref().and_then(|value| {
self.options self.options
@@ -266,10 +254,11 @@ where
}) })
.cursor_pointer() .cursor_pointer()
.justify_between() .justify_between()
.gap_2() .gap_3()
.w_full() .w_full()
.h(metrics.input_height + BORDER_WIDTH * 2.0) .h(metrics.input_height)
.px(metrics.dense_padding_x) .pl(metrics.dense_padding_x)
.pr(metrics.plate_inset * 2.0)
.rounded(radius) .rounded(radius)
.border_1() .border_1()
.border_color(rest_border) .border_color(rest_border)
@@ -280,9 +269,7 @@ where
} else { } else {
muted_foreground muted_foreground
}) })
.when(is_open && focus_ring_on, |trigger| { .when(is_open, |trigger| trigger.shadow(focus_ring(ring)))
trigger.shadow(focus_ring(ring))
})
.hover(|style| style.bg(muted).border_color(hover_border)) .hover(|style| style.bg(muted).border_color(hover_border))
.child(trigger_text.clone()) .child(trigger_text.clone())
.child( .child(
+2 -2
View File
@@ -133,9 +133,9 @@ impl RenderOnce for Slider {
let radius = theme.radius; let radius = theme.radius;
let metrics = theme.sizes.resolve(self.size); let metrics = theme.sizes.resolve(self.size);
let row_height = metrics.icon_size; let row_height = metrics.icon_size * 2.5;
let track_height = metrics.icon_size / 4.0; let track_height = metrics.icon_size / 4.0;
let knob = metrics.icon_size * 1.25; let knob = metrics.indicator_size;
let value = self.value.clamp(self.min, self.max); let value = self.value.clamp(self.min, self.max);
let fraction = if self.max > self.min { let fraction = if self.max > self.min {
+2 -2
View File
@@ -19,7 +19,7 @@ use gpui::{
StyleRefinement, Styled, Subscription, Task, WeakEntity, Window, div, relative, StyleRefinement, Styled, Subscription, Task, WeakEntity, Window, div, relative,
}; };
use gpui_native_icons::{IconRole, icon}; use gpui_native_icons::{IconRole, icon};
use gpui_native_theme::{ActiveTheme as _, BORDER_WIDTH, Size}; use gpui_native_theme::{ActiveTheme as _, Size};
use gpui_native_utils::focus_ring; use gpui_native_utils::focus_ring;
use crate::common::{Sizable, StyledExt as _, h_flex}; use crate::common::{Sizable, StyledExt as _, h_flex};
@@ -743,7 +743,7 @@ impl RenderOnce for SpeechButton {
.group(group.clone()) .group(group.clone())
.role(Role::Button) .role(Role::Button)
.justify_center() .justify_center()
.h(metrics.control_height + BORDER_WIDTH * 2.0) .h(metrics.control_height)
.px(metrics.dense_padding_x) .px(metrics.dense_padding_x)
.gap_0p5() .gap_0p5()
.rounded(theme.radius.control) .rounded(theme.radius.control)
+6 -2
View File
@@ -122,7 +122,7 @@ impl RenderOnce for Switch {
h_flex() h_flex()
.id(self.id) .id(self.id)
.gap_1p5() .gap_2()
.text_size(metrics.text_size) .text_size(metrics.text_size)
.refine_style(&self.style) .refine_style(&self.style)
.role(Role::Switch) .role(Role::Switch)
@@ -147,12 +147,16 @@ impl RenderOnce for Switch {
.w(track_width) .w(track_width)
.h(track_height) .h(track_height)
.rounded(theme.radius.full) .rounded(theme.radius.full)
.border_1()
.when(self.checked, |track| { .when(self.checked, |track| {
track track
.bg(ramps.primary.base) .bg(ramps.primary.base)
.border_color(ramps.primary.base)
.hover(|style| style.bg(ramps.primary.hover)) .hover(|style| style.bg(ramps.primary.hover))
}) })
.when(!self.checked, |track| track.bg(colors.border)) .when(!self.checked, |track| {
track.bg(colors.input).border_color(colors.border)
})
.child( .child(
div() div()
.absolute() .absolute()
+3 -7
View File
@@ -274,16 +274,12 @@ impl ToastEntry {
fn pill(&self, toasts: &Entity<Toasts>, cx: &App) -> gpui::Stateful<gpui::Div> { fn pill(&self, toasts: &Entity<Toasts>, cx: &App) -> gpui::Stateful<gpui::Div> {
let theme = cx.theme(); let theme = cx.theme();
let surface = theme.colors.surface; let surface = theme.colors.surface;
let border = if theme.borders.overlays { let border = theme.colors.border;
theme.colors.border
} else {
surface
};
let foreground = theme.colors.foreground; let foreground = theme.colors.foreground;
let radius = theme.radius.full; let radius = theme.radius.full;
let shadows = theme.elevations.popover.shadows(); let shadows = theme.elevations.popover.shadows();
let icon_size = theme.sizes.small.icon_size; let icon_size = theme.sizes.medium.icon_size;
let text_size = theme.sizes.small.text_size; let text_size = theme.sizes.medium.text_size;
let toast = &self.toast; let toast = &self.toast;
let toasts = toasts.clone(); let toasts = toasts.clone();
let id = self.id; let id = self.id;
+2 -6
View File
@@ -64,18 +64,14 @@ impl Render for Tooltip {
fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement { fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
// Copied out: the mutable reads below need `cx` free of this borrow. // Copied out: the mutable reads below need `cx` free of this borrow.
let theme = cx.theme(); let theme = cx.theme();
let text_size = theme.sizes.small.text_size; let text_size = theme.sizes.medium.text_size;
let spacing_unit = theme.spacing.unit; let spacing_unit = theme.spacing.unit;
let surface = theme.colors.surface; let surface = theme.colors.surface;
let surface_foreground = theme.colors.surface_foreground; let surface_foreground = theme.colors.surface_foreground;
let radius_sm = theme.radius.sm; let radius_sm = theme.radius.sm;
let shadows = theme.elevations.popover.shadows(); let shadows = theme.elevations.popover.shadows();
let border = if theme.borders.overlays { let border = theme.colors.border;
theme.colors.border
} else {
theme.colors.surface
};
let build_panel = || { let build_panel = || {
div() div()
+1
View File
@@ -224,6 +224,7 @@ impl ListItem {
.gap_2() .gap_2()
.px_2() .px_2()
.py_1() .py_1()
.min_h(theme.sizes.medium.control_height)
.rounded(theme.radius.sm) .rounded(theme.radius.sm)
.role(Role::ListItem) .role(Role::ListItem)
.aria_selected(selected) .aria_selected(selected)
+1
View File
@@ -463,6 +463,7 @@ impl SidebarEntry {
.gap_2() .gap_2()
.px_2() .px_2()
.py_1() .py_1()
.min_h(theme.sizes.medium.control_height)
.rounded(theme.radius.sm) .rounded(theme.radius.sm)
.role(Role::ListItem) .role(Role::ListItem)
.aria_selected(selected) .aria_selected(selected)
+1
View File
@@ -354,6 +354,7 @@ impl TreeItem {
.pl(indent) .pl(indent)
.pr_2() .pr_2()
.py_1() .py_1()
.min_h(theme.sizes.medium.control_height)
.rounded(theme.radius.sm) .rounded(theme.radius.sm)
.role(Role::TreeItem) .role(Role::TreeItem)
.aria_selected(selected) .aria_selected(selected)
+5 -5
View File
@@ -21,7 +21,7 @@ pub struct ColorTokens {
pub foreground: Hsla, pub foreground: Hsla,
pub surface: Hsla, pub surface: Hsla,
pub surface_foreground: Hsla, pub surface_foreground: Hsla,
/// The docked sidebar's backdrop, matching the platform's window chrome. /// The docked sidebar's backdrop.
pub sidebar: Hsla, pub sidebar: Hsla,
pub primary: Hsla, pub primary: Hsla,
pub primary_foreground: Hsla, pub primary_foreground: Hsla,
@@ -77,8 +77,8 @@ impl ColorTokens {
info: hex(0x0284c7), info: hex(0x0284c7),
info_foreground: hex(0xffffff), info_foreground: hex(0xffffff),
border: hex(0xe4e4e7), border: hex(0xe4e4e7),
input: hex(0xe4e4e7), input: hex(0xffffff),
ring: hex(0x93c5fd), ring: hex(0x2563eb),
selection: hex(0xdbeafe), selection: hex(0xdbeafe),
overlay: scrim(0.25), overlay: scrim(0.25),
// macOS light overlay thumbs are translucent black. // macOS light overlay thumbs are translucent black.
@@ -112,8 +112,8 @@ impl ColorTokens {
info: hex(0x38bdf8), info: hex(0x38bdf8),
info_foreground: hex(0x082f49), info_foreground: hex(0x082f49),
border: hex(0x27272a), border: hex(0x27272a),
input: hex(0x27272a), input: hex(0x09090b),
ring: hex(0x1d4ed8), ring: hex(0x3b82f6),
selection: hex(0x1e3a8a), selection: hex(0x1e3a8a),
overlay: scrim(0.45), overlay: scrim(0.45),
// macOS dark overlay thumbs are translucent light gray. // macOS dark overlay thumbs are translucent light gray.
+93 -181
View File
@@ -19,7 +19,7 @@ pub use colors::{ColorTokens, MaterialTokens};
pub use definition::ThemeDefinition; pub use definition::ThemeDefinition;
pub use ramps::{AccentShades, Oklch}; pub use ramps::{AccentShades, Oklch};
pub use resolve::{Ramps, ResolvedTheme}; pub use resolve::{Ramps, ResolvedTheme};
pub use system::{AccessibilityPreferences, PartialPalette, SourceKind, SystemTheme}; pub use system::{AccessibilityPreferences, SourceKind, SystemTheme};
pub use typography::{TextRole, TypeMetrics, Typeset, Typography}; pub use typography::{TextRole, TypeMetrics, Typeset, Typography};
use gpui::{ use gpui::{
@@ -159,21 +159,19 @@ pub struct Theme {
pub material: MaterialTokens, pub material: MaterialTokens,
pub ramps: Ramps, pub ramps: Ramps,
pub radius: Radius, pub radius: Radius,
/// Per-platform border and focus chrome.
pub borders: Borders,
pub spacing: Spacing, pub spacing: Spacing,
pub elevations: Elevations, pub elevations: Elevations,
/// Overlay transition timing; gpui's animation primitives do the rest. /// Overlay transition timing; gpui's animation primitives do the rest.
pub motion: Motion, pub motion: Motion,
/// Overlay scrollbar geometry. /// Overlay scrollbar geometry.
pub scrollbar: Scrollbar, pub scrollbar: Scrollbar,
/// The height the window's titlebar strips draw at, per the platform. /// The height the window's titlebar strips draw at.
pub titlebar_height: Pixels, pub titlebar_height: Pixels,
/// The platform's native root font size; rem-based sizing scales with it. /// The theme's root font size; rem-based sizing scales with it.
pub root_font_size: Pixels, pub root_font_size: Pixels,
/// The platform's monospace family, for code surfaces. /// The monospace family, for code surfaces.
pub mono_font: &'static str, pub mono_font: &'static str,
/// The platform's type ladder, resolved at the root font size. /// The type ladder, resolved at the root font size.
pub typography: Typography, pub typography: Typography,
pub sizes: SizeTable, pub sizes: SizeTable,
pub accessibility: AccessibilityPreferences, pub accessibility: AccessibilityPreferences,
@@ -196,7 +194,6 @@ impl Theme {
material: resolved.material, material: resolved.material,
ramps: resolved.ramps, ramps: resolved.ramps,
radius: resolved.radius, radius: resolved.radius,
borders: resolved.borders,
spacing: resolved.spacing, spacing: resolved.spacing,
elevations: resolved.elevations, elevations: resolved.elevations,
motion: resolved.motion, motion: resolved.motion,
@@ -264,54 +261,7 @@ impl Default for Radius {
} }
} }
/// Which surfaces keep a 1px border, per the platform's chrome: Windows and /// The spacing rhythm: paddings and gaps step by this unit.
/// KDE frame their controls, macOS and GNOME paint fills.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Borders {
/// Filled actions keep a border (Windows, KDE).
pub buttons: bool,
/// Text fields and selects keep a border.
pub fields: bool,
/// Floating layers keep a border.
pub overlays: bool,
/// Keyboard focus paints an accent ring around the control.
pub focus_ring: bool,
}
impl Borders {
pub(crate) fn for_platform(source: SourceKind, variant: ThemeVariant) -> Self {
let overlays = variant == ThemeVariant::Dark;
match source {
SourceKind::Windows | SourceKind::Kde => Self {
buttons: true,
fields: true,
overlays: true,
focus_ring: false,
},
SourceKind::Macos => Self {
buttons: false,
fields: true,
overlays,
focus_ring: true,
},
SourceKind::Omarchy | SourceKind::Gnome => Self {
buttons: false,
fields: false,
overlays,
focus_ring: true,
},
SourceKind::Fallback => Self {
buttons: true,
fields: true,
overlays: true,
focus_ring: false,
},
}
}
}
/// The spacing rhythm of the platform: paddings and gaps step by this unit.
#[derive(Clone, Copy, Debug, PartialEq)] #[derive(Clone, Copy, Debug, PartialEq)]
pub struct Spacing { pub struct Spacing {
pub unit: Pixels, pub unit: Pixels,
@@ -420,7 +370,7 @@ pub struct Elevations {
} }
impl Elevations { impl Elevations {
pub(crate) fn for_platform(source: SourceKind, variant: ThemeVariant) -> Self { pub(crate) fn for_variant(variant: ThemeVariant) -> Self {
if variant == ThemeVariant::Dark { if variant == ThemeVariant::Dark {
return Self { return Self {
popover: Elevation::none(), popover: Elevation::none(),
@@ -429,8 +379,7 @@ impl Elevations {
}; };
} }
match source { Self {
SourceKind::Macos => Self {
popover: Elevation::layered( popover: Elevation::layered(
Shadow::black(0., 4., 24., 0.12), Shadow::black(0., 4., 24., 0.12),
Shadow::black(0., 1., 1., 0.05), Shadow::black(0., 1., 1., 0.05),
@@ -440,30 +389,11 @@ impl Elevations {
Shadow::black(0., 1., 2., 0.06), Shadow::black(0., 1., 2., 0.06),
), ),
control: Elevation::single(Shadow::black(0., 1., 2., 0.1)), control: Elevation::single(Shadow::black(0., 1., 2., 0.1)),
},
SourceKind::Windows => Self {
popover: Elevation::layered(
Shadow::black(0., 8., 16., 0.14),
Shadow::black(0., 2., 4., 0.1),
),
dialog: Elevation::layered(
Shadow::black(0., 16., 32., 0.16),
Shadow::black(0., 4., 8., 0.1),
),
control: Elevation::single(Shadow::black(0., 1., 2., 0.12)),
},
SourceKind::Omarchy | SourceKind::Kde | SourceKind::Gnome | SourceKind::Fallback => {
Self {
popover: Elevation::single(Shadow::black(0., 3., 6., 0.2)),
dialog: Elevation::single(Shadow::black(0., 9., 18., 0.24)),
control: Elevation::single(Shadow::black(0., 1., 2., 0.16)),
}
}
} }
} }
} }
/// Overlay transition timings; the platform refines these per phase. /// Overlay transition timings.
#[derive(Clone, Copy, Debug, PartialEq)] #[derive(Clone, Copy, Debug, PartialEq)]
pub struct Motion { pub struct Motion {
/// The enter transition of popovers, menus, and dialogs. /// The enter transition of popovers, menus, and dialogs.
@@ -478,8 +408,7 @@ impl Default for Motion {
} }
} }
/// Overlay scrollbar presentation, transcribed from the platform's overlay /// Overlay scrollbar presentation.
/// crollbars.
#[derive(Clone, Copy, Debug, PartialEq)] #[derive(Clone, Copy, Debug, PartialEq)]
pub struct Scrollbar { pub struct Scrollbar {
/// The painted thumb's thickness. /// The painted thumb's thickness.
@@ -549,85 +478,105 @@ pub struct SizeTable {
impl SizeTable { impl SizeTable {
pub fn with_root_font_size(rem_size: Pixels) -> Self { pub fn with_root_font_size(rem_size: Pixels) -> Self {
struct ClassFactors { struct ClassFactors {
height: f32, control_height: f32,
padding: f32, input_height: f32,
text: f32, padding_x: f32,
icon: f32, text_size: f32,
avatar: f32, icon_size: f32,
strip: f32, dense_icon_size: f32,
inset: f32, indicator_size: f32,
floor_icon: bool, avatar_size: f32,
caption_size: f32,
dense_padding_x: f32,
plate_inset: f32,
strip_height: f32,
menu_item_height: f32,
switch_height: f32,
switch_width: f32,
switch_knob: f32,
} }
let small = ClassFactors { let small = ClassFactors {
height: 1.5, control_height: 1.75,
padding: 0.75, input_height: 1.75,
text: 0.85, padding_x: 0.5,
icon: 0.875, text_size: 0.75,
avatar: 1.125, icon_size: 0.875,
strip: 1.5, dense_icon_size: 0.75,
inset: 0.125, indicator_size: 0.875,
floor_icon: false, avatar_size: 1.5,
caption_size: 0.75,
dense_padding_x: 0.5,
plate_inset: 0.125,
strip_height: 1.75,
menu_item_height: 1.75,
switch_height: 1.125,
switch_width: 2.0,
switch_knob: 0.75,
}; };
let medium = ClassFactors { let medium = ClassFactors {
height: 1.75, control_height: 2.0,
padding: 1.0, input_height: 2.0,
text: 1.0, padding_x: 0.75,
icon: 1.0, text_size: 0.875,
avatar: 1.5, icon_size: 1.0,
strip: 2.0, dense_icon_size: 0.75,
inset: 0.25, indicator_size: 1.0,
floor_icon: true, avatar_size: 2.0,
caption_size: 0.75,
dense_padding_x: 0.5,
plate_inset: 0.125,
strip_height: 2.0,
menu_item_height: 2.0,
switch_height: 1.25,
switch_width: 2.25,
switch_knob: 0.875,
}; };
let large = ClassFactors { let large = ClassFactors {
height: 2.25, control_height: 2.5,
padding: 1.25, input_height: 2.5,
text: 1.15, padding_x: 1.0,
icon: 1.25, text_size: 1.0,
avatar: 2.0, icon_size: 1.25,
strip: 3.0, dense_icon_size: 0.9375,
inset: 0.375, indicator_size: 1.25,
floor_icon: true, avatar_size: 2.5,
caption_size: 0.875,
dense_padding_x: 0.75,
plate_inset: 0.1875,
strip_height: 2.5,
menu_item_height: 2.25,
switch_height: 1.5,
switch_width: 2.75,
switch_knob: 1.125,
}; };
let metrics = |f: &ClassFactors| { let metrics = |f: &ClassFactors| ControlMetrics {
let icon_size = if f.floor_icon { control_height: rem_size * f.control_height,
(rem_size * f.icon).max(px(16.)) input_height: rem_size * f.input_height,
} else { padding_x: rem_size * f.padding_x,
rem_size * f.icon text_size: rem_size * f.text_size,
}; icon_size: rem_size * f.icon_size,
let switch_height = rem_size * f.height * 0.75; dense_icon_size: rem_size * f.dense_icon_size,
ControlMetrics { indicator_size: rem_size * f.indicator_size,
control_height: rem_size * f.height, avatar_size: rem_size * f.avatar_size,
input_height: rem_size * (f.height + 0.125), caption_size: rem_size * f.caption_size,
padding_x: rem_size * f.padding, dense_padding_x: rem_size * f.dense_padding_x,
text_size: rem_size * f.text, plate_inset: rem_size * f.plate_inset,
icon_size, strip_height: rem_size * f.strip_height,
dense_icon_size: icon_size * 0.75, menu_item_height: rem_size * f.menu_item_height,
indicator_size: rem_size * f.height * 0.7, switch_height: rem_size * f.switch_height,
avatar_size: rem_size * f.avatar, switch_width: rem_size * f.switch_width,
caption_size: rem_size * f.text, switch_knob: rem_size * f.switch_knob,
dense_padding_x: rem_size * f.padding * 0.75,
plate_inset: rem_size * f.inset,
strip_height: rem_size * f.strip,
menu_item_height: rem_size * f.height * 0.85,
switch_height,
switch_width: switch_height * 2.25,
switch_knob: switch_height * 0.85,
}
}; };
let mut table = Self { Self {
small: metrics(&small), small: metrics(&small),
medium: metrics(&medium), medium: metrics(&medium),
large: metrics(&large), large: metrics(&large),
}; }
table.small.caption_size = table.small.text_size * 0.85;
table.large.caption_size = table.medium.text_size;
table
} }
/// The metrics for `size`. /// The metrics for `size`.
@@ -638,43 +587,6 @@ impl SizeTable {
Size::Large => self.large, Size::Large => self.large,
} }
} }
/// Sets the medium class's text-field height to the platform's stated value.
pub fn set_input_height(&mut self, medium_input_height: Pixels) {
let ratio = medium_input_height / self.medium.input_height;
self.small.input_height = (self.small.input_height * ratio).floor();
self.medium.input_height = medium_input_height;
self.large.input_height = (self.large.input_height * ratio).floor();
}
/// Sets the medium class's control height to the platform's stated value.
pub fn set_control_height(&mut self, medium_control_height: Pixels) {
let ratio = medium_control_height / self.medium.control_height;
self.small.control_height = (self.small.control_height * ratio).floor();
self.medium.control_height = medium_control_height;
self.large.control_height = (self.large.control_height * ratio).floor();
}
/// Sets the medium class's menu row height to the platform's stated value.
pub fn set_menu_item_height(&mut self, medium_menu_item_height: Pixels) {
let ratio = medium_menu_item_height / self.medium.menu_item_height;
self.small.menu_item_height *= ratio;
self.medium.menu_item_height = medium_menu_item_height;
self.large.menu_item_height *= ratio;
}
/// Sets the medium class's switch dimensions to the platform's stated values.
pub fn set_switch_metrics(&mut self, track_height: Pixels, track_width: Pixels, knob: Pixels) {
let ratio = track_height / self.medium.switch_height;
for metrics in [&mut self.small, &mut self.large] {
metrics.switch_height *= ratio;
metrics.switch_width *= ratio;
metrics.switch_knob *= ratio;
}
self.medium.switch_height = track_height;
self.medium.switch_width = track_width;
self.medium.switch_knob = knob;
}
} }
/// User customizations layered over the resolved theme. /// User customizations layered over the resolved theme.
File diff suppressed because it is too large Load Diff
+12 -120
View File
@@ -4,74 +4,40 @@
use std::collections::HashMap; use std::collections::HashMap;
use gpui::{Hsla, Pixels, px}; use gpui::Hsla;
use crate::system::{PartialPalette, SourceKind, SystemTheme}; use crate::system::{SourceKind, SystemTheme};
/// The colors stated in kdeglobals' `[Colors:*]` groups. /// The accent and window background stated in kdeglobals.
#[derive(Clone, Copy, Debug, Default, PartialEq)] #[derive(Clone, Copy, Debug, Default, PartialEq)]
pub(crate) struct KdeScheme { pub(crate) struct KdeScheme {
pub(crate) accent: Option<Hsla>, pub(crate) accent: Option<Hsla>,
pub(crate) background: Option<Hsla>, pub(crate) background: Option<Hsla>,
pub(crate) palette: PartialPalette,
/// The root font size parsed from `[General] font=` (family, pointSize,
/// pixelSize, ...).
pub(crate) root_font_size: Option<Pixels>,
} }
impl KdeScheme { impl KdeScheme {
/// Parses kdeglobals text. /// Parses kdeglobals text.
pub(crate) fn parse(text: &str) -> Self { pub(crate) fn parse(text: &str) -> Self {
let groups = parse_groups(text); let groups = parse_groups(text);
let window = groups.get("Colors:Window");
let view = groups.get("Colors:View");
let button = groups.get("Colors:Button");
let selection = groups.get("Colors:Selection");
let background = window.and_then(|group| group_color(group, "BackgroundNormal")); let background = groups
.get("Colors:Window")
.and_then(|group| group_color(group, "BackgroundNormal"));
let accent = groups let accent = groups
.get("General") .get("General")
.and_then(|group| group.get("AccentColor")) .and_then(|group| group.get("AccentColor"))
.and_then(|value| color_list(value)); .and_then(|value| color_list(value));
let palette = PartialPalette { Self { accent, background }
background,
foreground: window.and_then(|group| group_color(group, "ForegroundNormal")),
surface: view.and_then(|group| group_color(group, "BackgroundNormal")),
surface_foreground: view.and_then(|group| group_color(group, "ForegroundNormal")),
secondary: button.and_then(|group| group_color(group, "BackgroundNormal")),
secondary_foreground: button.and_then(|group| group_color(group, "ForegroundNormal")),
muted: window.and_then(|group| group_color(group, "DecorationHover")),
muted_foreground: window.and_then(|group| group_color(group, "ForegroundInactive")),
destructive: window.and_then(|group| group_color(group, "ForegroundNegative")),
success: window.and_then(|group| group_color(group, "ForegroundPositive")),
border: window.and_then(|group| group_color(group, "DecorationNormal")),
ring: window.and_then(|group| group_color(group, "DecorationFocus")),
selection: selection.and_then(|group| group_color(group, "BackgroundNormal")),
primary_foreground: selection.and_then(|group| group_color(group, "ForegroundNormal")),
..PartialPalette::default()
};
Self {
accent,
background,
palette,
root_font_size: root_font_size(groups.get("General")),
}
} }
pub(crate) fn into_system( pub(crate) fn into_system(
mut self, self,
accessibility: crate::system::AccessibilityPreferences, accessibility: crate::system::AccessibilityPreferences,
portal_accent: Option<Hsla>, portal_accent: Option<Hsla>,
portal_variant: Option<crate::ThemeVariant>, portal_variant: Option<crate::ThemeVariant>,
) -> SystemTheme { ) -> SystemTheme {
// Schemes that state no DecorationFocus fall back to the accent.
if self.palette.ring.is_none() {
self.palette.ring = self.accent;
}
SystemTheme { SystemTheme {
// The portal states the mode on Plasma 5.21+. // The portal states the mode on Plasma 5.21+.
// //
@@ -80,18 +46,6 @@ impl KdeScheme {
.or(self.background.map(crate::ThemeVariant::by_lightness)) .or(self.background.map(crate::ThemeVariant::by_lightness))
.unwrap_or(crate::ThemeVariant::Light), .unwrap_or(crate::ThemeVariant::Light),
accent: self.accent.or(portal_accent), accent: self.accent.or(portal_accent),
palette: self.palette,
control_radius: Some(px(5.)),
overlay_radius: Some(px(5.)),
sm_radius: None,
control_height: Some(px(33.)),
input_height: Some(px(29.)),
menu_item_height: Some(px(29.)),
switch_height: Some(px(18.)),
switch_width: Some(px(36.)),
switch_knob: Some(px(18.)),
titlebar_height: Some(px(44.)),
root_font_size: Some(self.root_font_size.unwrap_or(px(13.33))),
accessibility, accessibility,
window_background: None, window_background: None,
source: SourceKind::Kde, source: SourceKind::Kde,
@@ -99,22 +53,6 @@ impl KdeScheme {
} }
} }
/// The root font size of a `[General]` group's `font=` QFont string.
fn root_font_size(group: Option<&HashMap<&str, &str>>) -> Option<Pixels> {
let fields: Vec<&str> = group?.get("font")?.split(',').map(str::trim).collect();
let points = fields.get(1)?.parse::<f32>().ok()?;
let pixels = fields
.get(2)
.and_then(|size| size.parse::<f32>().ok())
.unwrap_or(-1.0);
let size = if pixels > 0.0 {
pixels
} else {
points * 96.0 / 72.0
};
(size > 0.0).then(|| px(size))
}
fn parse_groups(text: &str) -> HashMap<&str, HashMap<&str, &str>> { fn parse_groups(text: &str) -> HashMap<&str, HashMap<&str, &str>> {
let mut groups: HashMap<&str, HashMap<&str, &str>> = HashMap::new(); let mut groups: HashMap<&str, HashMap<&str, &str>> = HashMap::new();
let mut section: Option<&str> = None; let mut section: Option<&str> = None;
@@ -236,10 +174,10 @@ activeBackground=39,44,49
"; ";
#[test] #[test]
fn breeze_groups_map_onto_roles() { fn breeze_states_the_window_background() {
let scheme = KdeScheme::parse(BREEZE_DARK); let scheme = KdeScheme::parse(BREEZE_DARK);
let scale = |component: u32| component as f32 / 255.0; let scale = |component: u32| component as f32 / 255.0;
let background = scheme.palette.background.expect("window background"); let background = scheme.background.expect("window background");
assert_eq!( assert_eq!(
gpui::Rgba::from(background), gpui::Rgba::from(background),
@@ -250,41 +188,12 @@ activeBackground=39,44,49
a: 1.0, a: 1.0,
} }
); );
assert_eq!(
scheme.palette.selection,
Some(Hsla::from(gpui::Rgba {
r: scale(61),
g: scale(174),
b: scale(233),
a: 1.0,
}))
);
assert_eq!(
scheme.palette.muted_foreground,
Some(Hsla::from(gpui::Rgba {
r: scale(161),
g: scale(169),
b: scale(177),
a: 1.0,
}))
);
assert_eq!(
scheme.palette.destructive,
Some(Hsla::from(gpui::Rgba {
r: scale(218),
g: scale(68),
b: scale(83),
a: 1.0,
}))
);
} }
#[test] #[test]
fn localized_and_unrelated_keys_are_ignored() { fn localized_and_unrelated_keys_are_ignored() {
let scheme = KdeScheme::parse(BREEZE_DARK); let scheme = KdeScheme::parse(BREEZE_DARK);
assert!(scheme.accent.is_none()); assert!(scheme.accent.is_none());
assert_eq!(scheme.palette.foreground, scheme.palette.surface_foreground);
} }
#[test] #[test]
@@ -329,29 +238,12 @@ activeBackground=39,44,49
assert_eq!(system.variant, crate::ThemeVariant::Light); assert_eq!(system.variant, crate::ThemeVariant::Light);
} }
#[test]
fn the_default_font_applies_without_a_stated_font() {
let system = KdeScheme::parse(BREEZE_DARK).into_system(Default::default(), None, None);
assert!((system.root_font_size.expect("default font") - px(13.33)).abs() < px(0.01));
}
#[test] #[test]
fn color_components_outside_0_to_255_are_rejected() { fn color_components_outside_0_to_255_are_rejected() {
let above = KdeScheme::parse("[Colors:Window]\nBackgroundNormal=300,20,20\n"); let above = KdeScheme::parse("[Colors:Window]\nBackgroundNormal=300,20,20\n");
assert!(above.palette.background.is_none()); assert!(above.background.is_none());
let below = KdeScheme::parse("[Colors:Window]\nBackgroundNormal=-5,20,20\n"); let below = KdeScheme::parse("[Colors:Window]\nBackgroundNormal=-5,20,20\n");
assert!(below.palette.background.is_none()); assert!(below.background.is_none());
}
#[test]
fn the_stated_font_beats_the_default() {
let text = "[General]\nfont=Noto Sans,10,-1,5,50,0,0,0,0,0\n";
let system = KdeScheme::parse(text).into_system(Default::default(), None, None);
assert!((system.root_font_size.unwrap() - px(10.0 * 96.0 / 72.0)).abs() < px(0.01));
let text = "[General]\nfont=Adwaita Sans,-1,12,5,50,0,0,0,0,0\n";
let system = KdeScheme::parse(text).into_system(Default::default(), None, None);
assert_eq!(system.root_font_size, Some(px(12.)));
} }
} }
+10 -76
View File
@@ -1,11 +1,11 @@
//! Linux adapter selection: Omarchy → KDE → portal (GNOME/generic) → //! Linux adapter selection: Omarchy → KDE → portal (GNOME/generic) →
//! fallback, per the plan's detection cascade. Omarchy and KDE palettes come //! fallback, per the plan's detection cascade. Omarchy and KDE state the mode
//! from their files; the portal supplements mode, accent, and the //! and accent; the portal supplements both with the accessibility flags;
//! accessibility flags; `gsettings` covers sessions without a portal. //! `gsettings` covers sessions without a portal.
use std::path::{Path, PathBuf}; use std::path::{Path, PathBuf};
use gpui::{Hsla, Pixels}; use gpui::Hsla;
use notify::{RecursiveMode, Watcher}; use notify::{RecursiveMode, Watcher};
use super::ThemeSource; use super::ThemeSource;
@@ -16,26 +16,7 @@ use super::signal::ReapplySignal;
use crate::ThemeVariant; use crate::ThemeVariant;
use crate::system::{PartialPalette, SourceKind, SystemTheme}; use crate::system::{SourceKind, SystemTheme};
/// libadwaita's control corner radius, in px at 100% scaling.
const CONTROL_RADIUS_PX: f32 = 9.0;
/// libadwaita's popover corner radius.
const OVERLAY_RADIUS_PX: f32 = 15.0;
/// The checkbox indicator's corner radius.
const SM_RADIUS_PX: f32 = 6.0;
/// libadwaita's standard control and text-field height.
const CONTROL_HEIGHT_PX: f32 = 34.0;
/// The GTK menu row height.
const MENU_ITEM_HEIGHT_PX: f32 = 32.0;
/// The GTK switch: a 46x26 track with a 20px knob.
const SWITCH_HEIGHT_PX: f32 = 26.0;
const SWITCH_WIDTH_PX: f32 = 46.0;
const SWITCH_KNOB_PX: f32 = 20.0;
/// GNOME's headerbar height, in px at 100% scaling.
const TITLEBAR_HEIGHT_PX: f32 = 47.0;
/// The default 11pt interface font, in px.
const ROOT_FONT_SIZE_PX: f32 = 14.67;
pub(crate) struct LinuxSource { pub(crate) struct LinuxSource {
backend: Backend, backend: Backend,
@@ -87,7 +68,6 @@ fn detect(home: &Path, portal_reachable: bool, gsettings_reachable: bool) -> Bac
struct GSettingsSnapshot { struct GSettingsSnapshot {
variant: Option<ThemeVariant>, variant: Option<ThemeVariant>,
accent: Option<Hsla>, accent: Option<Hsla>,
root_font_size: Option<Pixels>,
} }
fn gsettings_value(args: &[&str]) -> Option<String> { fn gsettings_value(args: &[&str]) -> Option<String> {
@@ -129,22 +109,10 @@ fn read_gsettings() -> Option<GSettingsSnapshot> {
let accent = gsettings_value(&["get", "org.gnome.desktop.interface", "accent-color"]) let accent = gsettings_value(&["get", "org.gnome.desktop.interface", "accent-color"])
.and_then(|value| accent_rgb(value.trim().trim_matches('\''))); .and_then(|value| accent_rgb(value.trim().trim_matches('\'')));
let root_font_size = gsettings_value(&["get", "org.gnome.desktop.interface", "font-name"]) if variant.is_none() && accent.is_none() {
.and_then(|value| font_root_px(value.trim().trim_matches('\'')));
if variant.is_none() && accent.is_none() && root_font_size.is_none() {
return None; return None;
} }
Some(GSettingsSnapshot { Some(GSettingsSnapshot { variant, accent })
variant,
accent,
root_font_size,
})
}
fn font_root_px(name: &str) -> Option<Pixels> {
let points = name.split_whitespace().last()?.parse::<f32>().ok()?;
(points > 0.0).then(|| gpui::px(points * 96.0 / 72.0))
} }
pub(crate) fn platform_source() -> Box<dyn ThemeSource> { pub(crate) fn platform_source() -> Box<dyn ThemeSource> {
@@ -174,22 +142,6 @@ impl LinuxSource {
SystemTheme { SystemTheme {
variant, variant,
accent, accent,
palette: PartialPalette::default(),
control_radius: Some(gpui::px(CONTROL_RADIUS_PX)),
overlay_radius: Some(gpui::px(OVERLAY_RADIUS_PX)),
sm_radius: Some(gpui::px(SM_RADIUS_PX)),
control_height: Some(gpui::px(CONTROL_HEIGHT_PX)),
input_height: Some(gpui::px(CONTROL_HEIGHT_PX)),
menu_item_height: Some(gpui::px(MENU_ITEM_HEIGHT_PX)),
switch_height: Some(gpui::px(SWITCH_HEIGHT_PX)),
switch_width: Some(gpui::px(SWITCH_WIDTH_PX)),
switch_knob: Some(gpui::px(SWITCH_KNOB_PX)),
titlebar_height: Some(gpui::px(TITLEBAR_HEIGHT_PX)),
root_font_size: Some(
self.gsettings
.and_then(|gsettings| gsettings.root_font_size)
.unwrap_or(gpui::px(ROOT_FONT_SIZE_PX)),
),
accessibility, accessibility,
window_background: None, window_background: None,
source: SourceKind::Gnome, source: SourceKind::Gnome,
@@ -358,25 +310,7 @@ mod tests {
} }
#[test] #[test]
fn the_gsettings_font_name_states_the_root_font_size() { fn the_gnome_snapshot_labels_gnome() {
assert_eq!(
font_root_px("Adwaita Sans 11"),
Some(gpui::px(11.0 * 96.0 / 72.0))
);
assert_eq!(
font_root_px("Noto Sans 10"),
Some(gpui::px(10.0 * 96.0 / 72.0))
);
assert_eq!(
font_root_px("Cantarell Bold 12.5"),
Some(gpui::px(12.5 * 96.0 / 72.0))
);
assert_eq!(font_root_px("Adwaita Sans"), None);
assert_eq!(font_root_px("Sans 0"), None);
}
#[test]
fn the_gnome_snapshot_labels_gnome_and_defaults_the_root_font() {
let source = LinuxSource { let source = LinuxSource {
backend: Backend::Portal, backend: Backend::Portal,
portal: None, portal: None,
@@ -391,7 +325,7 @@ mod tests {
); );
assert_eq!(system.source, SourceKind::Gnome); assert_eq!(system.source, SourceKind::Gnome);
// The default 11pt font when gsettings states none. assert_eq!(system.variant, ThemeVariant::Light);
assert_eq!(system.root_font_size, Some(gpui::px(ROOT_FONT_SIZE_PX))); assert_eq!(system.accent, None);
} }
} }
+4 -89
View File
@@ -1,14 +1,12 @@
//! macOS Adapter //! macOS Adapter
//! //!
//! Reads AppKit's semantic colors in the effective appearance and watches //! Reads the system accent and watches the system's color preferences.
//! the system's color preferences.
use objc2::rc::Retained; use objc2::rc::Retained;
use objc2::runtime::{AnyObject, NSObject}; use objc2::runtime::{AnyObject, NSObject};
use objc2::{AnyThread, DefinedClass, define_class, msg_send, sel}; use objc2::{AnyThread, DefinedClass, define_class, msg_send, sel};
use objc2_app_kit::{ use objc2_app_kit::{
NSAppearance, NSAppearanceNameAqua, NSAppearanceNameDarkAqua, NSColor, NSColorSpace, NSColor, NSColorSpace, NSWorkspace, NSWorkspaceAccessibilityDisplayOptionsDidChangeNotification,
NSWorkspace, NSWorkspaceAccessibilityDisplayOptionsDidChangeNotification,
}; };
use objc2_foundation::{ use objc2_foundation::{
NSDictionary, NSDistributedNotificationCenter, NSKeyValueObservingOptions, NSNotification, NSDictionary, NSDistributedNotificationCenter, NSKeyValueObservingOptions, NSNotification,
@@ -20,24 +18,7 @@ use super::narrow_component;
use super::ThemeSource; use super::ThemeSource;
use super::signal::ReapplySignal; use super::signal::ReapplySignal;
use crate::ThemeVariant; use crate::ThemeVariant;
use crate::system::{AccessibilityPreferences, PartialPalette, SourceKind, SystemTheme}; use crate::system::{AccessibilityPreferences, SourceKind, SystemTheme};
/// Default control radius for macOS controls.
const CONTROL_RADIUS_PTS: f32 = 6.0;
/// The text field's intrinsic height at regular size, square or rounded bezel alike.
const INPUT_HEIGHT_PTS: f32 = 24.0;
/// AppKit's regular push button, measured via `NSButton::fittingSize`.
const CONTROL_HEIGHT_PTS: f32 = 24.0;
/// The `NSMenu` row height; 20 before the macOS 26 redesign.
const MENU_ITEM_HEIGHT_PTS: f32 = 24.0;
/// `NSSwitch`, measured via `fittingSize`.
const SWITCH_TRACK_HEIGHT_PTS: f32 = 24.0;
const SWITCH_TRACK_WIDTH_PTS: f32 = 54.0;
const SWITCH_KNOB_PTS: f32 = 20.0;
/// The standard titled window's titlebar, measured via `contentLayoutRect`.
const TITLEBAR_HEIGHT_PTS: f32 = 32.0;
/// The HIG's default body text on macOS is 13 pt (system font size 13 at 1x).
const ROOT_FONT_SIZE_PTS: f32 = 13.0;
// An observer that forwards distributed notifications and preference. // An observer that forwards distributed notifications and preference.
define_class!( define_class!(
@@ -91,58 +72,6 @@ impl MacosSource {
a: narrow_component(converted.alphaComponent()), a: narrow_component(converted.alphaComponent()),
})) }))
} }
/// Resolves the semantic colors with `variant` as the current drawing appearance.
fn snapshot_in_appearance(&self, variant: ThemeVariant) -> PartialPalette {
let name = match variant {
ThemeVariant::Light => {
// SAFETY: extern statics exported by AppKit, always initialized.
unsafe { NSAppearanceNameAqua }
}
ThemeVariant::Dark => {
// SAFETY: as above.
unsafe { NSAppearanceNameDarkAqua }
}
};
let Some(appearance) = NSAppearance::appearanceNamed(name) else {
return self.read_palette();
};
let palette = std::cell::Cell::new(PartialPalette::default());
appearance.performAsCurrentDrawingAppearance(&block2::RcBlock::new(|| {
palette.set(self.read_palette());
}));
palette.into_inner()
}
fn read_palette(&self) -> PartialPalette {
PartialPalette {
background: Self::color_to_hsla(&NSColor::windowBackgroundColor()),
foreground: Self::color_to_hsla(&NSColor::labelColor()),
surface: Self::color_to_hsla(&NSColor::textBackgroundColor()),
surface_foreground: Self::color_to_hsla(&NSColor::labelColor()),
sidebar: Self::color_to_hsla(&NSColor::windowBackgroundColor()),
primary_foreground: Self::color_to_hsla(&NSColor::alternateSelectedControlTextColor()),
accent_foreground: Self::color_to_hsla(&NSColor::alternateSelectedControlTextColor()),
secondary: None,
secondary_foreground: Self::color_to_hsla(&NSColor::secondaryLabelColor()),
muted: None,
muted_hover: None,
muted_foreground: Self::color_to_hsla(&NSColor::secondaryLabelColor()),
destructive: Self::color_to_hsla(&NSColor::systemRedColor()),
success: None,
warning: None,
info: None,
border: Self::color_to_hsla(&NSColor::separatorColor()),
input: Self::color_to_hsla(&NSColor::controlBackgroundColor()),
ring: Self::color_to_hsla(&NSColor::keyboardFocusIndicatorColor()),
selection: Self::color_to_hsla(&NSColor::selectedTextBackgroundColor()),
overlay: None,
scrollbar_thumb: None,
}
}
} }
impl ThemeSource for MacosSource { impl ThemeSource for MacosSource {
@@ -155,26 +84,12 @@ impl ThemeSource for MacosSource {
reduce_transparency: workspace.accessibilityDisplayShouldReduceTransparency(), reduce_transparency: workspace.accessibilityDisplayShouldReduceTransparency(),
}; };
let palette = self.snapshot_in_appearance(variant);
SystemTheme { SystemTheme {
variant, variant,
accent: Self::color_to_hsla(&NSColor::controlAccentColor()), accent: Self::color_to_hsla(&NSColor::controlAccentColor()),
palette, accessibility,
// macOS blurs what is behind the window natively. // macOS blurs what is behind the window natively.
window_background: Some(gpui::WindowBackgroundAppearance::Blurred), window_background: Some(gpui::WindowBackgroundAppearance::Blurred),
control_radius: Some(gpui::px(CONTROL_RADIUS_PTS)),
overlay_radius: None,
sm_radius: None,
control_height: Some(gpui::px(CONTROL_HEIGHT_PTS)),
input_height: Some(gpui::px(INPUT_HEIGHT_PTS)),
menu_item_height: Some(gpui::px(MENU_ITEM_HEIGHT_PTS)),
switch_height: Some(gpui::px(SWITCH_TRACK_HEIGHT_PTS)),
switch_width: Some(gpui::px(SWITCH_TRACK_WIDTH_PTS)),
switch_knob: Some(gpui::px(SWITCH_KNOB_PTS)),
titlebar_height: Some(gpui::px(TITLEBAR_HEIGHT_PTS)),
root_font_size: Some(gpui::px(ROOT_FONT_SIZE_PTS)),
accessibility,
source: SourceKind::Macos, source: SourceKind::Macos,
} }
} }
+8 -64
View File
@@ -5,15 +5,14 @@
use gpui::Hsla; use gpui::Hsla;
use toml::Table; use toml::Table;
use crate::system::{PartialPalette, SourceKind, SystemTheme}; use crate::system::{SourceKind, SystemTheme};
use crate::{AccessibilityPreferences, ThemeVariant}; use crate::{AccessibilityPreferences, ThemeVariant};
/// The palette Omarchy deploys with the current theme. /// The mode and accent Omarchy deploys with the current theme.
#[derive(Clone, Copy, Debug, PartialEq)] #[derive(Clone, Copy, Debug, PartialEq)]
pub(crate) struct OmarchyTheme { pub(crate) struct OmarchyTheme {
pub(crate) variant: ThemeVariant, pub(crate) variant: ThemeVariant,
pub(crate) accent: Option<Hsla>, pub(crate) accent: Option<Hsla>,
pub(crate) palette: PartialPalette,
} }
impl OmarchyTheme { impl OmarchyTheme {
@@ -21,7 +20,6 @@ impl OmarchyTheme {
let table = text.parse::<Table>().ok()?; let table = text.parse::<Table>().ok()?;
let background = hex_color(&table, "background")?; let background = hex_color(&table, "background")?;
let foreground = hex_color(&table, "foreground")?;
let variant = table let variant = table
.get("mode") .get("mode")
@@ -30,47 +28,14 @@ impl OmarchyTheme {
.unwrap_or_else(|| ThemeVariant::by_lightness(background)); .unwrap_or_else(|| ThemeVariant::by_lightness(background));
let accent = hex_color(&table, "accent").or_else(|| hex_color(&table, "color4")); let accent = hex_color(&table, "accent").or_else(|| hex_color(&table, "color4"));
let selection = hex_color(&table, "selection");
let muted_foreground =
hex_color(&table, "dark_foreground").or_else(|| hex_color(&table, "color8"));
let palette = PartialPalette { Some(Self { variant, accent })
background: Some(background),
foreground: Some(foreground),
surface: hex_color(&table, "lighter_background"),
surface_foreground: Some(foreground),
muted_foreground,
destructive: hex_color(&table, "red").or_else(|| hex_color(&table, "color1")),
success: hex_color(&table, "green").or_else(|| hex_color(&table, "color2")),
warning: hex_color(&table, "yellow").or_else(|| hex_color(&table, "orange")),
ring: accent,
selection,
..PartialPalette::default()
};
Some(Self {
variant,
accent,
palette,
})
} }
pub(crate) fn into_system(self, accessibility: AccessibilityPreferences) -> SystemTheme { pub(crate) fn into_system(self, accessibility: AccessibilityPreferences) -> SystemTheme {
SystemTheme { SystemTheme {
variant: self.variant, variant: self.variant,
accent: self.accent, accent: self.accent,
palette: self.palette,
control_radius: Some(gpui::px(9.)),
overlay_radius: Some(gpui::px(15.)),
sm_radius: Some(gpui::px(6.)),
control_height: Some(gpui::px(34.)),
input_height: Some(gpui::px(34.)),
menu_item_height: Some(gpui::px(32.)),
switch_height: Some(gpui::px(26.)),
switch_width: Some(gpui::px(46.)),
switch_knob: Some(gpui::px(20.)),
titlebar_height: None,
root_font_size: None,
accessibility, accessibility,
window_background: None, window_background: None,
source: SourceKind::Omarchy, source: SourceKind::Omarchy,
@@ -171,25 +136,11 @@ color15 = \"#635d6f\"
"; ";
#[test] #[test]
fn semantic_keys_map_onto_roles() { fn semantic_keys_state_the_mode_and_accent() {
let theme = OmarchyTheme::parse(TOKYO_NIGHT).expect("tokyo-night parses"); let theme = OmarchyTheme::parse(TOKYO_NIGHT).expect("tokyo-night parses");
assert_eq!(theme.variant, ThemeVariant::Dark); assert_eq!(theme.variant, ThemeVariant::Dark);
assert_eq!(theme.accent, Some(Hsla::from(gpui::rgb(0x7aa2f7)))); assert_eq!(theme.accent, Some(Hsla::from(gpui::rgb(0x7aa2f7))));
let palette = theme.palette;
let background = palette.background.expect("background stated");
assert_eq!(background, Hsla::from(gpui::rgb(0x1a1b26)));
assert_eq!(palette.surface, Some(Hsla::from(gpui::rgb(0x24283b))));
assert_eq!(
palette.muted_foreground,
Some(Hsla::from(gpui::rgb(0x565f89)))
);
assert_eq!(palette.destructive, Some(Hsla::from(gpui::rgb(0xf7768e))));
assert_eq!(palette.success, Some(Hsla::from(gpui::rgb(0x9ece6a))));
assert_eq!(palette.warning, Some(Hsla::from(gpui::rgb(0xe0af68))));
assert_eq!(palette.selection, Some(Hsla::from(gpui::rgb(0x292e42))));
assert_eq!(palette.ring, theme.accent);
} }
#[test] #[test]
@@ -198,14 +149,6 @@ color15 = \"#635d6f\"
assert_eq!(theme.variant, ThemeVariant::Light); assert_eq!(theme.variant, ThemeVariant::Light);
assert_eq!(theme.accent, Some(Hsla::from(gpui::rgb(0x0060ff)))); assert_eq!(theme.accent, Some(Hsla::from(gpui::rgb(0x0060ff))));
assert_eq!(
theme.palette.destructive,
Some(Hsla::from(gpui::rgb(0xab2833)))
);
assert_eq!(
theme.palette.muted_foreground,
Some(Hsla::from(gpui::rgb(0x625e6a)))
);
} }
#[test] #[test]
@@ -216,11 +159,12 @@ color15 = \"#635d6f\"
} }
#[test] #[test]
fn omarchy_states_no_titlebar_or_root_font() { fn the_system_snapshot_keeps_only_mode_and_accent() {
let theme = OmarchyTheme::parse(TOKYO_NIGHT).expect("parses"); let theme = OmarchyTheme::parse(TOKYO_NIGHT).expect("parses");
let system = theme.into_system(Default::default()); let system = theme.into_system(Default::default());
assert_eq!(system.titlebar_height, None); assert_eq!(system.variant, ThemeVariant::Dark);
assert_eq!(system.root_font_size, None); assert_eq!(system.accent, theme.accent);
assert_eq!(system.source, SourceKind::Omarchy);
} }
} }
+3 -55
View File
@@ -1,7 +1,6 @@
//! Windows 11 adapter: WinRT `UISettings` semantic colors with a //! Windows 11 adapter: WinRT `UISettings` accent and background with a
//! `Personalize` registry fallback, watched through `ColorValuesChanged`, //! `Personalize` registry fallback, watched through `ColorValuesChanged`,
//! `TextScaleFactorChanged`, `AdvancedEffectsEnabledChanged`, and //! `AdvancedEffectsEnabledChanged`, and `HighContrastChanged`.
//! `HighContrastChanged`.
use windows::Foundation::TypedEventHandler; use windows::Foundation::TypedEventHandler;
use windows::UI::ViewManagement::{AccessibilitySettings, UIColorType, UISettings}; use windows::UI::ViewManagement::{AccessibilitySettings, UIColorType, UISettings};
@@ -12,26 +11,7 @@ use windows::core::IInspectable;
use super::ThemeSource; use super::ThemeSource;
use super::signal::ReapplySignal; use super::signal::ReapplySignal;
use crate::ThemeVariant; use crate::ThemeVariant;
use crate::system::{AccessibilityPreferences, PartialPalette, SourceKind, SystemTheme}; use crate::system::{AccessibilityPreferences, SourceKind, SystemTheme};
/// WinUI 11's `ControlCornerRadius`, in pixels at 100% scaling.
const CONTROL_RADIUS_PX: f32 = 4.0;
/// WinUI 11's `OverlayCornerRadius`, in pixels at 100% scaling.
const OVERLAY_RADIUS_PX: f32 = 8.0;
/// WinUI 11's default text-box height, in pixels at 100% scaling.
const INPUT_HEIGHT_PX: f32 = 32.0;
/// The default button height, in pixels at 100% scaling.
const CONTROL_HEIGHT_PX: f32 = 32.0;
/// The default menu row: item padding 4/5 + a 20px Body line + 2px item margins.
const MENU_ITEM_HEIGHT_PX: f32 = 33.0;
/// ToggleSwitch: a 40x20 track with a 12px resting knob.
const SWITCH_TRACK_HEIGHT_PX: f32 = 20.0;
const SWITCH_TRACK_WIDTH_PX: f32 = 40.0;
const SWITCH_KNOB_PX: f32 = 12.0;
/// The window caption's height, in pixels at 100% scaling, as Win32 reports it.
const TITLEBAR_HEIGHT_PX: f32 = 32.0;
/// WinUI 11's default body text size, in pixels at 100% scaling.
const ROOT_FONT_SIZE_PX: f32 = 14.0;
/// The `Personalize` registry values and the OS build number. /// The `Personalize` registry values and the OS build number.
#[derive(Clone, Copy, Debug, Default)] #[derive(Clone, Copy, Debug, Default)]
@@ -159,7 +139,6 @@ impl ThemeSource for WindowsSource {
fn snapshot(&self, variant: ThemeVariant) -> SystemTheme { fn snapshot(&self, variant: ThemeVariant) -> SystemTheme {
let accent = self.color(UIColorType::Accent); let accent = self.color(UIColorType::Accent);
let background = self.color(UIColorType::Background); let background = self.color(UIColorType::Background);
let foreground = self.color(UIColorType::Foreground);
let variant = background let variant = background
.map(ThemeVariant::by_lightness) .map(ThemeVariant::by_lightness)
@@ -172,30 +151,9 @@ impl ThemeSource for WindowsSource {
})) }))
.unwrap_or(variant); .unwrap_or(variant);
let text_scale = self.ui_settings.TextScaleFactor().unwrap_or(1.0);
SystemTheme { SystemTheme {
variant, variant,
accent, accent,
// Windows states its ramp through UIColorType's accent variants.
palette: PartialPalette {
background,
foreground,
// Windows paints keyboard focus with the accent itself.
ring: accent,
..PartialPalette::default()
},
control_radius: Some(gpui::px(CONTROL_RADIUS_PX)),
overlay_radius: Some(gpui::px(OVERLAY_RADIUS_PX)),
sm_radius: None,
control_height: Some(gpui::px(CONTROL_HEIGHT_PX)),
input_height: Some(gpui::px(INPUT_HEIGHT_PX)),
menu_item_height: Some(gpui::px(MENU_ITEM_HEIGHT_PX)),
switch_height: Some(gpui::px(SWITCH_TRACK_HEIGHT_PX)),
switch_width: Some(gpui::px(SWITCH_TRACK_WIDTH_PX)),
switch_knob: Some(gpui::px(SWITCH_KNOB_PX)),
titlebar_height: Some(gpui::px(TITLEBAR_HEIGHT_PX)),
root_font_size: Some(gpui::px(ROOT_FONT_SIZE_PX * text_scale as f32)),
accessibility: self.accessibility(), accessibility: self.accessibility(),
window_background: self.window_material(), window_background: self.window_material(),
source: SourceKind::Windows, source: SourceKind::Windows,
@@ -214,16 +172,6 @@ impl ThemeSource for WindowsSource {
log::warn!("theme: color change watch failed: {error}"); log::warn!("theme: color change watch failed: {error}");
} }
let scale_signal = signal.sender();
let scale_handler = TypedEventHandler::<UISettings, IInspectable>::new(move |_, _| {
ReapplySignal::poke(&scale_signal);
Ok(())
});
if let Err(error) = self.ui_settings.TextScaleFactorChanged(&scale_handler) {
log::warn!("theme: text scale watch failed: {error}");
}
let effects_signal = signal.sender(); let effects_signal = signal.sender();
let effects_handler = TypedEventHandler::<UISettings, IInspectable>::new(move |_, _| { let effects_handler = TypedEventHandler::<UISettings, IInspectable>::new(move |_, _| {
ReapplySignal::poke(&effects_signal); ReapplySignal::poke(&effects_signal);
+1 -79
View File
@@ -1,6 +1,6 @@
//! The normalized snapshot a platform adapter produces. //! The normalized snapshot a platform adapter produces.
use gpui::{Hsla, Pixels, WindowBackgroundAppearance, px}; use gpui::{Hsla, WindowBackgroundAppearance};
use crate::ThemeVariant; use crate::ThemeVariant;
@@ -43,49 +43,6 @@ impl SourceKind {
pub fn scrollbar_autohide(self) -> bool { pub fn scrollbar_autohide(self) -> bool {
matches!(self, Self::Macos | Self::Omarchy | Self::Gnome) matches!(self, Self::Macos | Self::Omarchy | Self::Gnome)
} }
/// The base spacing unit:
///
/// - GNOME lays out on a 6px grid
/// - Other platform on 4px grid
pub fn spacing_unit(self) -> Pixels {
match self {
Self::Gnome | Self::Omarchy => px(6.),
_ => px(4.),
}
}
}
/// A partial palette with optional colors.
#[derive(Clone, Copy, Debug, Default, PartialEq)]
pub struct PartialPalette {
pub background: Option<Hsla>,
pub foreground: Option<Hsla>,
pub surface: Option<Hsla>,
pub surface_foreground: Option<Hsla>,
/// Only macOS states it, the window backdrop its sidebars show.
pub sidebar: Option<Hsla>,
pub primary_foreground: Option<Hsla>,
pub accent_foreground: Option<Hsla>,
pub secondary: Option<Hsla>,
pub secondary_foreground: Option<Hsla>,
pub muted: Option<Hsla>,
/// No platform states a hover wash, presets override it.
pub muted_hover: Option<Hsla>,
pub muted_foreground: Option<Hsla>,
pub destructive: Option<Hsla>,
/// No platform states severity colors, presets override them.
pub success: Option<Hsla>,
pub warning: Option<Hsla>,
pub info: Option<Hsla>,
pub border: Option<Hsla>,
pub input: Option<Hsla>,
pub ring: Option<Hsla>,
pub selection: Option<Hsla>,
/// No platform states a scrim color; preset and user files override it.
pub overlay: Option<Hsla>,
/// No platform states a scrollbar thumb color; presets override it.
pub scrollbar_thumb: Option<Hsla>,
} }
/// A normalized snapshot of the running system's theme. /// A normalized snapshot of the running system's theme.
@@ -93,29 +50,6 @@ pub struct PartialPalette {
pub struct SystemTheme { pub struct SystemTheme {
pub variant: ThemeVariant, pub variant: ThemeVariant,
pub accent: Option<Hsla>, pub accent: Option<Hsla>,
pub palette: PartialPalette,
/// The platform's stated control corner radius, if it has one.
pub control_radius: Option<Pixels>,
/// The platform's stated menu/popover radius, if it has one.
pub overlay_radius: Option<Pixels>,
/// The platform's stated checkbox radius, if it has one.
pub sm_radius: Option<Pixels>,
/// The platform's stated control height, if it has one.
pub control_height: Option<Pixels>,
/// The platform's stated text-field height, if it has one.
pub input_height: Option<Pixels>,
/// The platform's stated menu row height, if it has one.
pub menu_item_height: Option<Pixels>,
/// The platform's stated switch track height, if it has one.
pub switch_height: Option<Pixels>,
/// The platform's stated switch track width, if it has one.
pub switch_width: Option<Pixels>,
/// The platform's stated switch knob size, if it has one.
pub switch_knob: Option<Pixels>,
/// The platform's native titlebar height, if it states one.
pub titlebar_height: Option<Pixels>,
/// The platform's native root font size, if it has one.
pub root_font_size: Option<Pixels>,
pub accessibility: AccessibilityPreferences, pub accessibility: AccessibilityPreferences,
/// The window material the platform natively applies, if any. /// The window material the platform natively applies, if any.
pub window_background: Option<WindowBackgroundAppearance>, pub window_background: Option<WindowBackgroundAppearance>,
@@ -127,18 +61,6 @@ impl SystemTheme {
Self { Self {
variant, variant,
accent: None, accent: None,
palette: PartialPalette::default(),
control_radius: None,
overlay_radius: None,
sm_radius: None,
control_height: None,
input_height: None,
menu_item_height: None,
switch_height: None,
switch_width: None,
switch_knob: None,
titlebar_height: None,
root_font_size: None,
accessibility: AccessibilityPreferences::default(), accessibility: AccessibilityPreferences::default(),
window_background: None, window_background: None,
source: SourceKind::Fallback, source: SourceKind::Fallback,
+65 -387
View File
@@ -1,224 +1,29 @@
//! The platform's type ladder: eleven roles resolved from the OS's own text //! One type ladder shared by every platform, scaled by the theme's root font
//! styles. //! size.
//!
//! Each [`SourceKind`] paints its stated ramp — Apple's macOS built-in text
//! styles, WinUI's type ramp, GTK 4's typography classes, Kirigami's heading
//! levels — and every rung scales with the theme's root font size, the way
//! XAML text scaling and GTK's relative font sizes work. Platforms that state
//! no styles paint the neutral ladder.
use gpui::{App, FontWeight, Pixels, Styled, px}; use gpui::{App, FontWeight, Pixels, Styled, px};
use crate::ActiveTheme; use crate::ActiveTheme;
use crate::system::SourceKind;
const MACOS_BASE_PX: f32 = 13.0; /// The shared ladder at a 16px root: size, line height, then weight.
const WINDOWS_BASE_PX: f32 = 14.0; const LADDER: [Rung; 11] = [
const GNOME_BASE_PX: f32 = 44.0 / 3.0; (24.0, 32.0, FontWeight::SEMIBOLD),
const KDE_BASE_PX: f32 = 40.0 / 3.0;
const NEUTRAL_BASE_PX: f32 = 16.0;
const GNOME_LEADING: f32 = 1.33;
const KDE_LEADING: f32 = 1.36;
/// Apple's macOS built-in text styles (HIG, Typography specifications).
const MACOS: [Rung; 11] = [
// Large Title
(26.0, 32.0, FontWeight::NORMAL),
// Title 1
(22.0, 26.0, FontWeight::NORMAL),
// Title 2
(17.0, 22.0, FontWeight::NORMAL),
// Title 3
(15.0, 20.0, FontWeight::NORMAL),
// Headline
(13.0, 16.0, FontWeight::SEMIBOLD),
// Body
(13.0, 16.0, FontWeight::NORMAL),
// Callout
(12.0, 15.0, FontWeight::NORMAL),
// Subheadline
(11.0, 14.0, FontWeight::NORMAL),
// Footnote
(10.0, 13.0, FontWeight::NORMAL),
// Caption 1
(10.0, 13.0, FontWeight::NORMAL),
// Caption 2
(10.0, 13.0, FontWeight::MEDIUM),
];
/// WinUI's type ramp (Segoe UI Variable, Windows 11).
const WINDOWS: [Rung; 11] = [
// TitleLarge
(40.0, 52.0, FontWeight::SEMIBOLD),
// Title
(28.0, 36.0, FontWeight::SEMIBOLD),
// Subtitle
(20.0, 28.0, FontWeight::SEMIBOLD), (20.0, 28.0, FontWeight::SEMIBOLD),
// BodyLarge (18.0, 24.0, FontWeight::SEMIBOLD),
(18.0, 24.0, FontWeight::NORMAL), (16.0, 24.0, FontWeight::BOLD),
// BodyStrong (14.0, 20.0, FontWeight::BOLD),
(14.0, 20.0, FontWeight::SEMIBOLD),
// Body
(14.0, 20.0, FontWeight::NORMAL),
// Body
(14.0, 20.0, FontWeight::NORMAL),
// Caption
(12.0, 16.0, FontWeight::NORMAL),
// Caption
(12.0, 16.0, FontWeight::NORMAL),
// Caption
(12.0, 16.0, FontWeight::NORMAL),
// Caption
(12.0, 16.0, FontWeight::NORMAL),
];
/// GTK 4's typography classes (Adwaita, "General Typography"), stated as
/// percentages of the default font.
const GNOME: [Rung; 11] = [
// large-title: 240%, light
(
GNOME_BASE_PX * 2.4,
GNOME_BASE_PX * 2.4 * GNOME_LEADING,
FontWeight::LIGHT,
),
// title-1: 200%
(
GNOME_BASE_PX * 2.0,
GNOME_BASE_PX * 2.0 * GNOME_LEADING,
FontWeight::EXTRA_BOLD,
),
// title-2: 150%
(
GNOME_BASE_PX * 1.5,
GNOME_BASE_PX * 1.5 * GNOME_LEADING,
FontWeight::EXTRA_BOLD,
),
// title-3: 150%
(
GNOME_BASE_PX * 1.5,
GNOME_BASE_PX * 1.5 * GNOME_LEADING,
FontWeight::BOLD,
),
// heading: 110%
(
GNOME_BASE_PX * 1.1,
GNOME_BASE_PX * 1.1 * GNOME_LEADING,
FontWeight::BOLD,
),
// body: the default font; the HIG's body is control-label size, so the
// theme's `.body` class adds a further 10% only where apps ask for it.
(
GNOME_BASE_PX,
GNOME_BASE_PX * GNOME_LEADING,
FontWeight::NORMAL,
),
// body
(
GNOME_BASE_PX,
GNOME_BASE_PX * GNOME_LEADING,
FontWeight::NORMAL,
),
// caption: 90%
(
GNOME_BASE_PX * 0.9,
GNOME_BASE_PX * 0.9 * GNOME_LEADING,
FontWeight::NORMAL,
),
// caption
(
GNOME_BASE_PX * 0.9,
GNOME_BASE_PX * 0.9 * GNOME_LEADING,
FontWeight::NORMAL,
),
// caption
(
GNOME_BASE_PX * 0.9,
GNOME_BASE_PX * 0.9 * GNOME_LEADING,
FontWeight::NORMAL,
),
// caption-heading: 90%
(
GNOME_BASE_PX * 0.9,
GNOME_BASE_PX * 0.9 * GNOME_LEADING,
FontWeight::BOLD,
),
];
/// Kirigami's heading levels and Plasma's small font (Breeze).
const KDE: [Rung; 11] = [
// Heading level 1: 1.35×, DemiBold
(
KDE_BASE_PX * 1.35,
KDE_BASE_PX * 1.35 * KDE_LEADING,
FontWeight::SEMIBOLD,
),
// level 2: 1.20×
(
KDE_BASE_PX * 1.2,
KDE_BASE_PX * 1.2 * KDE_LEADING,
FontWeight::SEMIBOLD,
),
// level 3: 1.15×
(
KDE_BASE_PX * 1.15,
KDE_BASE_PX * 1.15 * KDE_LEADING,
FontWeight::SEMIBOLD,
),
// level 4: 1.10×
(
KDE_BASE_PX * 1.1,
KDE_BASE_PX * 1.1 * KDE_LEADING,
FontWeight::SEMIBOLD,
),
// level 5: DemiBold at the default size
(KDE_BASE_PX, KDE_BASE_PX * KDE_LEADING, FontWeight::SEMIBOLD),
// the default font
(KDE_BASE_PX, KDE_BASE_PX * KDE_LEADING, FontWeight::NORMAL),
// the default font
(KDE_BASE_PX, KDE_BASE_PX * KDE_LEADING, FontWeight::NORMAL),
// Plasma's small font (8pt at the 10pt default)
(
KDE_BASE_PX * 0.8,
KDE_BASE_PX * 0.8 * KDE_LEADING,
FontWeight::NORMAL,
),
(
KDE_BASE_PX * 0.8,
KDE_BASE_PX * 0.8 * KDE_LEADING,
FontWeight::NORMAL,
),
(
KDE_BASE_PX * 0.8,
KDE_BASE_PX * 0.8 * KDE_LEADING,
FontWeight::NORMAL,
),
// DemiBold, the platform's only stated emphasis weight
(
KDE_BASE_PX * 0.8,
KDE_BASE_PX * 0.8 * KDE_LEADING,
FontWeight::SEMIBOLD,
),
];
/// The fallback ladder for platforms that state no text styles.
const NEUTRAL: [Rung; 11] = [
(32.0, 40.0, FontWeight::NORMAL),
(24.0, 32.0, FontWeight::NORMAL),
(20.0, 26.0, FontWeight::NORMAL),
(18.0, 24.0, FontWeight::NORMAL),
(16.0, 24.0, FontWeight::SEMIBOLD),
(16.0, 24.0, FontWeight::NORMAL), (16.0, 24.0, FontWeight::NORMAL),
(15.0, 22.0, FontWeight::NORMAL), (14.0, 20.0, FontWeight::NORMAL),
(14.0, 20.0, FontWeight::NORMAL), (14.0, 20.0, FontWeight::NORMAL),
(13.0, 18.0, FontWeight::NORMAL), (13.0, 18.0, FontWeight::NORMAL),
(12.0, 16.0, FontWeight::NORMAL), (12.0, 16.0, FontWeight::NORMAL),
(12.0, 16.0, FontWeight::MEDIUM), (12.0, 16.0, FontWeight::MEDIUM),
]; ];
/// One rung: size and line height at the table's base size, then the weight. /// One rung: size and line height at a 16px root, then the weight.
type Rung = (f32, f32, FontWeight); type Rung = (f32, f32, FontWeight);
/// A role in the platform's type ladder. /// A role in the unified type ladder.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum TextRole { pub enum TextRole {
/// The largest heading — hero panels, greeters, welcome screens. /// The largest heading — hero panels, greeters, welcome screens.
@@ -253,7 +58,7 @@ pub struct TypeMetrics {
pub weight: FontWeight, pub weight: FontWeight,
} }
/// The platform's type ladder, resolved at the theme's root font size. /// The unified type ladder, resolved at the theme's root font size.
#[derive(Clone, Copy, Debug, PartialEq)] #[derive(Clone, Copy, Debug, PartialEq)]
pub struct Typography { pub struct Typography {
pub large_title: TypeMetrics, pub large_title: TypeMetrics,
@@ -270,19 +75,12 @@ pub struct Typography {
} }
impl Typography { impl Typography {
pub(crate) fn resolve(source: SourceKind, root_font_size: Pixels) -> Self { pub(crate) fn resolve(root_font_size: Pixels) -> Self {
let (ladder, base_px) = match source { let scale = root_font_size / px(16.);
SourceKind::Macos => (MACOS, MACOS_BASE_PX),
SourceKind::Windows => (WINDOWS, WINDOWS_BASE_PX),
SourceKind::Gnome => (GNOME, GNOME_BASE_PX),
SourceKind::Kde => (KDE, KDE_BASE_PX),
SourceKind::Fallback | SourceKind::Omarchy => (NEUTRAL, NEUTRAL_BASE_PX),
};
let scale = root_font_size / px(base_px);
let metrics = |(size, line_height, weight): Rung| TypeMetrics { let metrics = |(size, line_height, weight): Rung| TypeMetrics {
size: px(size * scale), size: px(size) * scale,
line_height: px(line_height * scale), line_height: px(line_height) * scale,
weight, weight,
}; };
@@ -298,7 +96,7 @@ impl Typography {
footnote, footnote,
caption, caption,
caption2, caption2,
] = ladder.map(metrics); ] = LADDER.map(metrics);
Self { Self {
large_title, large_title,
@@ -335,7 +133,7 @@ impl Typography {
/// Paints a [`TextRole`] from the resolved theme, on anything styled. /// Paints a [`TextRole`] from the resolved theme, on anything styled.
pub trait Typeset: Styled + Sized { pub trait Typeset: Styled + Sized {
/// Sizes, leads, and weights the element as the platform's `role`. /// Sizes, leads, and weights the element as `role`.
fn typeset(self, role: TextRole, cx: &App) -> Self { fn typeset(self, role: TextRole, cx: &App) -> Self {
let theme = cx.theme(); let theme = cx.theme();
let metrics = theme.typography.get(role); let metrics = theme.typography.get(role);
@@ -351,181 +149,61 @@ impl<E: Styled> Typeset for E {}
mod tests { mod tests {
use super::*; use super::*;
fn typography(source: SourceKind, root_font_size: f32) -> Typography { fn typography(root_font_size: f32) -> Typography {
Typography::resolve(source, px(root_font_size)) Typography::resolve(px(root_font_size))
} }
#[test] #[test]
fn the_platforms_paint_their_stated_styles() { fn the_unified_ladder_matches_the_base_contract() {
let macos = typography(SourceKind::Macos, 13.0); let typography = typography(16.0);
assert_eq!( let expected = [
macos.body, (TextRole::LargeTitle, 24.0, 32.0, FontWeight::SEMIBOLD),
TypeMetrics { (TextRole::Title, 20.0, 28.0, FontWeight::SEMIBOLD),
size: px(13.0), (TextRole::Title2, 18.0, 24.0, FontWeight::SEMIBOLD),
line_height: px(16.0), (TextRole::Title3, 16.0, 24.0, FontWeight::BOLD),
weight: FontWeight::NORMAL (TextRole::Headline, 14.0, 20.0, FontWeight::BOLD),
} (TextRole::Body, 16.0, 24.0, FontWeight::NORMAL),
); (TextRole::Callout, 14.0, 20.0, FontWeight::NORMAL),
assert_eq!( (TextRole::Subheadline, 14.0, 20.0, FontWeight::NORMAL),
macos.headline, (TextRole::Footnote, 13.0, 18.0, FontWeight::NORMAL),
TypeMetrics { (TextRole::Caption, 12.0, 16.0, FontWeight::NORMAL),
size: px(13.0), (TextRole::Caption2, 12.0, 16.0, FontWeight::MEDIUM),
line_height: px(16.0),
weight: FontWeight::SEMIBOLD
}
);
assert_eq!(
macos.caption2,
TypeMetrics {
size: px(10.0),
line_height: px(13.0),
weight: FontWeight::MEDIUM
}
);
assert_eq!(macos.large_title.size, px(26.0));
let windows = typography(SourceKind::Windows, 14.0);
assert_eq!(
windows.body,
TypeMetrics {
size: px(14.0),
line_height: px(20.0),
weight: FontWeight::NORMAL
}
);
assert_eq!(
windows.headline,
TypeMetrics {
size: px(14.0),
line_height: px(20.0),
weight: FontWeight::SEMIBOLD
}
);
assert_eq!(
windows.large_title,
TypeMetrics {
size: px(40.0),
line_height: px(52.0),
weight: FontWeight::SEMIBOLD
}
);
let gnome_base = 44.0 / 3.0;
let gnome = typography(SourceKind::Gnome, gnome_base);
assert_eq!(
gnome.body,
TypeMetrics {
size: px(gnome_base),
line_height: px(gnome_base * GNOME_LEADING),
weight: FontWeight::NORMAL
}
);
assert_eq!(
gnome.large_title,
TypeMetrics {
size: px(gnome_base * 2.4),
line_height: px(gnome_base * 2.4 * GNOME_LEADING),
weight: FontWeight::LIGHT
}
);
assert_eq!(
gnome.caption2,
TypeMetrics {
size: px(gnome_base * 0.9),
line_height: px(gnome_base * 0.9 * GNOME_LEADING),
weight: FontWeight::BOLD
}
);
let kde_base = 40.0 / 3.0;
let kde = typography(SourceKind::Kde, kde_base);
assert_eq!(
kde.body,
TypeMetrics {
size: px(kde_base),
line_height: px(kde_base * KDE_LEADING),
weight: FontWeight::NORMAL
}
);
assert_eq!(
kde.large_title,
TypeMetrics {
size: px(kde_base * 1.35),
line_height: px(kde_base * 1.35 * KDE_LEADING),
weight: FontWeight::SEMIBOLD
}
);
}
#[test]
fn a_raised_root_font_size_scales_the_whole_ladder() {
// 26pt over macOS's 13pt base doubles every rung, weights carry over.
let doubled = typography(SourceKind::Macos, 26.0);
assert_eq!(
doubled.body,
TypeMetrics {
size: px(26.0),
line_height: px(32.0),
weight: FontWeight::NORMAL
}
);
assert_eq!(
doubled.large_title,
TypeMetrics {
size: px(52.0),
line_height: px(64.0),
weight: FontWeight::NORMAL
}
);
}
#[test]
fn the_body_rung_equals_the_root_font_size_on_every_platform() {
let native = [
(SourceKind::Macos, 13.0),
(SourceKind::Windows, 14.0),
(SourceKind::Gnome, 44.0 / 3.0),
(SourceKind::Kde, 40.0 / 3.0),
(SourceKind::Fallback, 16.0),
(SourceKind::Omarchy, 16.0),
]; ];
for (source, base) in native { for (role, size, line_height, weight) in expected {
let typography = typography(source, base); assert_eq!(
assert_eq!(typography.body.size, px(base), "{source:?}"); typography.get(role),
TypeMetrics {
size: px(size),
line_height: px(line_height),
weight,
},
"{role:?}"
);
} }
let raised = typography(SourceKind::Windows, 18.9);
assert!((raised.body.size - px(18.9)).abs() < px(0.01));
} }
#[test] #[test]
fn every_platform_ladder_descends() { fn the_ladder_scales_from_a_16px_root() {
let sources = [ let base = typography(16.0);
SourceKind::Fallback, let raised = typography(20.0);
SourceKind::Omarchy, for role in [
SourceKind::Macos, TextRole::LargeTitle,
SourceKind::Windows, TextRole::Title,
SourceKind::Gnome, TextRole::Title2,
SourceKind::Kde, TextRole::Title3,
]; TextRole::Headline,
for source in sources { TextRole::Body,
let typography = typography(source, 16.0); TextRole::Callout,
let ladder = [ TextRole::Subheadline,
typography.get(TextRole::LargeTitle).size, TextRole::Footnote,
typography.get(TextRole::Title).size, TextRole::Caption,
typography.get(TextRole::Title2).size, TextRole::Caption2,
typography.get(TextRole::Title3).size, ] {
typography.get(TextRole::Headline).size, let base = base.get(role);
typography.get(TextRole::Body).size, let raised = raised.get(role);
typography.get(TextRole::Callout).size, assert!((raised.size - base.size * 1.25).abs() < px(0.01));
typography.get(TextRole::Subheadline).size, assert!((raised.line_height - base.line_height * 1.25).abs() < px(0.01));
typography.get(TextRole::Footnote).size, assert_eq!(raised.weight, base.weight);
typography.get(TextRole::Caption).size,
typography.get(TextRole::Caption2).size,
];
for pair in ladder.windows(2) {
assert!(pair[0] >= pair[1], "{source:?}: {ladder:?}");
}
} }
} }
} }