chore: enforce clippy lints across workspace
Rust / build (macos-latest, stable) (push) Waiting to run
Rust / build (ubuntu-latest, stable) (push) Waiting to run
Rust / build (windows-latest, stable) (push) Waiting to run

This commit is contained in:
2026-11-20 08:14:03 +07:00
parent 51dd5c8630
commit 01c3ced1c7
85 changed files with 2773 additions and 2001 deletions
+3
View File
@@ -69,3 +69,6 @@ objc2-foundation = { version = "=0.3.2", default-features = false, features = [
[dev-dependencies]
gpui = { workspace = true, features = ["test-support"] }
[lints]
workspace = true
+21 -25
View File
@@ -28,7 +28,8 @@ use gpui::{
use crate::components::button::{Button, ButtonVariant};
use crate::components::common::{
DismissHandler, ResultLogErr as _, Sizable as _, StyledExt as _, TOAST_LAYER, v_flex,
DismissHandler, ResultLogErr as _, Sizable as _, StyledExt as _, TOAST_LAYER, floating_panel,
v_flex,
};
use crate::icons::{Icon, IconRole};
use crate::theme::{ALERT_EDGE_WIDTH, ALERT_STACK_WIDTH, ActiveTheme as _, ENTER_SLIDE_DISTANCE};
@@ -194,10 +195,9 @@ impl RenderOnce for Alert {
});
match self.presentation {
AlertStyle::Overlay => {
let surface = theme.colors.surface;
let border = theme.colors.border;
AlertStyle::Overlay => floating_panel(
cx,
theme.radius.overlay,
div()
.id(self.id.clone())
.role(Role::Alert)
@@ -206,26 +206,22 @@ impl RenderOnce for Alert {
.items_start()
.gap_2()
.px_3()
.py_2()
.rounded(theme.radius.overlay)
.bg(surface)
.border_1()
.border_color(border)
.shadow(theme.elevations.popover.shadows())
.refine_style(&self.style)
.when_some(self.icon.clone(), |alert, icon_glyph| {
alert.child(
div()
.flex_none()
.flex()
.items_center()
.h(window.line_height())
.child(icon_glyph.size(rems(1.0)).color(ramp.base)),
)
})
.child(content)
.when_some(dismiss, |alert, dismiss| alert.child(dismiss))
}
.py_2(),
theme.elevations.popover.shadows(),
)
.refine_style(&self.style)
.when_some(self.icon.clone(), |alert, icon_glyph| {
alert.child(
div()
.flex_none()
.flex()
.items_center()
.h(window.line_height())
.child(icon_glyph.size(rems(1.0)).color(ramp.base)),
)
})
.child(content)
.when_some(dismiss, |alert, dismiss| alert.child(dismiss)),
AlertStyle::Inline => div()
.id(self.id.clone())
.role(Role::Alert)
+17
View File
@@ -11,6 +11,7 @@
//! .picture(Some("https://example.com/ada.png"));
//! ```
use std::collections::HashMap;
use std::fmt::Display;
use gpui::{
@@ -211,7 +212,23 @@ impl RenderOnce for PixelAvatar {
}
}
// Computed identicon patterns per seed, so avatars do not reroll their PRNG every frame.
thread_local! {
static PATTERN_CACHE: std::cell::RefCell<HashMap<u64, [u8; GRID_SIZE * GRID_SIZE]>> =
std::cell::RefCell::new(HashMap::new());
}
fn pattern(seed: u64) -> [u8; GRID_SIZE * GRID_SIZE] {
let cached = PATTERN_CACHE.with(|cache| cache.borrow().get(&seed).copied());
if let Some(cached) = cached {
return cached;
}
let computed = compute_pattern(seed);
PATTERN_CACHE.with(|cache| cache.borrow_mut().insert(seed, computed));
computed
}
fn compute_pattern(seed: u64) -> [u8; GRID_SIZE * GRID_SIZE] {
let mut rng = PixelRng::new(seed);
let mut pattern = [0u8; GRID_SIZE * GRID_SIZE];
let mut filled = 0usize;
+73 -51
View File
@@ -15,7 +15,7 @@ use std::rc::Rc;
use gpui::prelude::FluentBuilder as _;
use gpui::{
AnyElement, AnyView, App, ClickEvent, ElementId, InteractiveElement as _, IntoElement,
AnyElement, AnyView, App, ClickEvent, ElementId, Hsla, InteractiveElement as _, IntoElement,
ParentElement, RenderOnce, Role, SharedString, StatefulInteractiveElement as _,
StyleRefinement, Styled as _, Window, canvas, relative, transparent_black,
};
@@ -47,6 +47,65 @@ pub enum ButtonVariant {
Destructive,
}
/// The variant colors a button paints with, resolved from the active theme.
pub struct ButtonChrome {
/// The resting background, `None` for unpainted variants like `Ghost`.
pub background: Option<Hsla>,
pub foreground: Hsla,
pub hover: Hsla,
pub pressed: Hsla,
pub border: Hsla,
pub hover_border: Hsla,
pub pressed_border: Hsla,
}
impl ButtonVariant {
/// The variant's colors from the active theme.
pub fn chrome(&self, cx: &App) -> ButtonChrome {
let theme = cx.theme();
let colors = theme.colors;
let ramps = theme.ramps;
match self {
Self::Primary => ButtonChrome {
background: Some(ramps.primary.base),
foreground: colors.primary_foreground,
hover: ramps.primary.hover,
pressed: ramps.primary.pressed,
border: ramps.primary.base,
hover_border: ramps.primary.hover,
pressed_border: ramps.primary.pressed,
},
Self::Secondary => ButtonChrome {
background: Some(colors.surface),
foreground: colors.foreground,
hover: colors.muted,
pressed: colors.muted_hover,
border: colors.border,
hover_border: colors.border,
pressed_border: colors.border,
},
Self::Ghost => ButtonChrome {
background: None,
foreground: colors.foreground,
hover: colors.muted_hover,
pressed: ramps.secondary.pressed,
border: transparent_black(),
hover_border: transparent_black(),
pressed_border: transparent_black(),
},
Self::Destructive => ButtonChrome {
background: Some(ramps.destructive.base),
foreground: colors.destructive_foreground,
hover: ramps.destructive.hover,
pressed: ramps.destructive.pressed,
border: ramps.destructive.base,
hover_border: ramps.destructive.hover,
pressed_border: ramps.destructive.pressed,
},
}
}
}
/// Which edge the button's content aligns to.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum ButtonSide {
@@ -236,13 +295,21 @@ impl Sizable for Button {
impl RenderOnce for Button {
fn render(self, _window: &mut Window, cx: &mut App) -> impl IntoElement {
let theme = cx.theme();
let colors = theme.colors;
let ramps = theme.ramps;
let ButtonChrome {
background,
foreground,
hover,
pressed,
border,
hover_border,
pressed_border,
} = self.variant.chrome(cx);
let radius = if self.fully_rounded {
let theme = cx.theme();
theme.radius.full
} else {
let theme = cx.theme();
theme.radius.control
};
@@ -256,52 +323,7 @@ impl RenderOnce for Button {
let is_round_child = is_child_only && self.fully_rounded;
let icon_trailing = self.side == ButtonSide::Right;
let (background, foreground, hover, pressed) = match self.variant {
ButtonVariant::Primary => (
Some(ramps.primary.base),
colors.primary_foreground,
ramps.primary.hover,
ramps.primary.pressed,
),
ButtonVariant::Secondary => (
Some(colors.surface),
colors.foreground,
colors.muted,
colors.muted_hover,
),
ButtonVariant::Ghost => (
None,
colors.foreground,
colors.muted_hover,
ramps.secondary.pressed,
),
ButtonVariant::Destructive => (
Some(ramps.destructive.base),
colors.destructive_foreground,
ramps.destructive.hover,
ramps.destructive.pressed,
),
};
let (border, hover_border, pressed_border) = match self.variant {
ButtonVariant::Primary => (
ramps.primary.base,
ramps.primary.hover,
ramps.primary.pressed,
),
ButtonVariant::Secondary => (colors.border, colors.border, colors.border),
ButtonVariant::Ghost => (
transparent_black(),
transparent_black(),
transparent_black(),
),
ButtonVariant::Destructive => (
ramps.destructive.base,
ramps.destructive.hover,
ramps.destructive.pressed,
),
};
let ring = cx.theme().colors.ring;
h_flex()
.id(self.id.clone())
@@ -381,7 +403,7 @@ impl RenderOnce for Button {
.tab_stop(self.tab_stop)
.hover(move |style| style.bg(hover).border_color(hover_border))
.active(move |style| style.bg(pressed).border_color(pressed_border))
.focus_visible(|style| style.shadow(focus_ring(colors.ring)))
.focus_visible(|style| style.shadow(focus_ring(ring)))
.when_some(on_click, |button, on_click| {
button.on_click(move |event, window, cx| on_click(event, window, cx))
})
+47 -24
View File
@@ -84,6 +84,12 @@ impl SelectionPoint {
}
}
/// The source-derived part of one rendered line, cached between frames.
struct CodeLineLayout {
text: String,
roles: Vec<Role>,
}
/// Retained state for a code view.
///
/// Build one in a [`gpui::Entity`], render the entity, and call its setters
@@ -93,6 +99,8 @@ pub struct CodeViewState {
source: SharedString,
language: Language,
code: HighlightedCode,
/// Per-line layout cache, rebuilt whenever the source changes.
line_layouts: Vec<CodeLineLayout>,
handle: UniformListScrollHandle,
/// The hovered line, driving the active-line wash and number emphasis.
active_line: Option<usize>,
@@ -113,12 +121,14 @@ impl CodeViewState {
{
let source = source.into();
let code = highlight(&source, language);
let line_layouts = Self::layout(&code);
Self {
id: id.into(),
source,
language,
code,
line_layouts,
handle: UniformListScrollHandle::new(),
active_line: None,
selection: None,
@@ -137,6 +147,7 @@ impl CodeViewState {
let source = source.into();
self.code = highlight(&source, language);
self.line_layouts = Self::layout(&self.code);
self.source = source;
self.language = language;
self.selection = None;
@@ -145,17 +156,16 @@ impl CodeViewState {
cx.notify();
}
/// Replaces one line's text and re-highlights the file. `line_ix` past
/// the end clamps to the last line, and the replacement may span
/// multiple lines.
///
/// # Panics
///
/// Panics if the source is empty, which leaves no line to replace.
/// Replaces one line's text and re-highlights the file.
pub fn update_line<T>(&mut self, line_ix: usize, text: T, cx: &mut Context<Self>)
where
T: AsRef<str>,
{
// An empty source has no line to replace.
if self.source.is_empty() {
return;
}
let trailing_newline = self.source.ends_with('\n');
let mut lines: Vec<String> = self.source.lines().map(str::to_string).collect();
let line_ix = line_ix.min(lines.len().saturating_sub(1));
@@ -170,10 +180,37 @@ impl CodeViewState {
self.source = (lines.join("\n") + if trailing_newline { "\n" } else { "" }).into();
self.code = highlight(&self.source, self.language);
self.line_layouts = Self::layout(&self.code);
self.selection = None;
cx.notify();
}
/// The cached per-line text and roles for the highlighted source.
fn layout(code: &HighlightedCode) -> Vec<CodeLineLayout> {
code.lines
.iter()
.map(|line| {
let mut text = String::new();
for span in &line.spans {
text.push_str(&span.text);
}
let char_count = text.chars().count();
let mut roles = vec![Role::Text; char_count];
let mut offset = 0usize;
for span in &line.spans {
let chars = span.text.chars().count();
for slot in &mut roles[offset..offset + chars] {
*slot = span.role;
}
offset += chars;
}
CodeLineLayout { text, roles }
})
.collect()
}
/// The source text the view renders.
pub fn source(&self) -> &str {
&self.source
@@ -500,24 +537,10 @@ fn render_row(
line_height: Pixels,
cx: &App,
) -> gpui::AnyElement {
let line = code.code().lines.get(line_ix);
let mut text = String::new();
for span in line.map_or(&[][..], |line| line.spans.as_slice()) {
text.push_str(&span.text);
}
let layout = code.line_layouts.get(line_ix);
let text = layout.map_or("", |layout| layout.text.as_str());
let roles = layout.map_or(&[][..], |layout| layout.roles.as_slice());
let char_count = text.chars().count();
let mut roles = vec![Role::Text; char_count];
let mut offset = 0usize;
for span in line.map_or(&[][..], |line| line.spans.as_slice()) {
let chars = span.text.chars().count();
for slot in &mut roles[offset..offset + chars] {
*slot = span.role;
}
offset += chars;
}
let mut selected = vec![false; char_count];
+166 -173
View File
@@ -31,16 +31,18 @@ use std::rc::Rc;
use gpui::prelude::FluentBuilder;
use gpui::{
App, Bounds, Context, ElementId, Entity, InteractiveElement as _, IntoElement, KeyBinding,
MouseButton, MouseDownEvent, ParentElement as _, Pixels, Render, Role, ScrollHandle,
SharedString, StatefulInteractiveElement as _, StyleRefinement, Styled, Subscription, Task,
Window, actions, anchored, canvas, deferred, div, point, px,
MouseButton, MouseDownEvent, ParentElement as _, Pixels, Render, Role, SharedString,
StatefulInteractiveElement as _, StyleRefinement, Styled, Subscription, Task,
UniformListScrollHandle, Window, actions, anchored, canvas, deferred, div, point, px,
uniform_list,
};
use crate::components::common::{
ControlSizing, OVERLAY_LAYER, ResultLogErr as _, Sizable, StyledExt as _, h_flex, v_flex,
ControlSizing, OVERLAY_LAYER, ResultLogErr as _, Sizable, StyledExt as _, floating_panel,
h_flex, paint_highlighted_row, v_flex, wrapping_adjacent_selectable,
};
use crate::components::empty_state::EmptyState;
use crate::components::input::{Input, InputState, InputStateEvent};
use crate::components::scroll_area::ScrollArea;
use crate::icons::{IconRole, icon};
use crate::theme::{ActiveTheme as _, COMBOBOX_MIN_WIDTH, COMBOBOX_WIDTH, POPUP_MAX_HEIGHT, Size};
@@ -245,8 +247,10 @@ where
size: Size,
/// Width refinements from the builder, applied to the wrapper each render.
style: StyleRefinement,
/// Handler reports in flight; held so they die with the state.
tasks: Vec<Task<()>>,
/// The row list's scroll, kept across frames while the popup is open.
rows_scroll: UniformListScrollHandle,
/// The most recent handler report in flight; a newer report replaces it.
task: Option<Task<()>>,
/// Keeps the query-event subscription tied to the state's lifetime.
_subscription: Subscription,
}
@@ -304,7 +308,8 @@ where
unmatched: combobox.unmatched,
size: combobox.size,
style: combobox.style,
tasks: Vec::new(),
rows_scroll: UniformListScrollHandle::new(),
task: None,
_subscription: subscription,
}
}
@@ -385,7 +390,7 @@ where
cx.update(|window, cx| on_change(value, window, cx))
.log_err();
});
self.tasks.push(task);
self.task.replace(task);
}
cx.notify();
}
@@ -453,36 +458,22 @@ where
cx.update(|window, cx| on_create(text, window, cx))
.log_err();
});
self.tasks.push(task);
self.task.replace(task);
}
}
}
cx.notify();
}
/// Down and Up over the visible rows.
/// Down and Up over the visible rows, wrapping at the ends.
fn move_highlight(&mut self, delta: i32, cx: &mut Context<Self>) {
if self.visible.is_empty() {
return;
}
let count = self.visible.len();
let current = self.highlight.filter(|row| *row < count);
let next = match current {
Some(row) => match row.checked_add_signed(isize::try_from(delta).unwrap_or(0)) {
Some(next) if next < count => next,
Some(_) => 0,
None => count - 1,
},
None => {
if delta > 0 {
0
} else {
count - 1
}
}
};
self.highlight = Some(next);
let current = self.highlight.filter(|row| *row < self.visible.len());
let rows: Vec<usize> = (0..self.visible.len()).collect();
let next = wrapping_adjacent_selectable(&rows, current, delta > 0);
self.highlight = next;
cx.notify();
}
@@ -511,13 +502,12 @@ where
T: Clone + PartialEq + 'static,
{
fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
let (colors, radius, panel_border, shadows) = {
let (colors, radius, shadows) = {
let theme = cx.theme();
(
theme.colors,
theme.radius,
theme.colors.border,
theme.elevations.popover.shadows(),
)
};
@@ -620,96 +610,101 @@ where
.child(chevron),
)
.when(open, |wrapper| {
let rows: Vec<gpui::AnyElement> = self
.visible
.iter()
.enumerate()
.map(|(row, option_index)| {
let Some((value, label)) = self.options.get(*option_index) else {
return div().into_any_element();
};
let visible = self.visible.clone();
let options = self.options.clone();
let highlight = self.highlight;
let selected = self.selected.clone();
let size = self.size;
let list_state = state.clone();
let rows_id = id.clone();
let radius_sm = radius.sm;
let foreground = colors.foreground;
let highlighted = self.highlight == Some(row);
let checked = self.selected.as_ref() == Some(value);
let state = state.clone();
let row_index = row;
// Rows are `control_height`, so the row height follows the size.
let row_height = size.control_height_rems().to_pixels(window.rem_size());
let count = visible.len();
div()
.id(("option", *option_index))
.debug_selector({
let id = id.clone();
move || format!("{id}-option-{row}")
})
.role(Role::ListBoxOption)
.aria_label(label.clone())
.flex()
.items_center()
.gap_2()
.px_2()
.py_1()
.control_height(self.size)
.control_text(self.size)
.rounded(radius.sm)
.when(highlighted, |row| row.bg(colors.muted))
.when(!highlighted, |row| row.hover(|row| row.bg(colors.muted)))
.on_mouse_move({
let state = state.clone();
move |_, _window, cx| {
if state.read(cx).highlight != Some(row_index) {
state.update(cx, |state, cx| {
state.highlight = Some(row_index);
cx.notify();
});
}
}
})
.on_click({
let state = state.clone();
move |_, window, cx| {
state.update(cx, |state, cx| {
state.choose_row(row_index, window, cx)
});
}
})
.child(
div()
.flex_1()
.min_w_0()
.overflow_hidden()
.whitespace_nowrap()
.text_ellipsis()
.child(label.clone()),
)
.when(checked, |row| {
row.child(
icon(IconRole::Check)
.size(self.size.dense_icon_rems())
.color(colors.foreground),
)
})
.into_any_element()
})
.collect();
let list_height = (row_height * count as f32)
.max(row_height)
.min(POPUP_MAX_HEIGHT);
let rows: gpui::AnyElement = if rows.is_empty() {
div()
.px_2()
.py_1()
.control_caption_text(self.size)
.text_color(colors.muted_foreground)
.child("No matches")
.into_any_element()
let rows: gpui::AnyElement = if count == 0 {
EmptyState::compact("No matches", cx).into_any_element()
} else {
let scroll = window.use_keyed_state((id.clone(), "rows-scroll"), cx, |_, _| {
ScrollHandle::new()
});
uniform_list((rows_id.clone(), "rows"), count, move |range, _, cx| {
range
.map(|row| {
let Some(option_index) = visible.get(row).copied() else {
return div().into_any_element();
};
let Some((value, label)) = options.get(option_index) else {
return div().into_any_element();
};
ScrollArea::new((id.clone(), "rows"))
.handle(scroll.read(cx).clone())
.axes(crate::components::scroll_area::ScrollAxes::Vertical)
.max_h(POPUP_MAX_HEIGHT)
.children(rows)
.into_any_element()
let highlighted = highlight == Some(row);
let checked = selected.as_ref() == Some(value);
let state = list_state.clone();
let row_index = row;
div()
.id(("option", option_index))
.debug_selector({
let id = rows_id.clone();
move || format!("{id}-option-{row}")
})
.role(Role::ListBoxOption)
.aria_label(label.clone())
.flex()
.items_center()
.gap_2()
.px_2()
.py_1()
.h(row_height)
.control_text(size)
.rounded(radius_sm)
.map(|row| paint_highlighted_row(cx, row, highlighted, false))
.on_mouse_move({
let state = state.clone();
move |_, _window, cx| {
if state.read(cx).highlight != Some(row_index) {
state.update(cx, |state, cx| {
state.highlight = Some(row_index);
cx.notify();
});
}
}
})
.on_click({
let state = state.clone();
move |_, window, cx| {
state.update(cx, |state, cx| {
state.choose_row(row_index, window, cx)
});
}
})
.child(
div()
.flex_1()
.min_w_0()
.overflow_hidden()
.whitespace_nowrap()
.text_ellipsis()
.child(label.clone()),
)
.when(checked, |row| {
row.child(
icon(IconRole::Check)
.size(size.dense_icon_rems())
.color(foreground),
)
})
.into_any_element()
})
.collect()
})
.track_scroll(&self.rows_scroll)
.h(list_height)
.into_any_element()
};
let panel_bounds: Rc<RefCell<Option<Bounds<Pixels>>>> = Rc::new(RefCell::new(None));
@@ -719,64 +714,62 @@ where
.map(|bounds| bounds.size.width)
.unwrap_or(COMBOBOX_WIDTH);
let panel = v_flex()
.id((id.clone(), "panel"))
.debug_selector({
let id = id.clone();
move || format!("{id}-panel")
})
.w(popup_width)
.p_1()
.bg(colors.surface)
.text_color(colors.foreground)
.rounded(radius.overlay)
.border_1()
.border_color(panel_border)
.shadow(shadows)
.overflow_hidden()
.child(rows)
.child(
canvas(
{
let cell = panel_bounds.clone();
move |bounds, _window, _cx| *cell.borrow_mut() = Some(bounds)
},
{
let state = state.clone();
let panel_bounds = panel_bounds.clone();
let wrapper_bounds = wrapper_bounds.clone();
move |_, _, window, _cx| {
window.on_mouse_event({
let state = state.clone();
let panel_bounds = panel_bounds.clone();
let wrapper_bounds = wrapper_bounds.clone();
move |event: &MouseDownEvent, phase, _window, cx| {
if phase != gpui::DispatchPhase::Bubble {
return;
}
let on_panel =
panel_bounds.borrow().is_some_and(|bounds| {
bounds.contains(&event.position)
});
let on_wrapper =
wrapper_bounds.borrow().is_some_and(|bounds| {
bounds.contains(&event.position)
});
if on_panel || on_wrapper {
return;
}
state.update(cx, |state, cx| {
state.highlight = None;
cx.notify();
});
let panel = floating_panel(
cx,
radius.overlay,
v_flex()
.id((id.clone(), "panel"))
.debug_selector({
let id = id.clone();
move || format!("{id}-panel")
})
.w(popup_width)
.p_1()
.text_color(colors.foreground),
shadows,
)
.overflow_hidden()
.child(rows)
.child(
canvas(
{
let cell = panel_bounds.clone();
move |bounds, _window, _cx| *cell.borrow_mut() = Some(bounds)
},
{
let state = state.clone();
let panel_bounds = panel_bounds.clone();
let wrapper_bounds = wrapper_bounds.clone();
move |_, _, window, _cx| {
window.on_mouse_event({
let state = state.clone();
let panel_bounds = panel_bounds.clone();
let wrapper_bounds = wrapper_bounds.clone();
move |event: &MouseDownEvent, phase, _window, cx| {
if phase != gpui::DispatchPhase::Bubble {
return;
}
});
}
},
)
.absolute()
.inset_0(),
);
let on_panel = panel_bounds
.borrow()
.is_some_and(|bounds| bounds.contains(&event.position));
let on_wrapper = wrapper_bounds
.borrow()
.is_some_and(|bounds| bounds.contains(&event.position));
if on_panel || on_wrapper {
return;
}
state.update(cx, |state, cx| {
state.highlight = None;
cx.notify();
});
}
});
}
},
)
.absolute()
.inset_0(),
);
wrapper.child(
deferred(anchored().offset(point(px(0.), px(4.))).child(panel))
+164 -164
View File
@@ -29,14 +29,17 @@ use std::rc::Rc;
use gpui::prelude::FluentBuilder;
use gpui::{
AnyElement, App, Context, ElementId, Entity, InteractiveElement as _, IntoElement, KeyBinding,
MouseButton, ParentElement as _, Render, Role, ScrollHandle, SharedString,
StatefulInteractiveElement as _, StyleRefinement, Styled as _, Subscription, Window, actions,
canvas, deferred, div, relative, rems,
MouseButton, ParentElement as _, Render, Role, SharedString, StatefulInteractiveElement as _,
StyleRefinement, Styled as _, Subscription, UniformListScrollHandle, Window, actions, canvas,
deferred, div, relative, rems, uniform_list,
};
use crate::components::common::{DIALOG_LAYER, StyledExt as _, h_flex, v_flex};
use crate::components::common::{
DIALOG_LAYER, StyledExt as _, floating_panel, h_flex, paint_highlighted_row, v_flex,
wrapping_adjacent_selectable,
};
use crate::components::empty_state::EmptyState;
use crate::components::input::{Input, InputState, InputStateEvent};
use crate::components::scroll_area::{ScrollArea, ScrollAxes};
use crate::icons::Icon;
use crate::theme::{ActiveTheme as _, POPUP_MAX_HEIGHT};
@@ -211,6 +214,8 @@ pub struct CommandPaletteState {
/// The highlighted row, when the palette is open.
highlight: Option<usize>,
open: bool,
/// The row list's scroll, kept across frames while the palette is open.
rows_scroll: UniformListScrollHandle,
/// Keeps the query-event subscription tied to the state's lifetime.
_subscription: Subscription,
}
@@ -239,6 +244,7 @@ impl CommandPaletteState {
matches,
highlight: None,
open: false,
rows_scroll: UniformListScrollHandle::new(),
_subscription: subscription,
}
}
@@ -320,17 +326,9 @@ impl CommandPaletteState {
if self.matches.is_empty() {
return;
}
let count = self.matches.len();
let next = match self.highlight {
Some(row) => match row.checked_add_signed(isize::try_from(delta).unwrap_or(0)) {
Some(next) if next < count => next,
Some(_) => 0,
None => count - 1,
},
None if delta > 0 => 0,
None => count - 1,
};
self.highlight = Some(next);
let rows: Vec<usize> = (0..self.matches.len()).collect();
let next = wrapping_adjacent_selectable(&rows, self.highlight, delta > 0);
self.highlight = next;
cx.notify();
}
@@ -371,12 +369,11 @@ impl Render for CommandPaletteState {
return div().into_any_element();
}
let (colors, radius, panel_border, shadows, titlebar_height) = {
let (colors, radius, shadows, titlebar_height) = {
let theme = cx.theme();
(
theme.colors,
theme.radius,
theme.colors.border,
theme.elevations.dialog.shadows(),
theme.titlebar_height,
)
@@ -386,157 +383,160 @@ impl Render for CommandPaletteState {
let state = cx.entity();
let query_focus = self.query.read(cx).focus_handle();
let rows: Vec<AnyElement> = self
.matches
.iter()
.enumerate()
.map(|(row, command)| {
let highlighted = self.highlight == Some(row);
let state = state.clone();
let row_index = row;
h_flex()
.id((ElementId::from(command.id.clone()), "command"))
.debug_selector({
let id = id.clone();
move || format!("{id}-command-{row}")
})
.role(Role::ListBoxOption)
.aria_label(command.label.clone())
.gap_2()
.px_2()
.py_1()
.min_h_8()
.text_sm()
.line_height(relative(1.0))
.rounded(radius.sm)
.when(highlighted, |row| row.bg(colors.muted))
.when(!highlighted, |row| row.hover(|row| row.bg(colors.muted)))
.on_mouse_move({
let state = state.clone();
move |_, _window, cx| {
if state.read(cx).highlight != Some(row_index) {
state.update(cx, |state, cx| {
state.highlight = Some(row_index);
cx.notify();
});
}
}
})
.on_click({
let state = state.clone();
move |_, window, cx| {
state.update(cx, |state, cx| state.choose_row(row_index, window, cx));
}
})
.when_some(command.icon.clone(), |row, icon| {
row.child(icon.size(rems(1.0)).color(colors.foreground))
})
.child(
div()
.flex_1()
.min_w_0()
.overflow_hidden()
.whitespace_nowrap()
.text_ellipsis()
.child(command.label.clone()),
)
.when_some(command.hint.clone(), |row, hint| {
row.child(
div()
.flex_shrink_0()
.text_xs()
.text_color(colors.muted_foreground)
.child(hint),
)
})
.into_any_element()
})
.collect();
let rows: AnyElement = if rows.is_empty() {
div()
.px_2()
.py_1()
.text_xs()
.text_color(colors.muted_foreground)
.child("No matches")
.into_any_element()
let rows: AnyElement = if self.matches.is_empty() {
EmptyState::compact("No matches", cx).into_any_element()
} else {
let scroll =
window.use_keyed_state((id.clone(), "rows-scroll"), cx, |_, _| ScrollHandle::new());
let matches = self.matches.clone();
let highlight = self.highlight;
let state = state.clone();
let rows_id = id.clone();
let radius_sm = radius.sm;
let foreground = colors.foreground;
let muted_foreground = colors.muted_foreground;
ScrollArea::new((id.clone(), "rows"))
.handle(scroll.read(cx).clone())
.axes(ScrollAxes::Vertical)
.max_h(POPUP_MAX_HEIGHT)
.children(rows)
.into_any_element()
// Rows are `min_h_8`, so the uniform row height is two rems.
let row_height = rems(2.0).to_pixels(window.rem_size());
let count = matches.len();
let list_height = (row_height * count as f32).min(POPUP_MAX_HEIGHT);
uniform_list((rows_id.clone(), "rows"), count, move |range, _, cx| {
range
.map(|row| {
let Some(command) = matches.get(row) else {
return div().into_any_element();
};
let highlighted = highlight == Some(row);
let row_index = row;
h_flex()
.id((ElementId::from(command.id.clone()), "command"))
.debug_selector({
let id = rows_id.clone();
move || format!("{id}-command-{row}")
})
.role(Role::ListBoxOption)
.aria_label(command.label.clone())
.gap_2()
.px_2()
.py_1()
.min_h_8()
.text_sm()
.line_height(relative(1.0))
.rounded(radius_sm)
.map(|row| paint_highlighted_row(cx, row, highlighted, false))
.on_mouse_move({
let state = state.clone();
move |_, _window, cx| {
if state.read(cx).highlight != Some(row_index) {
state.update(cx, |state, cx| {
state.highlight = Some(row_index);
cx.notify();
});
}
}
})
.on_click({
let state = state.clone();
move |_, window, cx| {
state.update(cx, |state, cx| {
state.choose_row(row_index, window, cx)
});
}
})
.when_some(command.icon.clone(), |row, icon| {
row.child(icon.size(rems(1.0)).color(foreground))
})
.child(
div()
.flex_1()
.min_w_0()
.overflow_hidden()
.whitespace_nowrap()
.text_ellipsis()
.child(command.label.clone()),
)
.when_some(command.hint.clone(), |row, hint| {
row.child(
div()
.flex_shrink_0()
.text_xs()
.text_color(muted_foreground)
.child(hint),
)
})
.into_any_element()
})
.collect()
})
.track_scroll(&self.rows_scroll)
.h(list_height)
.into_any_element()
};
let panel = v_flex()
.id((id.clone(), "panel"))
.debug_selector({
let id = id.clone();
move || format!("{id}-panel")
})
.key_context(COMMAND_PALETTE_CONTEXT)
.role(Role::Dialog)
.aria_label(self.name.clone())
.w_full()
.max_w(relative(0.6))
.p_2()
.gap_2()
.bg(colors.surface)
.text_color(colors.foreground)
.rounded(radius.overlay)
.border_1()
.border_color(panel_border)
.shadow(shadows)
.overflow_hidden()
.refine_style(&self.style)
.on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation())
.on_action({
let state = state.clone();
move |_: &HighlightNext, _window, cx| {
state.update(cx, |state, cx| state.move_highlight(1, cx));
}
})
.on_action({
let state = state.clone();
move |_: &HighlightPrevious, _window, cx| {
state.update(cx, |state, cx| state.move_highlight(-1, cx));
}
})
.on_action({
let state = state.clone();
move |_: &Choose, window, cx| {
state.update(cx, |state, cx| state.choose(window, cx));
}
})
.on_action({
let state = state.clone();
move |_: &Dismiss, window, cx| {
state.update(cx, |state, cx| state.dismiss(window, cx));
}
})
.child(
Input::new((id.clone(), "query"), self.query.clone())
.placeholder(self.placeholder.clone()),
)
.child(rows)
.child(
canvas(|_, _, _| {}, {
let focus = query_focus.clone();
move |_, _, window, cx| {
if !focus.contains_focused(window, cx) {
window.focus(&focus, cx);
}
}
let panel = floating_panel(
cx,
radius.overlay,
v_flex()
.id((id.clone(), "panel"))
.debug_selector({
let id = id.clone();
move || format!("{id}-panel")
})
.absolute()
.inset_0(),
);
.key_context(COMMAND_PALETTE_CONTEXT)
.role(Role::Dialog)
.aria_label(self.name.clone())
.w_full()
.max_w(relative(0.6))
.p_2()
.gap_2()
.text_color(colors.foreground),
shadows,
)
.overflow_hidden()
.refine_style(&self.style)
.on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation())
.on_action({
let state = state.clone();
move |_: &HighlightNext, _window, cx| {
state.update(cx, |state, cx| state.move_highlight(1, cx));
}
})
.on_action({
let state = state.clone();
move |_: &HighlightPrevious, _window, cx| {
state.update(cx, |state, cx| state.move_highlight(-1, cx));
}
})
.on_action({
let state = state.clone();
move |_: &Choose, window, cx| {
state.update(cx, |state, cx| state.choose(window, cx));
}
})
.on_action({
let state = state.clone();
move |_: &Dismiss, window, cx| {
state.update(cx, |state, cx| state.dismiss(window, cx));
}
})
.child(
Input::new((id.clone(), "query"), self.query.clone())
.placeholder(self.placeholder.clone()),
)
.child(rows)
.child(
canvas(|_, _, _| {}, {
let focus = query_focus.clone();
move |_, _, window, cx| {
if !focus.contains_focused(window, cx) {
window.focus(&focus, cx);
}
}
})
.absolute()
.inset_0(),
);
let scrim = div()
.absolute()
+51
View File
@@ -129,6 +129,38 @@ pub fn focus_ring(color: Hsla) -> Vec<BoxShadow> {
]
}
/// The shared floating-panel stack.
#[must_use]
pub fn floating_panel<R>(cx: &App, radius: Pixels, panel: R, shadows: Vec<BoxShadow>) -> R
where
R: Styled + IntoElement,
{
let theme = cx.theme();
panel.map(|panel| {
panel
.bg(theme.colors.surface)
.rounded(radius)
.border_1()
.border_color(theme.colors.border)
.shadow(shadows)
})
}
/// The next selectable row in the direction.
pub fn wrapping_adjacent_selectable(
selectable: &[usize],
selected: Option<usize>,
forward: bool,
) -> Option<usize> {
if selectable.is_empty() {
return None;
}
adjacent_selectable(selectable, selected, forward)
.or_else(|| forward.then(|| selectable.first().copied()).flatten())
.or_else(|| (!forward).then(|| selectable.last().copied()).flatten())
}
/// The next selectable row in the direction, or `None` at the ends.
pub fn adjacent_selectable(
selectable: &[usize],
@@ -199,6 +231,25 @@ where
})
}
/// A row that highlights under the pointer, for lists driven by mouse move
/// instead of selection.
#[must_use]
pub fn paint_highlighted_row<R>(cx: &App, row: R, highlighted: bool, disabled: bool) -> R
where
R: IntoElement + Styled + StatefulInteractiveElement,
{
let theme = cx.theme();
row.map(|row| {
if disabled {
row
} else if highlighted {
row.bg(theme.colors.muted)
} else {
row.hover(|row| row.bg(theme.colors.muted))
}
})
}
/// A handler told to clean up after a dismissed surface.
pub type DismissHandler = std::rc::Rc<dyn Fn(&mut gpui::App)>;
+105 -107
View File
@@ -33,11 +33,11 @@ use gpui::{
};
use crate::components::button::{Button, ButtonVariant};
use crate::components::common::{DIALOG_LAYER, Sizable, StyledExt as _, v_flex};
use crate::components::common::h_flex;
use crate::components::common::{DIALOG_LAYER, Sizable, StyledExt as _, floating_panel, v_flex};
use crate::components::grain::grain;
use crate::components::scroll_area::ScrollArea;
use crate::icons::IconRole;
use crate::layout::h_flex;
use crate::theme::{ActiveTheme as _, DIALOG_MIN_WIDTH};
/// Requests the dialog's close: `false` closes.
@@ -255,13 +255,11 @@ impl RenderOnce for Dialog {
})
});
let (scrim_color, border, foreground, surface, radius, shadows, enter_duration) = {
let (scrim_color, foreground, radius, shadows, enter_duration) = {
let theme = cx.theme();
(
theme.colors.overlay,
theme.colors.border,
theme.colors.foreground,
theme.colors.surface,
theme.radius.overlay,
theme.elevations.dialog.shadows(),
theme.motion.overlay,
@@ -297,112 +295,112 @@ impl RenderOnce for Dialog {
.read(cx)
.clone();
let panel = v_flex()
.id("dialog-panel")
.track_focus(&focus)
.role(role)
.aria_label(label)
.when_some(self.min_width, |panel, width| panel.min_w(width))
.when(self.min_width.is_none(), |panel| {
panel.min_w(DIALOG_MIN_WIDTH)
})
.max_w(relative(0.9))
.when_some(height, |panel, height| panel.h(height))
.bg(surface)
.text_color(foreground)
.rounded(radius)
.border_1()
.border_color(border)
.shadow(shadows)
.overflow_hidden()
.on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation())
.on_key_down({
let on_change = on_change.clone();
move |event: &KeyDownEvent, window, cx| {
if event.keystroke.key == "escape"
&& !alert
&& close_on_escape
&& let Some(on_change) = &on_change
{
on_change(false, window, cx);
}
cx.stop_propagation();
let panel = floating_panel(
cx,
radius,
v_flex()
.id("dialog-panel")
.track_focus(&focus)
.role(role)
.aria_label(label)
.when_some(self.min_width, |panel, width| panel.min_w(width))
.when(self.min_width.is_none(), |panel| {
panel.min_w(DIALOG_MIN_WIDTH)
})
.max_w(relative(0.9))
.when_some(height, |panel, height| panel.h(height))
.text_color(foreground),
shadows,
)
.overflow_hidden()
.on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation())
.on_key_down({
let on_change = on_change.clone();
move |event: &KeyDownEvent, window, cx| {
if event.keystroke.key == "escape"
&& !alert
&& close_on_escape
&& let Some(on_change) = &on_change
{
on_change(false, window, cx);
}
cx.stop_propagation();
}
})
.when(self.title.is_some() || show_close, |panel| {
panel.child(
h_flex()
.h_12()
.px_2()
.gap_2()
.justify_between()
.when(show_close, |row| row.child(div().w_7()))
.when_some(self.title.clone(), |row, title| {
row.child(
div()
.flex_1()
.text_center()
.text_sm()
.font_semibold()
.child(title),
)
})
.when(show_close, |row| {
row.child(
Button::new("dialog-close")
.icon(IconRole::Close)
.variant(ButtonVariant::Ghost)
.small()
.debug_selector(|| "dialog-close".to_string())
.accessibility_label("Close")
.on_click({
let on_change = on_change.clone();
move |_, window, cx| {
if let Some(on_change) = &on_change {
on_change(false, window, cx);
}
}
}),
)
}),
)
})
.when_some(content, |panel, content| {
panel.map(|this| {
if height.is_some() {
this.child(
ScrollArea::new("dialog-content")
.handle(scroll)
.flex_1()
.min_h_0()
.child(div().p_2().child(content)),
)
} else {
this.child(div().p_2().child(content))
}
})
.when(self.title.is_some() || show_close, |panel| {
panel.child(
h_flex()
.h_12()
.px_2()
.gap_2()
.justify_between()
.when(show_close, |row| row.child(div().w_7()))
.when_some(self.title.clone(), |row, title| {
row.child(
div()
.flex_1()
.text_center()
.text_sm()
.font_semibold()
.child(title),
)
})
.when(show_close, |row| {
row.child(
Button::new("dialog-close")
.icon(IconRole::Close)
.variant(ButtonVariant::Ghost)
.small()
.debug_selector(|| "dialog-close".to_string())
.accessibility_label("Close")
.on_click({
let on_change = on_change.clone();
move |_, window, cx| {
if let Some(on_change) = &on_change {
on_change(false, window, cx);
}
}
}),
)
}),
)
})
.when_some(content, |panel, content| {
panel.map(|this| {
if height.is_some() {
this.child(
ScrollArea::new("dialog-content")
.handle(scroll)
.flex_1()
.min_h_0()
.child(div().p_2().child(content)),
)
} else {
this.child(div().p_2().child(content))
})
.when_some(actions, |panel, actions| {
panel.child(
h_flex()
.px_2()
.h_12()
.justify_end()
.gap_2()
.children(actions),
)
})
.child(
canvas(|_, _, _| {}, {
move |_, _, window, cx| {
if !focus.contains_focused(window, cx) {
window.focus(&focus, cx);
}
})
}
})
.when_some(actions, |panel, actions| {
panel.child(
h_flex()
.px_2()
.h_12()
.justify_end()
.gap_2()
.children(actions),
)
})
.child(
canvas(|_, _, _| {}, {
move |_, _, window, cx| {
if !focus.contains_focused(window, cx) {
window.focus(&focus, cx);
}
}
})
.absolute()
.inset_0(),
);
.absolute()
.inset_0(),
);
let scrim = div()
.absolute()
+9 -8
View File
@@ -33,14 +33,17 @@ use gpui::{
App, Context, ElementId, HighlightStyle, InteractiveElement as _, IntoElement,
ListHorizontalSizingBehavior, ParentElement as _, Pixels, Render, ScrollStrategy, SharedString,
StatefulInteractiveElement as _, Styled as _, TextStyle, UniformListScrollHandle, Window, div,
point, rems, uniform_list,
point, px, rems, uniform_list,
};
use similar::{Change, ChangeTag, TextDiff};
use crate::components::highlight::{HighlightedCode, Language, Line, Role, highlight};
use crate::components::scrollbar::{Scrollbar, ScrollbarHandle, ScrollbarVisibility};
use crate::components::utils::{gutter_cell, wash, wash_gutter, wash_strong};
use crate::theme::{ActiveTheme as _, BORDER_WIDTH, CODE_GUTTER_WIDTH, MONO_ADVANCE_RATIO};
use crate::theme::{ActiveTheme as _, CODE_GUTTER_WIDTH, CODE_LINE_HEIGHT, MONO_ADVANCE_RATIO};
/// The left change-indicator bar's width, four hairlines.
const CHANGE_BAR_WIDTH: Pixels = px(4.0);
/// What a diff row did to the file.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
@@ -525,7 +528,7 @@ fn render_row(
let mono_font = theme.mono_font;
let colors = theme.colors;
let ramps = theme.ramps;
let line_height = text_size * 1.5;
let line_height = text_size * CODE_LINE_HEIGHT;
let char_width = text_size * MONO_ADVANCE_RATIO;
let frame = div()
@@ -563,7 +566,7 @@ fn render_row(
row_element.child(
div()
.flex_none()
.border_l(BORDER_WIDTH * 4.0)
.border_l(CHANGE_BAR_WIDTH)
.border_color(gpui::transparent_black()),
)
},
@@ -689,9 +692,7 @@ fn render_row(
_ => wash_strong(change_color),
})
.when(options.indicators == DiffIndicators::Bars, |number| {
number
.border_l(BORDER_WIDTH * 4.0)
.border_color(change_color)
number.border_l(CHANGE_BAR_WIDTH).border_color(change_color)
}),
)
})
@@ -702,7 +703,7 @@ fn render_row(
div()
.h_full()
.flex_none()
.border_l(BORDER_WIDTH * 4.0)
.border_l(CHANGE_BAR_WIDTH)
.border_color(change_color),
)
},
+9 -34
View File
@@ -23,7 +23,7 @@ use gpui::{
div, relative,
};
use crate::components::button::ButtonVariant;
use crate::components::button::{ButtonChrome, ButtonVariant};
use crate::components::common::{
ControlSizing, Sizable, StyledExt as _, focus_handle, focus_ring, h_flex,
};
@@ -194,45 +194,20 @@ impl RenderOnce for DropdownMenu {
fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
let theme = cx.theme();
let colors = theme.colors;
let ramps = theme.ramps;
let radius = theme.radius.control;
let ring = colors.ring;
let (panel_chrome, enter_duration) = MenuChrome::read(cx);
let (background, foreground, hover, pressed) = match self.variant {
ButtonVariant::Primary => (
Some(ramps.primary.base),
colors.primary_foreground,
ramps.primary.hover,
ramps.primary.pressed,
),
ButtonVariant::Secondary => (
Some(colors.surface),
colors.foreground,
colors.muted,
colors.muted_hover,
),
ButtonVariant::Ghost => (
None,
colors.foreground,
colors.muted_hover,
ramps.secondary.pressed,
),
ButtonVariant::Destructive => (
Some(ramps.destructive.base),
colors.destructive_foreground,
ramps.destructive.hover,
ramps.destructive.pressed,
),
};
let border = match self.variant {
ButtonVariant::Primary => ramps.primary.base,
ButtonVariant::Secondary => colors.border,
ButtonVariant::Ghost => gpui::transparent_black(),
ButtonVariant::Destructive => ramps.destructive.base,
};
let ButtonChrome {
background,
foreground,
hover,
pressed,
border,
..
} = self.variant.chrome(cx);
let split = self.on_click.is_some();
let icon_only = self.icon.is_some() && self.label.is_none() && !split;
+14
View File
@@ -71,6 +71,20 @@ impl EmptyState {
self.action = Some(action.into_any_element());
self
}
/// A compact inline caption for popups with nothing to show.
#[must_use]
pub fn compact<L>(label: L, cx: &App) -> gpui::Div
where
L: Into<SharedString>,
{
div()
.px_2()
.py_1()
.text_xs()
.text_color(cx.theme().colors.muted_foreground)
.child(label.into())
}
}
impl gpui::Styled for EmptyState {
+95 -7
View File
@@ -23,6 +23,7 @@
use std::ops::Range;
use std::rc::Rc;
use std::sync::Arc;
use std::time::{Duration, Instant};
use gpui::prelude::FluentBuilder as _;
@@ -353,15 +354,17 @@ impl InputBindings {
}
/// The shaped text: one wrapped line per buffer line, plus the mask map when masking.
#[derive(Clone)]
struct ShapedText {
lines: Vec<ShapedLineEntry>,
mask_map: Option<Vec<(usize, usize)>>,
}
/// One shaped source line and its first byte's offset in the display text.
#[derive(Clone)]
struct ShapedLineEntry {
start: usize,
line: WrappedLine,
line: Arc<WrappedLine>,
}
/// The field's inner padding.
@@ -550,6 +553,18 @@ pub struct InputState {
caret_epoch_started: Instant,
/// The shaped line and element bounds, recorded during each paint.
layout: Option<InputLayout>,
/// The last shaped buffer, reused while no shaping input changed.
shaped_cache: std::cell::RefCell<Option<(ShapeCacheKey, ShapedText)>>,
}
/// Everything `shape_text` consumes, for cache reuse between frames.
#[derive(Clone, PartialEq)]
struct ShapeCacheKey {
text: String,
wrap_width: Option<Pixels>,
font_size: Pixels,
font: Font,
color: gpui::Hsla,
}
impl EventEmitter<InputStateEvent> for InputState {}
@@ -645,6 +660,7 @@ impl InputState {
caret_epoch: 0,
caret_epoch_started: Instant::now(),
layout: None,
shaped_cache: std::cell::RefCell::new(None),
}
}
@@ -1024,7 +1040,8 @@ impl InputState {
}
/// Shapes the masked or plain buffer, wrapping to `wrap_width` when set,
/// with the paint-time text style.
/// with the paint-time text style. Reuses the previous result while the
/// text, wrap width, and text style are unchanged.
fn shape_current_text(&self, wrap_width: Option<Pixels>, window: &Window) -> ShapedText {
let (text, mask_map) = if self.masked() {
masked_display(&self.text)
@@ -1042,6 +1059,21 @@ impl InputState {
};
let font_size = text_style.font_size.to_pixels(window.rem_size());
let key = ShapeCacheKey {
text: text.clone(),
wrap_width,
font_size,
font: font.clone(),
color: text_style.color,
};
if let Some((cached_key, shaped)) = self.shaped_cache.borrow().as_ref()
&& *cached_key == key
{
return shaped.clone();
}
let runs = [TextRun {
len: text.len(),
font,
@@ -1062,14 +1094,19 @@ impl InputState {
let mut start = 0;
for line in shaped {
let end = start + line.len();
lines.push(ShapedLineEntry { start, line });
lines.push(ShapedLineEntry {
start,
line: Arc::new(line),
});
start = end + '\n'.len_utf8();
}
}
Err(err) => log::warn!("shaping input text failed: {err}"),
}
ShapedText { lines, mask_map }
let shaped = ShapedText { lines, mask_map };
*self.shaped_cache.borrow_mut() = Some((key, shaped.clone()));
shaped
}
/// Stores the paint geometry for hit-testing and the IME conversions.
@@ -2616,12 +2653,63 @@ fn utf16_to_utf8_offset(text: &str, utf16_offset: usize) -> usize {
/// Converts a UTF-8 byte range to a UTF-16 range.
fn utf8_range_to_utf16(text: &str, range: Range<usize>) -> Range<usize> {
let start = text[..range.start].encode_utf16().count();
let end = start + text[range.start..range.end].encode_utf16().count();
// IME can supply reversed or off-boundary offsets; normalize both
// endpoints so the slicing below cannot panic.
let start = floor_to_char_boundary(text, range.start.min(range.end));
let end = floor_to_char_boundary(text, range.start.max(range.end));
let start = text[..start].encode_utf16().count();
let end = start + text[start..end].encode_utf16().count();
start..end
}
/// Converts a UTF-16 range to a UTF-8 byte range.
fn utf16_range_to_utf8(text: &str, range: Range<usize>) -> Range<usize> {
utf16_to_utf8_offset(text, range.start)..utf16_to_utf8_offset(text, range.end)
// IME can supply a reversed range; order the endpoints so the result
// slices cleanly.
let (start, end) = (range.start.min(range.end), range.start.max(range.end));
utf16_to_utf8_offset(text, start)..utf16_to_utf8_offset(text, end)
}
/// Floors `index` to the nearest char boundary at or below it.
fn floor_to_char_boundary(text: &str, index: usize) -> usize {
if index >= text.len() {
return text.len();
}
let mut index = index;
while !text.is_char_boundary(index) {
index -= 1;
}
index
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
#[allow(clippy::reversed_empty_ranges)] // The fixture is intentionally reversed.
fn utf16_range_to_utf8_orders_reversed_endpoints() {
// "héllo": h 0, é 1, l 2, l 3, o 4 in UTF-16 units.
let text = "héllo";
assert_eq!(utf16_range_to_utf8(text, 4..2), 3..5);
assert_eq!(utf16_range_to_utf8(text, 2..4), 3..5);
}
#[test]
#[allow(clippy::reversed_empty_ranges)] // The fixture is intentionally reversed.
fn utf8_range_to_utf16_floors_off_boundary_offsets() {
let text = "héllo";
// Byte 2 sits inside `é`; a reversed, off-boundary range must not panic.
let range = utf8_range_to_utf16(text, 4..2);
assert!(range.start <= range.end);
assert_eq!(range, 1..3);
}
#[test]
fn char_boundary_floor_clamps_to_len() {
// "héllo" is six bytes.
assert_eq!(floor_to_char_boundary("héllo", 7), 6);
assert_eq!(floor_to_char_boundary("héllo", 2), 1);
assert_eq!(floor_to_char_boundary("héllo", 0), 0);
}
}
+1 -1
View File
@@ -1478,7 +1478,7 @@ fn block_frame(quote: bool, top: Rems, bottom: Rems, id: &ElementId, cx: &App) -
.w_full()
.flex()
.flex_col()
.font_family(".SystemUIFont")
.font_family(theme.ui_font())
.text_xs()
.line_height(relative(BODY_LINE_HEIGHT))
.text_color(theme.colors.foreground)
+114 -123
View File
@@ -25,14 +25,17 @@ use std::rc::Rc;
use gpui::prelude::FluentBuilder;
use gpui::{
Animation, AnimationExt as _, AnyElement, App, Bounds, BoxShadow, DefiniteLength,
DispatchPhase, ElementId, Entity, FocusHandle, InteractiveElement as _, IntoElement,
KeyDownEvent, MouseButton, MouseDownEvent, ParentElement as _, Pixels, Point, RenderOnce, Role,
ScrollHandle, SharedString, StatefulInteractiveElement as _, StyleRefinement, Styled as _,
Window, anchored, canvas, deferred, div, ease_out_quint, point, px, relative, rems,
Animation, AnimationExt as _, AnyElement, App, Bounds, DefiniteLength, DispatchPhase,
ElementId, Entity, FocusHandle, InteractiveElement as _, IntoElement, KeyDownEvent,
MouseButton, MouseDownEvent, ParentElement as _, Pixels, Point, RenderOnce, Role, ScrollHandle,
SharedString, StatefulInteractiveElement as _, StyleRefinement, Styled as _, Window, anchored,
canvas, deferred, div, ease_out_quint, point, px, relative, rems,
};
use crate::components::common::{OVERLAY_LAYER, StyledExt as _, focus_handle, v_flex};
use crate::components::common::{
OVERLAY_LAYER, StyledExt as _, floating_panel, focus_handle, v_flex,
wrapping_adjacent_selectable,
};
use crate::components::scroll_area::{ScrollArea, ScrollAxes};
use crate::icons::{Icon, IconRole, icon as icon_glyph};
use crate::theme::{ActiveTheme as _, MENU_MIN_WIDTH, POPUP_MAX_HEIGHT};
@@ -190,7 +193,6 @@ impl FluentBuilder for MenuItem {}
/// Menu chrome styles.
#[derive(Clone)]
pub(crate) struct MenuChrome {
surface: gpui::Hsla,
border: gpui::Hsla,
foreground: gpui::Hsla,
muted_foreground: gpui::Hsla,
@@ -199,9 +201,7 @@ pub(crate) struct MenuChrome {
primary_foreground: gpui::Hsla,
destructive: gpui::Hsla,
destructive_foreground: gpui::Hsla,
radius_overlay: Pixels,
radius_sm: Pixels,
shadow: Vec<BoxShadow>,
}
/// A floating menu of [`MenuItem`] rows anchored below its trigger.
@@ -227,7 +227,6 @@ impl MenuChrome {
let theme = cx.theme();
(
Self {
surface: theme.colors.surface,
border: theme.colors.border,
foreground: theme.colors.foreground,
muted_foreground: theme.colors.muted_foreground,
@@ -236,9 +235,7 @@ impl MenuChrome {
primary_foreground: theme.colors.primary_foreground,
destructive: theme.ramps.destructive.base,
destructive_foreground: theme.colors.destructive_foreground,
radius_overlay: theme.radius.overlay,
radius_sm: theme.radius.sm,
shadow: theme.elevations.popover.shadows(),
},
theme.motion.overlay,
)
@@ -688,110 +685,110 @@ fn menu_panel(
})
.collect();
v_flex()
.id("menu-panel")
.debug_selector(move || format!("{}-panel", params.debug_prefix))
.occlude()
.track_focus(focus)
.role(Role::Menu)
.aria_label(params.label)
.when_some(params.min_width, |panel, width| panel.min_w(width))
.when(params.min_width.is_none(), |panel| {
panel.min_w(MENU_MIN_WIDTH)
})
.p_1()
.bg(params.chrome.surface)
.text_color(params.chrome.foreground)
.rounded(params.chrome.radius_overlay)
.border_1()
.border_color(params.chrome.border)
.shadow(params.chrome.shadow.clone())
.overflow_hidden()
.on_mouse_down_out({
let on_dismiss = params.on_dismiss.clone();
let dismiss_bounds = params.dismiss_bounds.clone();
let flyout_stack = flyout_stack.clone();
floating_panel(
cx,
cx.theme().radius.overlay,
v_flex()
.id("menu-panel")
.debug_selector(move || format!("{}-panel", params.debug_prefix))
.occlude()
.track_focus(focus)
.role(Role::Menu)
.aria_label(params.label)
.when_some(params.min_width, |panel, width| panel.min_w(width))
.when(params.min_width.is_none(), |panel| {
panel.min_w(MENU_MIN_WIDTH)
})
.p_1()
.text_color(params.chrome.foreground),
cx.theme().elevations.popover.shadows(),
)
.overflow_hidden()
.on_mouse_down_out({
let on_dismiss = params.on_dismiss.clone();
let dismiss_bounds = params.dismiss_bounds.clone();
let flyout_stack = flyout_stack.clone();
move |event, window, cx| {
if dismiss_bounds
.borrow()
move |event, window, cx| {
if dismiss_bounds
.borrow()
.is_some_and(|bounds| bounds.contains(&event.position))
{
return;
}
// Clicks inside any open flyout belong to that flyout.
if flyout_stack.borrow().iter().any(|cell| {
cell.borrow()
.is_some_and(|bounds| bounds.contains(&event.position))
{
return;
}
// Clicks inside any open flyout belong to that flyout.
if flyout_stack.borrow().iter().any(|cell| {
cell.borrow()
.is_some_and(|bounds| bounds.contains(&event.position))
}) {
return;
}
if let Some(on_dismiss) = &on_dismiss {
on_dismiss(false, window, cx);
}
}) {
return;
}
})
.on_key_down({
let items = params.items.clone();
let selection = selection.clone();
let set_flyout = set_flyout.clone();
let on_dismiss = params.on_dismiss.clone();
let on_activate = params.on_activate.clone();
let left_dismisses = params.is_flyout;
move |event: &KeyDownEvent, window, cx| {
handle_menu_key(
event,
MenuKeyEnv {
items: &items,
selection: &selection,
set_flyout: &set_flyout,
on_dismiss: &on_dismiss,
on_activate: &on_activate,
left_dismisses,
},
window,
cx,
);
if let Some(on_dismiss) = &on_dismiss {
on_dismiss(false, window, cx);
}
})
.child(
ScrollArea::new("menu-items")
.handle(scroll.read(cx).clone())
.axes(ScrollAxes::Vertical)
.max_h(POPUP_MAX_HEIGHT)
.child(v_flex().gap_0p5().children(rows)),
)
.child(
canvas(
{
let bounds_sink = params.bounds_sink.cloned();
move |bounds, _window, _cx| {
if let Some(cell) = &bounds_sink {
*cell.borrow_mut() = Some(bounds);
}
}
}
})
.on_key_down({
let items = params.items.clone();
let selection = selection.clone();
let set_flyout = set_flyout.clone();
let on_dismiss = params.on_dismiss.clone();
let on_activate = params.on_activate.clone();
let left_dismisses = params.is_flyout;
move |event: &KeyDownEvent, window, cx| {
handle_menu_key(
event,
MenuKeyEnv {
items: &items,
selection: &selection,
set_flyout: &set_flyout,
on_dismiss: &on_dismiss,
on_activate: &on_activate,
left_dismisses,
},
{
let focus = focus.clone();
let flyout_open = flyout_open.clone();
move |_, _, window, cx| {
if flyout_open.read(cx).is_none() && !focus.contains_focused(window, cx) {
window.focus(&focus, cx);
}
window,
cx,
);
}
})
.child(
ScrollArea::new("menu-items")
.handle(scroll.read(cx).clone())
.axes(ScrollAxes::Vertical)
.max_h(POPUP_MAX_HEIGHT)
.child(v_flex().gap_0p5().children(rows)),
)
.child(
canvas(
{
let bounds_sink = params.bounds_sink.cloned();
move |bounds, _window, _cx| {
if let Some(cell) = &bounds_sink {
*cell.borrow_mut() = Some(bounds);
}
},
)
.absolute()
.inset_0(),
}
},
{
let focus = focus.clone();
let flyout_open = flyout_open.clone();
move |_, _, window, cx| {
if flyout_open.read(cx).is_none() && !focus.contains_focused(window, cx) {
window.focus(&focus, cx);
}
}
},
)
.with_animation(
"menu-enter",
Animation::new(params.enter_duration).with_easing(ease_out_quint()),
|panel, delta| panel.opacity(delta),
)
.into_any_element()
.absolute()
.inset_0(),
)
.with_animation(
"menu-enter",
Animation::new(params.enter_duration).with_easing(ease_out_quint()),
|panel, delta| panel.opacity(delta),
)
.into_any_element()
}
/// Renders one menu row.
@@ -1053,8 +1050,6 @@ fn handle_menu_key(event: &KeyDownEvent, env: MenuKeyEnv, window: &mut Window, c
.collect();
let current = *env.selection.read(cx);
let position =
current.and_then(|current| selectable.iter().position(|index| *index == current));
match event.keystroke.key.as_str() {
"down" | "up" | "home" | "end" => {
@@ -1062,19 +1057,15 @@ fn handle_menu_key(event: &KeyDownEvent, env: MenuKeyEnv, window: &mut Window, c
return;
}
let next = match event.keystroke.key.as_str() {
"down" => match position {
Some(pos) => (pos + 1).min(selectable.len() - 1),
None => 0,
},
"up" => match position {
Some(pos) => pos.saturating_sub(1),
None => selectable.len() - 1,
},
"home" => 0,
_ => selectable.len() - 1,
"down" => wrapping_adjacent_selectable(&selectable, current, true),
"up" => wrapping_adjacent_selectable(&selectable, current, false),
"home" => selectable.first().copied(),
_ => selectable.last().copied(),
};
env.selection
.update(cx, |selection, _| *selection = Some(selectable[next]));
if let Some(next) = next {
env.selection
.update(cx, |selection, _| *selection = Some(next));
}
}
"right" => {
let opens = current
+49 -50
View File
@@ -31,7 +31,7 @@ use gpui::{
px,
};
use crate::components::common::{OVERLAY_LAYER, StyledExt as _, v_flex};
use crate::components::common::{OVERLAY_LAYER, StyledExt as _, floating_panel, v_flex};
use crate::theme::{ActiveTheme as _, POPOVER_MIN_WIDTH};
/// Reports the next open state of a [`Popover`]: `true` to open, `false` to close.
@@ -124,14 +124,13 @@ impl gpui::Styled for Popover {
impl RenderOnce for Popover {
fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
let (colors, radius, shadows, enter_duration, panel_border) = {
let (colors, radius, shadows, enter_duration) = {
let theme = cx.theme();
(
theme.colors,
theme.radius,
theme.elevations.popover.shadows(),
theme.motion.overlay,
theme.colors.border,
)
};
@@ -197,60 +196,60 @@ impl RenderOnce for Popover {
let focus = crate::components::common::focus_handle(&self.id, window, cx);
let content = self.content.map(|content| content(window, cx));
let panel = v_flex()
.id("popover-panel")
.debug_selector(|| "popover-panel".to_string())
.occlude()
.track_focus(&focus)
.role(Role::Dialog)
.aria_label(label)
.min_w(POPOVER_MIN_WIDTH)
.bg(colors.surface)
.text_color(colors.surface_foreground)
.rounded(radius.overlay)
.border_1()
.border_color(panel_border)
.shadow(shadows)
.overflow_hidden()
.on_mouse_down_out({
let on_change = on_change.clone();
let trigger_bounds = trigger_bounds.clone();
move |event, window, cx| {
if trigger_bounds
.borrow()
.is_some_and(|bounds| bounds.contains(&event.position))
{
return;
}
let panel = floating_panel(
cx,
radius.overlay,
v_flex()
.id("popover-panel")
.debug_selector(|| "popover-panel".to_string())
.occlude()
.track_focus(&focus)
.role(Role::Dialog)
.aria_label(label)
.min_w(POPOVER_MIN_WIDTH)
.text_color(colors.surface_foreground),
shadows,
)
.overflow_hidden()
.on_mouse_down_out({
let on_change = on_change.clone();
let trigger_bounds = trigger_bounds.clone();
move |event, window, cx| {
if trigger_bounds
.borrow()
.is_some_and(|bounds| bounds.contains(&event.position))
{
return;
}
if let Some(on_change) = &on_change {
on_change(false, window, cx);
}
}
})
.on_key_down({
let on_change = on_change.clone();
move |event: &KeyDownEvent, window, cx| {
if event.keystroke.key == "escape" {
if let Some(on_change) = &on_change {
on_change(false, window, cx);
}
cx.stop_propagation();
}
})
.on_key_down({
let on_change = on_change.clone();
move |event: &KeyDownEvent, window, cx| {
if event.keystroke.key == "escape" {
if let Some(on_change) = &on_change {
on_change(false, window, cx);
}
cx.stop_propagation();
}
})
.when_some(content, |panel, content| panel.child(content))
.child(
canvas(|_, _, _| {}, {
let focus = focus;
move |_, _, window, cx| {
if !focus.contains_focused(window, cx) {
window.focus(&focus, cx);
}
}
})
.when_some(content, |panel, content| panel.child(content))
.child(
canvas(|_, _, _| {}, {
let focus = focus;
move |_, _, window, cx| {
if !focus.contains_focused(window, cx) {
window.focus(&focus, cx);
}
}
})
.absolute()
.inset_0(),
);
.absolute()
.inset_0(),
);
wrapper.child(
deferred(anchored().offset(point(Pixels::ZERO, px(4.))).child(
+1 -1
View File
@@ -228,7 +228,7 @@ where
};
h_flex()
.id((ElementId::from("segment"), segment.label.clone()))
.id(("segment", index))
.gap_2()
.justify_center()
.cursor_pointer()
+1 -2
View File
@@ -221,7 +221,6 @@ where
let open_for_items = open.clone();
let rest_border = if is_open { ring } else { border };
let hover_border = rest_border;
let selected_index = self.selected.as_ref().and_then(|value| {
self.options
@@ -282,7 +281,7 @@ where
} else {
muted_foreground
})
.hover(|style| style.bg(muted).border_color(hover_border))
.hover(|style| style.bg(muted).border_color(rest_border))
.child(trigger_text.clone())
.child(
icon(IconRole::ChevronDown)
+75 -47
View File
@@ -30,7 +30,7 @@ use std::time::Duration;
use gpui::prelude::FluentBuilder as _;
use gpui::{
App, Context, ElementId, Entity, EventEmitter, InteractiveElement as _, IntoElement,
App, Context, Div, ElementId, Entity, EventEmitter, Hsla, InteractiveElement as _, IntoElement,
ParentElement as _, RenderOnce, Role, SharedString, StatefulInteractiveElement as _,
StyleRefinement, Styled, Subscription, Task, WeakEntity, Window, div, relative, rems,
};
@@ -719,6 +719,32 @@ impl Sizable for SpeechButton {
}
}
/// The waveform bar elements for a dictation control's level history.
fn waveform_bars<'a>(
levels: &'a [f32],
size: Size,
cx: &'a App,
bar_color: impl Fn(f32) -> Hsla + 'a,
) -> impl IntoIterator<Item = Div> + 'a {
let theme = cx.theme();
let bar_height = move |level: f32| {
if theme.accessibility.reduce_motion {
STILL_HEIGHT
} else {
DOT_HEIGHT + (1.0 - DOT_HEIGHT) * level
}
};
levels.iter().map(move |level| {
div()
.flex_none()
.w(rems(size.dense_icon_rems().0 / 4.0))
.h(relative(bar_height(*level)))
.rounded(theme.radius.full)
.bg(bar_color(*level))
})
}
impl RenderOnce for SpeechButton {
fn render(self, _window: &mut Window, cx: &mut App) -> impl IntoElement {
let unsupported = !self.speech.read(cx).has_recognizer();
@@ -726,7 +752,7 @@ impl RenderOnce for SpeechButton {
return div().into_any_element();
}
let (status, unavailable, capturing, reduce_motion, bars) = {
let (status, unavailable, capturing, bars) = {
let state = self.speech.read(cx);
let status = state.status();
let levels = state.levels();
@@ -735,7 +761,6 @@ impl RenderOnce for SpeechButton {
status,
unsupported || !state.is_available(cx),
status.is_capturing(),
cx.theme().accessibility.reduce_motion,
levels[tail_start..].to_vec(),
)
};
@@ -762,6 +787,7 @@ impl RenderOnce for SpeechButton {
};
let foreground = colors.foreground;
let bar_color = |_| theme.ramps.primary.base;
h_flex()
.id(id.clone())
@@ -785,26 +811,12 @@ impl RenderOnce for SpeechButton {
.color(foreground)
.into_any_element()
} else if capturing {
let bar_height = |level: f32| {
if reduce_motion {
STILL_HEIGHT
} else {
DOT_HEIGHT + (1.0 - DOT_HEIGHT) * level
}
};
h_flex()
.id(("speech-bars", self.speech.entity_id()))
.h(size.icon_rems())
.items_end()
.gap_0p5()
.children(bars.iter().map(|level| {
div()
.flex_none()
.w(rems(size.dense_icon_rems().0 / 4.0))
.h(relative(bar_height(*level)))
.rounded(theme.radius.full)
.bg(theme.ramps.primary.base)
}))
.children(waveform_bars(&bars, size, cx, bar_color))
.group_hover(group.clone(), |style| style.invisible())
.into_any_element()
} else {
@@ -877,22 +889,19 @@ impl RenderOnce for SpeechWaveform {
if !self.speech.read(cx).status().is_capturing() {
return div().into_any_element();
}
let (levels, reduce_motion) = {
let levels = {
let state = self.speech.read(cx);
(
state.levels().to_vec(),
cx.theme().accessibility.reduce_motion,
)
state.levels().to_vec()
};
let theme = cx.theme();
let colors = theme.colors;
let size = self.size;
let bar_height = |level: f32| {
if reduce_motion {
STILL_HEIGHT
let bar_color = |level: f32| {
if level <= 0.0 {
colors.muted_foreground
} else {
DOT_HEIGHT + (1.0 - DOT_HEIGHT) * level
theme.ramps.primary.base
}
};
@@ -904,18 +913,7 @@ impl RenderOnce for SpeechWaveform {
.h(size.icon_rems())
.w(SPEECH_WAVEFORM_WIDTH)
.overflow_hidden()
.children(levels.iter().map(|level| {
div()
.flex_none()
.w(rems(size.dense_icon_rems().0 / 4.0))
.h(relative(bar_height(*level)))
.rounded(theme.radius.full)
.bg(if *level <= 0.0 {
colors.muted_foreground
} else {
theme.ramps.primary.base
})
}))
.children(waveform_bars(&levels, size, cx, bar_color))
.refine_style(&self.style)
.into_any_element()
}
@@ -948,11 +946,19 @@ impl AudioInput for Microphone {
};
let device_channels = stream_config.channels.max(1) as usize;
let (sender, receiver) = flume::unbounded::<Vec<i16>>();
let (sender, receiver) = flume::unbounded::<Result<Vec<i16>, String>>();
let converter = Arc::new(Mutex::new(Resampler::new(
config.sample_rate() as f32 / format.sample_rate().max(1) as f32,
)));
let error_handler = |error| log::warn!("microphone stream error: {error}");
let error_handler = {
let sender = sender.clone();
move |error: cpal::Error| {
log::warn!("microphone stream error: {error}");
if sender.send(Err(error.to_string())).is_err() {
log::debug!("speech session closed before its stream error arrived");
}
}
};
let stream = match config.sample_format() {
cpal::SampleFormat::F32 => device.build_input_stream(
@@ -1002,8 +1008,24 @@ impl AudioInput for Microphone {
stream.play().map_err(SpeechError::input)?;
let task = cx.spawn(async move |cx| {
while let Ok(samples) = receiver.recv_async().await {
cx.update(|cx| sink.push(samples, cx));
while let Ok(message) = receiver.recv_async().await {
match message {
Ok(samples) => cx.update(|cx| sink.push(samples, cx)),
Err(message) => {
let error = SpeechError::input(message);
let state = sink.state.clone();
let generation = sink.generation;
cx.update(move |cx| {
if let Some(state) = state.upgrade() {
state.update(cx, |state, cx| {
state.apply(generation, cx, |state, cx| {
state.report_error(error, cx)
})
});
}
});
}
}
}
});
@@ -1021,14 +1043,20 @@ impl Microphone {
device_channels: usize,
format: AudioFormat,
converter: Arc<Mutex<Resampler>>,
sender: flume::Sender<Vec<i16>>,
sender: flume::Sender<Result<Vec<i16>, String>>,
) -> impl FnMut(&[T], &cpal::InputCallbackInfo) + Send + 'static
where
T: Copy + 'static,
{
move |data: &[T], _: &cpal::InputCallbackInfo| {
let Ok(mut converter) = converter.lock() else {
return;
// A panic while resampling poisons the lock; the phase is
// approximate anyway, so recover and keep the stream alive.
let mut converter = match converter.lock() {
Ok(converter) => converter,
Err(poisoned) => {
log::warn!("microphone resampler lock was poisoned; recovering");
poisoned.into_inner()
}
};
let mut mono = Vec::with_capacity(data.len() / device_channels + 1);
@@ -1052,7 +1080,7 @@ impl Microphone {
}
}
if sender.send(samples).is_err() {
if sender.send(Ok(samples)).is_err() {
log::debug!("speech session closed before its audio arrived");
}
}
+86 -100
View File
@@ -21,11 +21,11 @@ use std::rc::Rc;
use gpui::prelude::FluentBuilder;
use gpui::{
AnyElement, App, AppContext as _, Bounds, ClickEvent, Context, Div, ElementId, Global,
AnyElement, App, AppContext as _, Bounds, ClickEvent, Context, Div, ElementId, Global, Hsla,
InteractiveElement as _, IntoElement, KeyDownEvent, MouseButton, ParentElement as _, Pixels,
Point, Render, RenderOnce, Role, SharedString, Stateful, StatefulInteractiveElement as _,
StyleRefinement, Styled as _, TextOverflow, Window, canvas, div, linear_color_stop,
linear_gradient, px, rems,
StyleRefinement, Styled, TextOverflow, Window, canvas, div, linear_color_stop, linear_gradient,
px, rems,
};
use crate::components::button::{Button, ButtonVariant};
@@ -100,6 +100,13 @@ impl TabsMeasurements {
.tabs
.insert(tab, measure);
}
/// Drops measurements for tabs no longer rendered in the strip.
fn retain_tabs(&mut self, key: &MeasureKey, rendered: &[String]) {
if let Some(strip) = self.strips.get_mut(key) {
strip.tabs.retain(|tab, _| rendered.contains(tab));
}
}
}
/// Everything a tab needs to draw and interact, shared across a strip's slots.
@@ -190,6 +197,64 @@ fn group_key(tabs_id: &ElementId, kind: &SharedString) -> ElementId {
SharedString::from(format!("{tabs_id}-tabs-group-{kind}")).into()
}
/// The label color shared by strip tabs and group chips.
fn tab_label_color(variant: TabsVariant, active: bool, disabled: bool, cx: &App) -> Hsla {
let theme = cx.theme();
if disabled {
return theme.colors.muted_foreground;
}
match variant {
TabsVariant::Underline => {
if active {
theme.ramps.primary.base
} else {
theme.colors.foreground
}
}
TabsVariant::Pill => theme.colors.foreground,
TabsVariant::Titlebar => {
if active {
theme.colors.foreground
} else {
theme.colors.muted_foreground
}
}
}
}
/// The variant treatment shared by strip tabs and group chips.
fn apply_tab_chrome<R>(row: R, variant: TabsVariant, active: bool, cx: &App) -> R
where
R: Styled + IntoElement,
{
let theme = cx.theme();
match variant {
TabsVariant::Underline => row
.px_2()
.py_1()
.rounded_tl(theme.radius.sm)
.rounded_tr(theme.radius.sm)
.border_b_2()
.border_color(gpui::transparent_black())
.when(active, |row| row.border_color(theme.ramps.primary.base)),
TabsVariant::Pill | TabsVariant::Titlebar => row
.h_8()
.px_2()
.pr_0p5()
.rounded(match variant {
TabsVariant::Titlebar => theme.radius.full,
_ => theme.radius.control,
})
.when(variant == TabsVariant::Titlebar, |row| {
row.bg(theme.colors.muted)
})
.when(active, |row| {
row.bg(theme.colors.background)
.shadow(theme.elevations.control.shadows())
}),
}
}
/// The payload dragged when reordering a tab.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct TabDrag {
@@ -619,23 +684,7 @@ impl Tabs {
let theme = cx.theme();
let group_key = group_key(&tabs_id, &kind);
let label_color = match ctx.variant {
TabsVariant::Underline => {
if active {
theme.ramps.primary.base
} else {
theme.colors.foreground
}
}
TabsVariant::Pill => theme.colors.foreground,
TabsVariant::Titlebar => {
if active {
theme.colors.foreground
} else {
theme.colors.muted_foreground
}
}
};
let label_color = tab_label_color(ctx.variant, active, false, cx);
let chip = div()
.id((group_key.clone(), "group-tab"))
@@ -660,31 +709,7 @@ impl Tabs {
})
})
})
.map(|chip| match ctx.variant {
TabsVariant::Underline => chip
.px_2()
.py_1()
.rounded_tl(theme.radius.sm)
.rounded_tr(theme.radius.sm)
.border_b_2()
.border_color(gpui::transparent_black())
.when(active, |chip| chip.border_color(theme.ramps.primary.base)),
TabsVariant::Pill | TabsVariant::Titlebar => chip
.h_8()
.px_2()
.pr_0p5()
.rounded(match ctx.variant {
TabsVariant::Titlebar => theme.radius.full,
_ => theme.radius.control,
})
.when(ctx.variant == TabsVariant::Titlebar, |chip| {
chip.bg(theme.colors.muted)
})
.when(active, |chip| {
chip.bg(theme.colors.background)
.shadow(theme.elevations.control.shadows())
}),
})
.map(|chip| apply_tab_chrome(chip, ctx.variant, active, cx))
.child(SharedString::from(format!("{kind} ({count})")))
.when(ctx.variant.is_capsule(), |chip| {
chip.child(div().flex_none().w_4())
@@ -826,6 +851,17 @@ impl RenderOnce for Tabs {
.unwrap_or(items.len());
let overflow_items = items.split_off(inline_count);
// The strip records geometry per inline tab each frame; drop entries
// for tabs no longer rendered inline.
if cx.try_global::<TabsMeasurements>().is_some() {
let rendered: Vec<String> = items
.iter()
.map(|item| item.measure_key(&self.id))
.collect();
cx.global_mut::<TabsMeasurements>()
.retain_tabs(&measure_key, &rendered);
}
let measure_frame = self.overflow_popover.then(|| MeasureFrame {
key: measure_key.clone(),
root_bounds: Rc::new(RefCell::new(None)),
@@ -1030,31 +1066,7 @@ impl Tab {
let theme = cx.theme();
let label_color = match ctx.variant {
TabsVariant::Underline => {
if self.disabled {
theme.colors.muted_foreground
} else if active {
theme.ramps.primary.base
} else {
theme.colors.foreground
}
}
TabsVariant::Pill => {
if self.disabled {
theme.colors.muted_foreground
} else {
theme.colors.foreground
}
}
TabsVariant::Titlebar => {
if self.disabled || !active {
theme.colors.muted_foreground
} else {
theme.colors.foreground
}
}
};
let label_color = tab_label_color(ctx.variant, active, self.disabled, cx);
let titlebar = ctx.variant == TabsVariant::Titlebar;
let group = SharedString::from(format!("{}-tab-{}", ctx.id, self.key));
@@ -1143,36 +1155,10 @@ impl Tab {
})
})
})
.map(|strip_tab| match ctx.variant {
TabsVariant::Underline => strip_tab
.px_2()
.py_1()
.rounded_tl(theme.radius.sm)
.rounded_tr(theme.radius.sm)
.border_b_2()
.border_color(gpui::transparent_black())
.when(active, |strip_tab| {
strip_tab.border_color(theme.ramps.primary.base)
}),
TabsVariant::Pill | TabsVariant::Titlebar => strip_tab
.h_8()
.px_2()
.pr_0p5()
.rounded(match ctx.variant {
TabsVariant::Titlebar => theme.radius.full,
_ => theme.radius.control,
})
.when(titlebar, |strip_tab| {
strip_tab
.min_w(TAB_MIN_WIDTH)
.max_w(TAB_MAX_WIDTH)
.bg(theme.colors.muted)
})
.when(active, |strip_tab| {
strip_tab
.bg(theme.colors.background)
.shadow(theme.elevations.control.shadows())
}),
.map(|strip_tab| {
apply_tab_chrome(strip_tab, ctx.variant, active, cx).when(titlebar, |strip_tab| {
strip_tab.min_w(TAB_MIN_WIDTH).max_w(TAB_MAX_WIDTH)
})
})
.when_some(self.lead.take(), |strip_tab, lead| strip_tab.child(lead))
.child(label)
+62 -63
View File
@@ -25,7 +25,7 @@ use gpui::{
use crate::components::button::{Button, ButtonVariant};
use crate::components::common::{
DismissHandler, ResultLogErr as _, Sizable as _, StyledExt as _, TOAST_LAYER,
DismissHandler, ResultLogErr as _, Sizable as _, StyledExt as _, TOAST_LAYER, floating_panel,
};
use crate::icons::{Icon, IconRole};
use crate::theme::{ActiveTheme as _, TOAST_MAX_WIDTH};
@@ -132,8 +132,10 @@ pub struct Toasts {
current: Option<ToastEntry>,
exiting: Option<ToastEntry>,
next_id: usize,
/// Pending dismiss and fade timers; held so they die with the store.
tasks: Vec<Task<()>>,
/// The pending auto-dismiss timer, replaced on each push.
dismiss_task: Option<Task<()>>,
/// The pending fade timer, replaced on each exit.
fade_task: Option<Task<()>>,
}
impl Toasts {
@@ -157,7 +159,7 @@ impl Toasts {
this.update(cx, |toasts, cx| toasts.dismiss(id, cx))
.log_err();
});
self.tasks.push(task);
self.dismiss_task.replace(task);
}
id
@@ -210,7 +212,7 @@ impl Toasts {
this.update(cx, |toasts, cx| toasts.finish_exit(cx))
.log_err();
});
self.tasks.push(task);
self.fade_task.replace(task);
}
fn finish_exit(&mut self, cx: &mut Context<Self>) {
@@ -286,80 +288,77 @@ impl ToastEntry {
/// The rendered pill for this toast.
fn pill(&self, toasts: &Entity<Toasts>, cx: &App) -> gpui::Stateful<gpui::Div> {
let theme = cx.theme();
let surface = theme.colors.surface;
let border = theme.colors.border;
let foreground = theme.colors.foreground;
let radius = theme.radius.full;
let shadows = theme.elevations.popover.shadows();
let toast = &self.toast;
let toasts = toasts.clone();
let id = self.id;
div()
.id(("toast", id))
.debug_selector(|| "toast-pill".to_string())
.role(Role::Alert)
.aria_label(toast.message.clone())
.max_w(TOAST_MAX_WIDTH)
.flex()
.items_center()
.gap_2()
.py_1p5()
.px_3()
.bg(surface)
.border_1()
.border_color(border)
.rounded(radius)
.shadow(shadows.clone())
.refine_style(&toast.style)
.when_some(toast.icon.clone(), |pill, icon| {
pill.child(
div()
.flex_none()
.flex()
.items_center()
.child(icon.size(rems(1.0)).color(foreground)),
)
})
.child(
floating_panel(
cx,
radius,
div()
.id(("toast", id))
.debug_selector(|| "toast-pill".to_string())
.role(Role::Alert)
.aria_label(toast.message.clone())
.max_w(TOAST_MAX_WIDTH)
.flex()
.items_center()
.gap_2()
.py_1p5()
.px_3(),
theme.elevations.popover.shadows(),
)
.refine_style(&toast.style)
.when_some(toast.icon.clone(), |pill, icon| {
pill.child(
div()
.flex_1()
.min_w(px(0.))
.truncate()
.text_sm()
.text_color(foreground)
.child(toast.message.clone()),
.flex_none()
.flex()
.items_center()
.child(icon.size(rems(1.0)).color(foreground)),
)
.when_some(toast.action.clone(), |pill, action| {
let toasts = toasts.clone();
pill.child(
div().flex_none().child(
Button::new(("toast-action", id))
.label(action.label.clone())
.variant(ButtonVariant::Primary)
.small()
.on_click(move |_, _window, cx| {
(action.handler)(cx);
toasts.update(cx, |toasts, cx| {
toasts.dismiss(id, cx);
});
}),
),
)
})
.child(
})
.child(
div()
.flex_1()
.min_w(px(0.))
.truncate()
.text_sm()
.text_color(foreground)
.child(toast.message.clone()),
)
.when_some(toast.action.clone(), |pill, action| {
let toasts = toasts.clone();
pill.child(
div().flex_none().child(
Button::new(("toast-close", id))
.icon(IconRole::Close)
.variant(ButtonVariant::Ghost)
Button::new(("toast-action", id))
.label(action.label.clone())
.variant(ButtonVariant::Primary)
.small()
.accessibility_label("Dismiss")
.on_click(move |_, _window, cx| {
(action.handler)(cx);
toasts.update(cx, |toasts, cx| {
toasts.dismiss(id, cx);
});
}),
),
)
})
.child(
div().flex_none().child(
Button::new(("toast-close", id))
.icon(IconRole::Close)
.variant(ButtonVariant::Ghost)
.small()
.accessibility_label("Dismiss")
.on_click(move |_, _window, cx| {
toasts.update(cx, |toasts, cx| {
toasts.dismiss(id, cx);
});
}),
),
)
}
}
+23 -24
View File
@@ -19,8 +19,10 @@ use gpui::{
StatefulInteractiveElement as _, Styled as _, Window, canvas, div, point, px,
};
use crate::components::common::{anchor_bounds, record_anchor_bounds};
use crate::theme::{ActiveTheme as _, BORDER_WIDTH, TOOLTIP_MAX_WIDTH, TOOLTIP_OFFSET};
use crate::components::common::{anchor_bounds, floating_panel, record_anchor_bounds};
use crate::theme::{
ActiveTheme as _, BORDER_WIDTH, TOOLTIP_ANCHOR_GAP, TOOLTIP_MAX_WIDTH, TOOLTIP_OFFSET,
};
const PANEL_BOUNDS_ID: &str = "tooltip-panel-bounds";
@@ -80,29 +82,26 @@ impl Render for Tooltip {
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.
let theme = cx.theme();
let surface = theme.colors.surface;
let surface_foreground = theme.colors.surface_foreground;
let radius_sm = theme.radius.sm;
let shadows = theme.elevations.popover.shadows();
let border = theme.colors.border;
let build_panel = || {
div()
.id("tooltip-panel")
.role(Role::Tooltip)
.debug_selector(|| "tooltip-panel".to_string())
.px_2()
.py_1()
.max_w(TOOLTIP_MAX_WIDTH)
.bg(surface)
.border_1()
.border_color(border)
.rounded(radius_sm)
.shadow(shadows.clone())
.text_sm()
.text_color(surface_foreground)
.child(self.text.clone())
floating_panel(
cx,
radius_sm,
div()
.id("tooltip-panel")
.role(Role::Tooltip)
.debug_selector(|| "tooltip-panel".to_string())
.px_2()
.py_1()
.max_w(TOOLTIP_MAX_WIDTH)
.text_sm()
.text_color(surface_foreground)
.child(self.text.clone()),
shadows.clone(),
)
};
let (wrapper, panel) = match self.anchor {
@@ -118,16 +117,16 @@ impl Render for Tooltip {
.map(|bounds| bounds.size.height)
.unwrap_or_else(|| window.line_height() + px(8.) + BORDER_WIDTH * 2.0);
let below = viewport_height - px(4.) - parent.bottom();
let above = parent.top() - px(4.);
let below = viewport_height - TOOLTIP_ANCHOR_GAP - parent.bottom();
let above = parent.top() - TOOLTIP_ANCHOR_GAP;
let hang_below = below >= height || below >= above;
let panel = build_panel()
.ml(parent.left() - origin.x)
.mt(if hang_below {
parent.bottom() + px(4.) - origin.y
parent.bottom() + TOOLTIP_ANCHOR_GAP - origin.y
} else {
parent.top() - px(4.) - height - origin.y
parent.top() - TOOLTIP_ANCHOR_GAP - height - origin.y
})
.child(
canvas(
+6 -3
View File
@@ -37,6 +37,9 @@ type DisclosureHandler = Rc<dyn Fn(usize, &mut Window, &mut App)>;
/// The visible row builder, run during render.
type ItemsFn = Box<dyn Fn(&mut Window, &mut App) -> Vec<TreeItem>>;
/// The deepest indent the tree paints, bounding misbuilt item trees.
const TREE_MAX_DEPTH: usize = 16;
/// One row of a [`Tree`].
#[derive(Clone)]
#[must_use]
@@ -362,7 +365,7 @@ impl TreeItem {
let label_color = selectable_label_color(cx, selected, self.disabled);
let disabled = self.disabled;
let depth = u32::try_from(self.depth).unwrap_or(u32::MAX) as f32;
let depth = self.depth.min(TREE_MAX_DEPTH) as f32;
let indent = rems(0.75 * if self.depth == 0 { 0.5 } else { depth + 1.0 });
div()
@@ -402,8 +405,8 @@ impl TreeItem {
}
})
})
.children((0..self.depth).map(|level| {
let step = u32::try_from(level).unwrap_or(u32::MAX) as f32;
.children((0..self.depth.min(TREE_MAX_DEPTH)).map(|level| {
let step = level as f32;
div()
.absolute()
.left(rems(0.75 * (step + 0.5)))
+4 -47
View File
@@ -1,11 +1,9 @@
//! Application window layout: a titlebar over a panel row.
//!
//! The shared flex and focus helpers live in [`crate::components::common`];
//! they are re-exported here for the `ui::layout::…` paths.
use gpui::{
App, BoxShadow, Div, ElementId, FocusHandle, Hsla, Refineable as _, StyleRefinement, Styled,
Window, div, px,
};
use crate::theme::{FOCUS_RING_ALPHA, FOCUS_RING_SPREAD};
pub use crate::components::common::{StyledExt, focus_handle, focus_ring, h_flex, v_flex};
pub mod panel;
pub mod resizable;
@@ -15,44 +13,3 @@ pub mod titlebar;
pub mod window_controls;
mod window_frame;
/// A row whose children center on the cross axis.
#[must_use]
pub fn h_flex() -> Div {
div().flex().flex_row().items_center()
}
/// A column whose children stack on the main axis.
#[must_use]
pub fn v_flex() -> Div {
div().flex().flex_col()
}
/// Extensions over [`Styled`], shared by the layout views.
pub trait StyledExt: Styled + Sized {
#[must_use]
fn refine_style(mut self, style: &StyleRefinement) -> Self {
self.style().refine(style);
self
}
}
impl<E: Styled> StyledExt for E {}
/// Returns a focus handle for the given element ID.
pub fn focus_handle(id: &ElementId, window: &mut Window, cx: &mut App) -> FocusHandle {
window
.with_element_namespace(id.clone(), |window| {
window.use_keyed_state("focus-handle", cx, |_, cx| cx.focus_handle())
})
.read(cx)
.clone()
}
/// Returns a focus ring shadow with the given color at half ink.
pub fn focus_ring(color: Hsla) -> Vec<BoxShadow> {
vec![
BoxShadow::new(px(0.), px(0.), color.alpha(FOCUS_RING_ALPHA))
.spread_radius(FOCUS_RING_SPREAD),
]
}
+3 -3
View File
@@ -7,13 +7,13 @@ use std::sync::Arc;
use gpui::{
AnyElement, AnyView, App, Axis, Div, ElementId, Entity, IntoElement, ParentElement as _,
Render, RenderOnce, SharedString, StyleRefinement, Styled as _, Window, div, px,
Render, RenderOnce, SharedString, StyleRefinement, Styled as _, Window, div,
};
use crate::components::tabs::Tab;
use crate::layout::StyledExt as _;
use crate::layout::resizable::{Resizable, ResizableState};
use crate::theme::ActiveTheme as _;
use crate::theme::{ActiveTheme as _, RESIZE_HANDLE_WIDTH};
/// A user-defined panel the row can show.
#[allow(unused_variables)]
@@ -186,7 +186,7 @@ impl gpui::Styled for PanelRow {
impl RenderOnce for PanelRow {
fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
let id = self.id.clone();
let gutter = px(8.);
let gutter = RESIZE_HANDLE_WIDTH;
let main = island(
div()
+32 -1
View File
@@ -86,7 +86,9 @@ impl ResizableState {
.filter(|(j, _)| *j != ix)
.fold(px(0.), |sum, (_, min)| sum + *min);
let ceiling = extent - floors;
size = size.min(ceiling);
// When the window is smaller than the other panes' floors, keep
// the floor rather than shrinking this pane below it.
size = size.min(ceiling.max(floor));
}
// Earlier panes hold the equal split they already render at,
@@ -107,6 +109,8 @@ impl ResizableState {
/// Sets pane `ix`'s width, backfilling earlier panes.
pub fn set_pane_width(&mut self, ix: usize, width: Pixels, cx: &mut Context<Self>) {
// Persisted layouts can carry negative sizes.
let width = width.max(PANE_MIN_SIZE);
while self.sizes.len() <= ix {
self.sizes.push(width);
}
@@ -310,3 +314,30 @@ impl RenderOnce for Resizable {
})
}
}
#[cfg(test)]
mod tests {
use super::*;
use gpui::TestAppContext;
#[gpui::test]
fn resize_never_stores_sub_floor_size(cx: &mut TestAppContext) {
let state = cx.new(|_| ResizableState::default());
state.update(cx, |state, cx| {
// The measured extent is smaller than the other pane's floor.
state.set_measured(px(100.), cx);
state.resize(0, px(500.), &[px(48.), px(150.)], cx);
assert_eq!(state.sizes[0], px(48.));
});
}
#[gpui::test]
fn set_pane_width_clamps_negative_values(cx: &mut TestAppContext) {
let state = cx.new(|_| ResizableState::default());
state.update(cx, |state, cx| {
// Persisted layouts can carry negative sizes.
state.set_pane_width(0, px(-20.), cx);
assert_eq!(state.pane_size(0, 1), PANE_MIN_SIZE);
});
}
}
+3 -2
View File
@@ -14,7 +14,8 @@ use gpui::{
use crate::layout::{StyledExt as _, focus_handle, focus_ring};
use crate::theme::{
ActiveTheme as _, BORDER_WIDTH, DISABLED_OPACITY, HAIRLINE_WIDTH, RESIZE_KEYBOARD_STEP,
ActiveTheme as _, BORDER_WIDTH, DISABLED_OPACITY, HAIRLINE_WIDTH, RESIZE_HANDLE_WIDTH,
RESIZE_KEYBOARD_STEP,
};
/// How far one keyboard arrow step moves the seam.
@@ -111,7 +112,7 @@ impl RenderOnce for ResizeHandle {
fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
let theme = cx.theme();
let ring = theme.colors.ring;
let thickness = px(8.);
let thickness = RESIZE_HANDLE_WIDTH;
let label = self
.accessibility_label
+2 -2
View File
@@ -274,7 +274,7 @@ fn caption_button(
.text_color(theme.colors.foreground)
})
})
.child(icon(role).size(rems(0.75)))
.child(icon(role).size(crate::theme::OVERLAY_ICON_SIZE))
.into_any_element()
}
@@ -309,6 +309,6 @@ where
action(window, cx);
})
})
.child(icon(role).size(rems(0.75)))
.child(icon(role).size(crate::theme::OVERLAY_ICON_SIZE))
.into_any_element()
}
+7
View File
@@ -164,3 +164,10 @@ impl MaterialTokens {
}
}
}
/// Windows paints its caption close-button hover red in every theme.
pub const WINDOWS_CLOSE_HOVER: Hsla = hsla(0.986043, 0.863406, 0.488235, 1.0);
/// The close-button hover dimmed while pressed.
pub const WINDOWS_CLOSE_PRESSED: Hsla = hsla(0.986043, 0.863406, 0.488235, 0.8);
/// The close glyph's color over the red hover.
pub const WINDOWS_CLOSE_FOREGROUND: Hsla = gpui::white();
+23
View File
@@ -187,6 +187,10 @@ impl ThemeDefinition {
/// Parses `#rgb` or `#rrggbb` into an opaque color.
pub(crate) fn parse_hex(value: &str) -> Option<Hsla> {
let digits = value.strip_prefix('#')?;
// Lengths are byte lengths; non-ASCII input would panic the slicing below.
if !digits.is_ascii() {
return None;
}
let expand = |channels: [f32; 3]| Some(expand_rgb([channels[0], channels[1], channels[2]]));
match digits.len() {
@@ -219,3 +223,22 @@ pub(crate) fn parse_hex(value: &str) -> Option<Hsla> {
fn expand_rgb([r, g, b]: [f32; 3]) -> Hsla {
Hsla::from(Rgba { r, g, b, a: 1.0 })
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn parse_hex_rejects_non_ascii_digits() {
assert_eq!(parse_hex("#éa"), None);
assert_eq!(parse_hex("#éaabbcc"), None);
}
#[test]
fn parse_hex_resolves_three_and_six_digits() {
assert!(parse_hex("#abc").is_some());
assert!(parse_hex("#aabbcc").is_some());
assert_eq!(parse_hex("abc"), None);
assert_eq!(parse_hex("#ab"), None);
}
}
+17 -8
View File
@@ -16,10 +16,14 @@ mod system;
use std::time::Duration;
pub use colors::{ColorTokens, MaterialTokens};
pub use colors::{
ColorTokens, MaterialTokens, WINDOWS_CLOSE_FOREGROUND, WINDOWS_CLOSE_HOVER,
WINDOWS_CLOSE_PRESSED,
};
pub use definition::ThemeDefinition;
use gpui::{
App, Global, Hsla, Pixels, SpringConfig, WindowAppearance, WindowBackgroundAppearance, hsla, px,
App, Global, Hsla, Pixels, Rems, SpringConfig, WindowAppearance, WindowBackgroundAppearance,
px, rems,
};
pub use ramps::{AccentShades, Oklch};
pub use resolve::{Ramps, ResolvedTheme};
@@ -27,6 +31,12 @@ pub use system::{AccessibilityPreferences, SourceKind, SystemTheme};
/// The hairline width of the control border every button and field paints.
pub const BORDER_WIDTH: Pixels = px(1.0);
/// The side of glyphs inside titlebar overlay controls.
pub const OVERLAY_ICON_SIZE: Rems = rems(0.75);
/// The draggable width of a resize seam and its panel-row gutter.
pub const RESIZE_HANDLE_WIDTH: Pixels = px(8.0);
/// The gap between an anchored tooltip and its anchor.
pub const TOOLTIP_ANCHOR_GAP: Pixels = px(4.0);
/// The widest a titlebar tab grows before its label fades.
pub const TAB_MAX_WIDTH: Pixels = px(240.0);
/// The narrowest a titlebar tab shrinks, keeping short labels clear of the fade.
@@ -75,12 +85,6 @@ pub const WINDOW_RESIZE_INSET: Pixels = px(4.0);
pub const TRAFFIC_LIGHT_PAD: Pixels = px(88.0);
/// The width of a Windows caption button.
pub const WINDOWS_CAPTION_WIDTH: Pixels = px(36.0);
/// Windows paints its caption close-button hover red in every theme.
pub const WINDOWS_CLOSE_HOVER: Hsla = hsla(0.986043, 0.863406, 0.488235, 1.0);
/// The close-button hover dimmed while pressed.
pub const WINDOWS_CLOSE_PRESSED: Hsla = hsla(0.986043, 0.863406, 0.488235, 0.8);
/// The close glyph's color over the red hover.
pub const WINDOWS_CLOSE_FOREGROUND: Hsla = gpui::white();
/// The width a sidebar opens at.
pub const SIDEBAR_DEFAULT_WIDTH: Pixels = px(240.0);
/// The narrowest a sidebar may be dragged.
@@ -210,6 +214,11 @@ impl Theme {
cx.global::<Self>()
}
/// The system UI family, for chrome surfaces.
pub fn ui_font(&self) -> &'static str {
".SystemUIFont"
}
fn from_resolved(resolved: ResolvedTheme) -> Self {
Self {
variant: resolved.variant,
+83 -7
View File
@@ -10,7 +10,8 @@ use objc2_app_kit::{
};
use objc2_foundation::{
NSDictionary, NSDistributedNotificationCenter, NSKeyValueObservingOptions, NSNotification,
NSNotificationName, NSObjectNSKeyValueObserverRegistration, NSString, NSUserDefaults,
NSNotificationCenter, NSNotificationName, NSObjectNSKeyValueObserverRegistration, NSString,
NSUserDefaults,
};
use super::signal::ReapplySignal;
@@ -46,14 +47,37 @@ define_class!(
impl ThemeObserver {
fn new(reapply: async_channel::Sender<()>) -> Retained<Self> {
let this = Self::alloc().set_ivars(reapply);
// SAFETY: `this` is freshly allocated with ivars set and not yet
// initialized, which is exactly the receiver `init` requires.
unsafe { msg_send![super(this), init] }
}
}
/// One watcher registration, kept so [`Drop`] can undo it.
enum Watcher {
/// A distributed notification, registered by name.
Distributed {
center: Retained<NSDistributedNotificationCenter>,
name: Retained<NSNotificationName>,
},
/// A defaults key path observed via KVO, which does not retain observers.
Defaults {
defaults: Retained<NSUserDefaults>,
key: Retained<NSString>,
},
/// A workspace notification, registered by name.
Workspace {
center: Retained<NSNotificationCenter>,
name: &'static NSNotificationName,
},
}
#[derive(Default)]
pub(crate) struct MacosSource {
/// The notification centers track, but do not retain, the observer.
_observer: Option<Retained<ThemeObserver>>,
/// The observer, retained until `Drop` has removed every registration.
observer: Option<Retained<ThemeObserver>>,
/// Registrations to undo, in the order they were installed.
watchers: Vec<Watcher>,
/// Keeps the reapply loop alive.
_signal: Option<ReapplySignal>,
}
@@ -96,6 +120,7 @@ impl ThemeSource for MacosSource {
fn install_watchers(&mut self, async_cx: gpui::AsyncApp) {
let signal = ReapplySignal::install(&async_cx);
let observer = ThemeObserver::new(signal.sender());
let mut watchers = Vec::new();
let center = NSDistributedNotificationCenter::defaultCenter();
for name in [
@@ -103,7 +128,9 @@ impl ThemeSource for MacosSource {
"AppleInterfaceThemeChangedNotification",
] {
let name = NSNotificationName::from_str(name);
// SAFETY: the observer is retained past every delivery.
// SAFETY: the center tracks this exact registration until `Drop`
// removes it, and the observer is retained by `MacosSource` until
// after that removal.
unsafe {
center.addObserver_selector_name_object(
&observer,
@@ -112,6 +139,10 @@ impl ThemeSource for MacosSource {
None,
);
}
watchers.push(Watcher::Distributed {
center: center.clone(),
name,
});
}
let defaults = NSUserDefaults::standardUserDefaults();
@@ -121,7 +152,9 @@ impl ThemeSource for MacosSource {
"AppleInterfaceStyle",
] {
let key = NSString::from_str(key);
// SAFETY: as above
// SAFETY: KVO does not retain the observer, so the registration is
// only valid while `MacosSource` keeps the observer alive and
// `Drop` unregisters the key path before releasing it.
unsafe {
defaults.addObserver_forKeyPath_options_context(
&observer,
@@ -130,13 +163,18 @@ impl ThemeSource for MacosSource {
core::ptr::null_mut(),
);
}
watchers.push(Watcher::Defaults {
defaults: defaults.clone(),
key,
});
}
let workspace_center = NSWorkspace::sharedWorkspace().notificationCenter();
let accessibility_name =
unsafe { NSWorkspaceAccessibilityDisplayOptionsDidChangeNotification };
// SAFETY: as above.
// SAFETY: the workspace center retains the observer for the
// registration's lifetime, and `Drop` removes the registration.
unsafe {
workspace_center.addObserver_selector_name_object(
&observer,
@@ -145,8 +183,13 @@ impl ThemeSource for MacosSource {
None,
);
}
watchers.push(Watcher::Workspace {
center: workspace_center,
name: accessibility_name,
});
self._observer = Some(observer);
self.observer = Some(observer);
self.watchers = watchers;
self._signal = Some(signal);
}
@@ -154,3 +197,36 @@ impl ThemeSource for MacosSource {
SourceKind::Macos.label()
}
}
impl Drop for MacosSource {
fn drop(&mut self) {
let Some(observer) = self.observer.take() else {
return;
};
for watcher in self.watchers.drain(..) {
match watcher {
Watcher::Distributed { center, name } => {
// SAFETY: the observer is registered with this center
// under this name and object.
unsafe {
center.removeObserver_name_object(&observer, Some(&name), None);
}
}
Watcher::Defaults { defaults, key } => {
// SAFETY: the observer is registered for this key path
// with no context.
unsafe {
defaults.removeObserver_forKeyPath(&observer, &key);
}
}
Watcher::Workspace { center, name } => {
// SAFETY: the observer is registered with this center
// under this name and object.
unsafe {
center.removeObserver_name_object(&observer, Some(name), None);
}
}
}
}
}
}
+62
View File
@@ -62,6 +62,68 @@ fn strip_window(
cx
}
struct CloseHarness {
closed: Rc<RefCell<Vec<usize>>>,
}
impl Render for CloseHarness {
fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
let closed = self.closed.clone();
div().size_full().child(
Tabs::new("strip")
.variant(TabsVariant::Pill)
.tabs(move |_, _| {
vec![
Tab::new("a", "Alpha").closeable(true),
Tab::new("b", "Beta").closeable(true),
]
})
.on_close(move |index, _, _| closed.borrow_mut().push(index)),
)
}
}
#[gpui::test]
fn a_pinned_tab_draws_inline_and_selects_itself(cx: &mut TestAppContext) {
let changed = Rc::new(RefCell::new(Vec::new()));
let mut cx = strip_window(cx, changed.clone(), Rc::new(RefCell::new(Vec::new())), true);
let delta = cx
.debug_bounds("strip-tab-Delta")
.expect("a pinned tab draws itself");
cx.simulate_click(delta.center(), Modifiers::none());
cx.run_until_parked();
assert_eq!(
changed.borrow().as_slice(),
&[3],
"clicking the pinned tab reports its index"
);
}
#[gpui::test]
fn a_closeable_tab_reports_its_close(cx: &mut TestAppContext) {
cx.update(Theme::init);
let closed = Rc::new(RefCell::new(Vec::new()));
let window = cx.open_window(size(px(800.), px(600.)), |_, _| CloseHarness {
closed: closed.clone(),
});
let mut cx = VisualTestContext::from_window(window.into(), cx);
cx.run_until_parked();
let close = cx
.debug_bounds("strip-close-Alpha")
.expect("a closeable tab draws its close control");
cx.simulate_click(close.center(), Modifiers::none());
cx.run_until_parked();
assert_eq!(
closed.borrow().as_slice(),
&[0],
"the close control reports the tab's index"
);
}
#[gpui::test]
fn same_kind_tabs_collapse_into_one_group(cx: &mut TestAppContext) {
let mut cx = strip_window(