Skip to content

armgit / zed

Public Imported from GitHub
0

Code at the speed of thought – Zed is a high-performance, multiplayer code editor from the creators of Atom and Tree-sitter.

Pixel snapping (#54728)

John Tur7d42f276f2cc
diff --git a/Cargo.lock b/Cargo.lock
index 4a72eb2b2eb..1035e7795ab 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -7969,9 +7969,9 @@ dependencies = [
[[package]]
name = "grid"
-version = "0.18.0"
+version = "1.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "12101ecc8225ea6d675bc70263074eab6169079621c2186fe0c66590b2df9681"
+checksum = "f9e2d4c0a8296178d8802098410ca05d86b17a10bb5ab559b3fb404c1f948220"
[[package]]
name = "group"
@@ -17616,9 +17616,9 @@ dependencies = [
[[package]]
name = "taffy"
-version = "0.9.0"
+version = "0.10.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "a13e5d13f79d558b5d353a98072ca8ca0e99da429467804de959aa8c83c9a004"
+checksum = "aea22054047c16c3f34d3ac473a2170be1424b1115b2a3adcf28cfb067c88859"
dependencies = [
"arrayvec",
"grid",
diff --git a/crates/editor/src/element.rs b/crates/editor/src/element.rs
index 293a5890e2e..dd10b734d9f 100644
--- a/crates/editor/src/element.rs
+++ b/crates/editor/src/element.rs
@@ -2335,7 +2335,8 @@ impl EditorElement {
line_height: Pixels,
gutter_dimensions: &GutterDimensions,
gutter_settings: crate::editor_settings::Gutter,
- scroll_pixel_position: gpui::Point<ScrollPixelOffset>,
+ scroll_position: gpui::Point<ScrollOffset>,
+ start_row: DisplayRow,
gutter_hitbox: &Hitbox,
window: &mut Window,
cx: &mut App,
@@ -2349,10 +2350,10 @@ impl EditorElement {
);
let crease_toggle_size = crease_toggle.layout_as_root(available_space, window, cx);
+ let display_row = DisplayRow(start_row.0 + ix as u32);
let position = point(
gutter_dimensions.width - gutter_dimensions.right_padding,
- ix as f32 * line_height
- - (scroll_pixel_position.y % ScrollPixelOffset::from(line_height)).into(),
+ line_height * (display_row.as_f64() - scroll_position.y) as f32,
);
let centering_offset = point(
(gutter_dimensions.fold_area_width() - crease_toggle_size.width) / 2.,
@@ -2384,6 +2385,8 @@ impl EditorElement {
line_height: Pixels,
content_origin: gpui::Point<Pixels>,
scroll_pixel_position: gpui::Point<ScrollPixelOffset>,
+ scroll_position: gpui::Point<ScrollOffset>,
+ start_row: DisplayRow,
em_width: Pixels,
window: &mut Window,
cx: &mut App,
@@ -2407,8 +2410,8 @@ impl EditorElement {
};
let position = point(
Pixels::from(scroll_pixel_position.x) + line.width + padding,
- ix as f32 * line_height
- - (scroll_pixel_position.y % ScrollPixelOffset::from(line_height)).into(),
+ line_height
+ * (DisplayRow(start_row.0 + ix as u32).as_f64() - scroll_position.y) as f32,
);
let centering_offset = point(px(0.), (line_height - size.height) / 2.);
let origin = content_origin + position + centering_offset;
@@ -2429,6 +2432,7 @@ impl EditorElement {
gutter_hitbox: &Hitbox,
display_rows: Range<DisplayRow>,
snapshot: &EditorSnapshot,
+ scroll_position: gpui::Point<ScrollOffset>,
window: &mut Window,
cx: &mut App,
) -> Vec<(DisplayDiffHunk, Option<Hitbox>)> {
@@ -2441,8 +2445,13 @@ impl EditorElement {
if let GitGutterSetting::TrackedFiles = git_gutter_setting {
for (hunk, hitbox) in &mut display_hunks {
if matches!(hunk, DisplayDiffHunk::Unfolded { .. }) {
- let hunk_bounds =
- Self::diff_hunk_bounds(snapshot, line_height, gutter_hitbox.bounds, hunk);
+ let hunk_bounds = Self::diff_hunk_bounds(
+ scroll_position,
+ line_height,
+ gutter_hitbox.bounds,
+ hunk,
+ snapshot,
+ );
*hitbox = Some(window.insert_hitbox(hunk_bounds, HitboxBehavior::BlockMouse));
}
}
@@ -2972,6 +2981,7 @@ impl EditorElement {
buffer_rows: &[RowInfo],
em_width: Pixels,
scroll_position: gpui::Point<ScrollOffset>,
+ start_row: DisplayRow,
line_height: Pixels,
gutter_hitbox: &Hitbox,
max_width: Option<Pixels>,
@@ -2996,7 +3006,6 @@ impl EditorElement {
} else {
AvailableSpace::MaxContent
};
- let scroll_top = scroll_position.y * ScrollPixelOffset::from(line_height);
let start_x = em_width;
let mut last_used_color: Option<(Hsla, Oid)> = None;
@@ -3021,8 +3030,8 @@ impl EditorElement {
cx,
)?;
- let start_y = ix as f32 * line_height
- - Pixels::from(scroll_top % ScrollPixelOffset::from(line_height));
+ let start_y = line_height
+ * (DisplayRow(start_row.0 + ix as u32).as_f64() - scroll_position.y) as f32;
let absolute_offset = gutter_hitbox.origin + point(start_x, start_y);
element.prepaint_as_root(
@@ -3413,6 +3422,7 @@ impl EditorElement {
em_width: Pixels,
line_height: Pixels,
scroll_position: gpui::Point<ScrollOffset>,
+ start_row: DisplayRow,
buffer_rows: &[RowInfo],
window: &mut Window,
cx: &mut App,
@@ -3423,8 +3433,6 @@ impl EditorElement {
let editor_font_size = self.style.text.font_size.to_pixels(window.rem_size()) * 1.2;
- let scroll_top = scroll_position.y * ScrollPixelOffset::from(line_height);
-
let max_line_number_length = self
.editor
.read(cx)
@@ -3487,8 +3495,8 @@ impl EditorElement {
let position = point(
git_gutter_width + px(1.),
- ix as f32 * line_height
- - Pixels::from(scroll_top % ScrollPixelOffset::from(line_height))
+ line_height
+ * (DisplayRow(start_row.0 + ix as u32).as_f64() - scroll_position.y) as f32
+ px(1.),
);
let origin = gutter_hitbox.origin + position;
@@ -5970,7 +5978,7 @@ impl EditorElement {
fn paint_background(&self, layout: &EditorLayout, window: &mut Window, cx: &mut App) {
window.paint_layer(layout.hitbox.bounds, |window| {
- let scroll_top = layout.position_map.snapshot.scroll_position().y;
+ let scroll_top = layout.position_map.scroll_position.y;
let gutter_bg = cx.theme().colors().editor_gutter_background;
window.paint_quad(fill(layout.gutter_hitbox.bounds, gutter_bg));
window.paint_quad(fill(
@@ -6130,10 +6138,10 @@ impl EditorElement {
cx.theme().colors().editor_wrap_guide
};
window.paint_quad(fill(
- Bounds {
+ window.pixel_snap_bounds(Bounds {
origin: point(*guide_x, layout.position_map.text_hitbox.origin.y),
size: size(px(1.), layout.position_map.text_hitbox.size.height),
- },
+ }),
color,
));
}
@@ -6199,10 +6207,10 @@ impl EditorElement {
if let Some(requested_line_width) = settings.visible_line_width(indent_guide.active) {
if let Some(color) = line_color {
window.paint_quad(fill(
- Bounds {
+ window.pixel_snap_bounds(Bounds {
origin: indent_guide.origin,
size: size(px(requested_line_width as f32), indent_guide.length),
- },
+ }),
color,
));
line_indicator_width = requested_line_width as f32;
@@ -6212,13 +6220,13 @@ impl EditorElement {
if let Some(color) = background_color {
let width = indent_guide.single_indent_width - px(line_indicator_width);
window.paint_quad(fill(
- Bounds {
+ window.pixel_snap_bounds(Bounds {
origin: point(
indent_guide.origin.x + px(line_indicator_width),
indent_guide.origin.y,
),
size: size(width, indent_guide.length),
- },
+ }),
color,
));
}
@@ -6296,10 +6304,11 @@ impl EditorElement {
let hunk_to_paint = match hunk {
DisplayDiffHunk::Folded { .. } => {
let hunk_bounds = Self::diff_hunk_bounds(
- &layout.position_map.snapshot,
+ layout.position_map.scroll_position,
line_height,
layout.gutter_hitbox.bounds,
hunk,
+ &layout.position_map.snapshot,
);
Some((
hunk_bounds,
@@ -6390,12 +6399,12 @@ impl EditorElement {
}
fn diff_hunk_bounds(
- snapshot: &EditorSnapshot,
+ scroll_position: gpui::Point<ScrollOffset>,
line_height: Pixels,
gutter_bounds: Bounds<Pixels>,
hunk: &DisplayDiffHunk,
+ snapshot: &EditorSnapshot,
) -> Bounds<Pixels> {
- let scroll_position = snapshot.scroll_position();
let scroll_top = scroll_position.y * ScrollPixelOffset::from(line_height);
let gutter_strip_width = Self::gutter_strip_width(line_height);
@@ -6825,10 +6834,10 @@ impl EditorElement {
+ sticky_headers.lines.last().unwrap().offset
+ layout.position_map.line_height;
let separator_height = px(1.);
- let border_bounds = Bounds::from_corners(
+ let border_bounds = window.pixel_snap_bounds(Bounds::from_corners(
point(layout.gutter_hitbox.bounds.left(), border_top),
point(text_bounds.right(), border_top + separator_height),
- );
+ ));
window.paint_quad(fill(border_bounds, cx.theme().colors().border_variant));
layout.sticky_headers = Some(sticky_headers);
@@ -9985,6 +9994,11 @@ impl Element for EditorElement {
});
let mut scroll_position = snapshot.scroll_position();
+ if !line_height.is_zero() {
+ scroll_position.y = window
+ .pixel_snap_f64(scroll_position.y * f64::from(line_height))
+ / f64::from(line_height);
+ }
// The scroll position is a fractional point, the whole number of which represents
// the top of the window in terms of display rows.
// We add clipped_top_in_lines to skip rows that are clipped by parent containers,
@@ -10307,6 +10321,7 @@ impl Element for EditorElement {
em_width,
line_height,
scroll_position,
+ start_row,
&row_infos,
window,
cx,
@@ -10339,6 +10354,7 @@ impl Element for EditorElement {
&gutter_hitbox,
start_row..end_row,
&snapshot,
+ scroll_position,
window,
cx,
);
@@ -10593,10 +10609,16 @@ impl Element for EditorElement {
cx,
)
{
- scroll_position = new_scroll_position;
+ scroll_position.x = new_scroll_position.x;
}
});
+ if !em_layout_width.is_zero() {
+ scroll_position.x = window
+ .pixel_snap_f64(scroll_position.x * f64::from(em_layout_width))
+ / f64::from(em_layout_width);
+ }
+
let scroll_pixel_position = point(
scroll_position.x * f64::from(em_layout_width),
scroll_position.y * f64::from(line_height),
@@ -10648,6 +10670,8 @@ impl Element for EditorElement {
line_height,
content_origin,
scroll_pixel_position,
+ scroll_position,
+ start_row,
em_width,
window,
cx,
@@ -10755,6 +10779,7 @@ impl Element for EditorElement {
&row_infos,
em_width,
scroll_position,
+ start_row,
line_height,
&gutter_hitbox,
gutter_dimensions.git_blame_entries_width,
@@ -11038,7 +11063,8 @@ impl Element for EditorElement {
line_height,
&gutter_dimensions,
gutter_settings,
- scroll_pixel_position,
+ scroll_position,
+ start_row,
&gutter_hitbox,
window,
cx,
@@ -12121,7 +12147,7 @@ impl PointForPosition {
impl PositionMap {
pub(crate) fn point_for_position(&self, position: gpui::Point<Pixels>) -> PointForPosition {
let text_bounds = self.text_hitbox.bounds;
- let scroll_position = self.snapshot.scroll_position();
+ let scroll_position = self.scroll_position;
let position = position - text_bounds.origin;
let y = position.y.max(px(0.)).min(self.size.height);
let x = position.x + (scroll_position.x as f32 * self.em_layout_width);
@@ -12175,7 +12201,7 @@ impl PositionMap {
line: &LineWithInvisibles,
) -> PointForPosition {
let text_bounds = self.text_hitbox.bounds;
- let scroll_position = self.snapshot.scroll_position();
+ let scroll_position = self.scroll_position;
let position = position - text_bounds.origin;
let x = position.x + (scroll_position.x as f32 * self.em_layout_width);
@@ -12399,7 +12425,7 @@ impl CursorLayout {
}
pub fn paint(&mut self, origin: gpui::Point<Pixels>, window: &mut Window, cx: &mut App) {
- let bounds = self.bounds(origin);
+ let bounds = window.pixel_snap_bounds(self.bounds(origin));
//Draw background or border quad
let cursor = if matches!(self.shape, CursorShape::Hollow) {
diff --git a/crates/gpui/Cargo.toml b/crates/gpui/Cargo.toml
index 9dd5a55dd07..9b1d4562dea 100644
--- a/crates/gpui/Cargo.toml
+++ b/crates/gpui/Cargo.toml
@@ -94,7 +94,7 @@ async-channel.workspace = true
stacksafe.workspace = true
strum.workspace = true
sum_tree.workspace = true
-taffy = "=0.9.0"
+taffy = "=0.10.1"
thiserror.workspace = true
gpui_util.workspace = true
hdrhistogram = { workspace = true, optional = true }
diff --git a/crates/gpui/src/elements/text.rs b/crates/gpui/src/elements/text.rs
index 847acb6e287..8502eccf8b7 100644
--- a/crates/gpui/src/elements/text.rs
+++ b/crates/gpui/src/elements/text.rs
@@ -399,9 +399,11 @@ impl TextLayout {
) -> LayoutId {
let text_style = window.text_style();
let font_size = text_style.font_size.to_pixels(window.rem_size());
- let line_height = text_style
- .line_height
- .to_pixels(font_size.into(), window.rem_size());
+ let line_height = window.pixel_snap(
+ text_style
+ .line_height
+ .to_pixels(font_size.into(), window.rem_size()),
+ );
let runs = if let Some(runs) = runs {
runs
diff --git a/crates/gpui/src/style.rs b/crates/gpui/src/style.rs
index 97acc6f92bc..05bc083d1d7 100644
--- a/crates/gpui/src/style.rs
+++ b/crates/gpui/src/style.rs
@@ -698,72 +698,16 @@ impl Style {
if self.is_border_visible() {
let border_widths = self.border_widths.to_pixels(rem_size);
- let max_border_width = border_widths.max();
- let max_corner_radius = corner_radii.max();
- let zero_size = Size {
- width: Pixels::ZERO,
- height: Pixels::ZERO,
- };
-
- let mut top_bounds = Bounds::from_corners(
- bounds.origin,
- bounds.top_right() + point(Pixels::ZERO, max_border_width.max(max_corner_radius)),
- );
- top_bounds.size = top_bounds.size.max(&zero_size);
- let mut bottom_bounds = Bounds::from_corners(
- bounds.bottom_left() - point(Pixels::ZERO, max_border_width.max(max_corner_radius)),
- bounds.bottom_right(),
- );
- bottom_bounds.size = bottom_bounds.size.max(&zero_size);
- let mut left_bounds = Bounds::from_corners(
- top_bounds.bottom_left(),
- bottom_bounds.origin + point(max_border_width, Pixels::ZERO),
- );
- left_bounds.size = left_bounds.size.max(&zero_size);
- let mut right_bounds = Bounds::from_corners(
- top_bounds.bottom_right() - point(max_border_width, Pixels::ZERO),
- bottom_bounds.top_right(),
- );
- right_bounds.size = right_bounds.size.max(&zero_size);
-
let mut background = self.border_color.unwrap_or_default();
background.a = 0.;
- let quad = quad(
+ window.paint_quad(quad(
bounds,
corner_radii,
background,
border_widths,
self.border_color.unwrap_or_default(),
self.border_style,
- );
-
- window.with_content_mask(Some(ContentMask { bounds: top_bounds }), |window| {
- window.paint_quad(quad.clone());
- });
- window.with_content_mask(
- Some(ContentMask {
- bounds: right_bounds,
- }),
- |window| {
- window.paint_quad(quad.clone());
- },
- );
- window.with_content_mask(
- Some(ContentMask {
- bounds: bottom_bounds,
- }),
- |window| {
- window.paint_quad(quad.clone());
- },
- );
- window.with_content_mask(
- Some(ContentMask {
- bounds: left_bounds,
- }),
- |window| {
- window.paint_quad(quad);
- },
- );
+ ));
}
#[cfg(debug_assertions)]
diff --git a/crates/gpui/src/taffy.rs b/crates/gpui/src/taffy.rs
index 475af08308c..4844748d6c7 100644
--- a/crates/gpui/src/taffy.rs
+++ b/crates/gpui/src/taffy.rs
@@ -1,6 +1,10 @@
use crate::{
AbsoluteLength, App, Bounds, DefiniteLength, Edges, GridTemplate, Length, Pixels, Point, Size,
- Style, Window, point, size,
+ Style, Window, size,
+ util::{
+ ceil_to_device_pixel, round_half_toward_zero, round_stroke_to_device_pixel,
+ round_to_device_pixel,
+ },
};
use collections::{FxHashMap, FxHashSet};
use stacksafe::{StackSafe, stacksafe};
@@ -30,6 +34,8 @@ struct NodeContext {
pub struct TaffyLayoutEngine {
taffy: TaffyTree<NodeContext>,
absolute_layout_bounds: FxHashMap<LayoutId, Bounds<Pixels>>,
+ /// Unrounded absolute border-box top-left per-node coordinate in device pixels.
+ absolute_outer_origins: FxHashMap<LayoutId, Point<f32>>,
computed_layouts: FxHashSet<LayoutId>,
layout_bounds_scratch_space: Vec<LayoutId>,
}
@@ -39,10 +45,11 @@ const EXPECT_MESSAGE: &str = "we should avoid taffy layout errors by constructio
impl TaffyLayoutEngine {
pub fn new() -> Self {
let mut taffy = TaffyTree::new();
- taffy.enable_rounding();
+ taffy.disable_rounding();
TaffyLayoutEngine {
taffy,
absolute_layout_bounds: FxHashMap::default(),
+ absolute_outer_origins: FxHashMap::default(),
computed_layouts: FxHashSet::default(),
layout_bounds_scratch_space: Vec::new(),
}
@@ -51,6 +58,7 @@ impl TaffyLayoutEngine {
pub fn clear(&mut self) {
self.taffy.clear();
self.absolute_layout_bounds.clear();
+ self.absolute_outer_origins.clear();
self.computed_layouts.clear();
}
@@ -170,10 +178,11 @@ impl TaffyLayoutEngine {
//
if !self.computed_layouts.insert(id) {
- let mut stack = &mut self.layout_bounds_scratch_space;
+ let stack = &mut self.layout_bounds_scratch_space;
stack.push(id);
while let Some(id) = stack.pop() {
self.absolute_layout_bounds.remove(&id);
+ self.absolute_outer_origins.remove(&id);
stack.extend(
self.taffy
.children(id.into())
@@ -225,37 +234,122 @@ impl TaffyLayoutEngine {
untransform(available_space.height),
);
- let a: Size<Pixels> =
+ let measured_size: Size<Pixels> =
(node_context.measure)(known_dimensions, available_space, window, cx);
- size(a.width.0 * scale_factor, a.height.0 * scale_factor).into()
+ snap_measured_size_to_device_pixels(measured_size, scale_factor).into()
},
)
.expect(EXPECT_MESSAGE);
}
+ // Pixel snapping
+ //
+ // Painting primitives at non-integer pixel coordinates produces blurry
+ // output. Pixel snapping converts layout coordinates into integer
+ // device-pixel coordinates so painted edges land exactly on physical
+ // pixel boundaries.
+ //
+ // Non-integer coordinates can arise for several reasons, including:
+ // - flex distribution, percentages, centering, and text measurement
+ // can produce fractional element sizes and positions;
+ // - at fractional scale factors (for example 125% or 150%), integer
+ // logical-pixel values can map to non-integer device-pixel values.
+ //
+ // We pixel-snap by rounding in device-pixel space, after multiplying
+ // by `scale_factor`, so that snapping targets physical pixels. Bounds
+ // are divided by `scale_factor` before being returned to GPUI.
+ //
+ // Midpoints are rounded toward zero. This is a stylistic choice: a
+ // 1-logical-pixel line at 150% scale should render as 1 dp rather than
+ // 2 dp.
+ //
+ // Pixel snapping is done in two phases:
+ //
+ // 1. Pre-layout metric snapping. Before Taffy computes layout, all
+ // authored absolute lengths are rounded in `to_taffy`. This
+ // includes borders, padding, gaps, and explicit sizes.
+ // Custom-measured leaf nodes have their measured sizes rounded up
+ // to integer device-pixel lengths.
+ //
+ // 2. Post-layout edge snapping. After Taffy resolves the tree, layout
+ // relationships such as flex shares, grid tracks, percentages, and
+ // centering can produce new fractional edge positions. Boxes now
+ // have edges in absolute coordinates, and snapping must decide
+ // where those edges land on the device-pixel grid.
+ //
+ // Ideally, post-layout snapping would satisfy:
+ //
+ // - Edge closure. Two raw layout edges at the same absolute position
+ // should snap to the same pixel column.
+ // - Translation stability. A component's internal geometry should not
+ // change when it moves to a new absolute position.
+ //
+ // These goals are in tension because rounding is not associative.
+ // The simple local schemes make different tradeoffs:
+ //
+ // - Absolute edge rounding gives each window coordinate one answer,
+ // so coincident edges always close globally. But a span's snapped
+ // length is `round(far) - round(near)`, which may change by 1 dp
+ // as its absolute origin moves.
+ //
+ // - Parent-relative edge rounding rounds each child inside its
+ // parent's coordinate space. This guarantees translation stability,
+ // but a shared edge reached through different parents can
+ // accumulate different rounding, causing non-closure between
+ // cousins.
+ //
+ // - Length rounding rounds each width, height, and thickness
+ // independently and then places boxes from those rounded lengths.
+ // Sizes stay stable under translation, but neighboring boxes derive
+ // their shared boundary from different sources, so closure is not
+ // guaranteed.
+ //
+ // We apply absolute edge rounding for each element's outer box in
+ // post-layout rounding to preserve closure. Border and padding widths
+ // are not touched by post-layout rounding; they keep their pre-layout
+ // rounded value so that they remain stable under translation.
+ //
+ // This gives both closure and translation stability in the case that
+ // all local metrics are integer device-pixel lengths. Pre-layout
+ // rounding covers that in most cases. The exception is metrics
+ // resolved by layout relationships, such as percentages. Outer box
+ // edges will still close globally, and painted border widths are still
+ // snapped independently, but the raw content-box origin can carry a
+ // 1dp residual into descendants.
+
pub fn layout_bounds(&mut self, id: LayoutId, scale_factor: f32) -> Bounds<Pixels> {
if let Some(layout) = self.absolute_layout_bounds.get(&id).cloned() {
return layout;
}
let layout = self.taffy.layout(id.into()).expect(EXPECT_MESSAGE);
- let mut bounds = Bounds {
- origin: point(
- Pixels(layout.location.x / scale_factor),
- Pixels(layout.location.y / scale_factor),
- ),
- size: size(
- Pixels(layout.size.width / scale_factor),
- Pixels(layout.size.height / scale_factor),
- ),
+ let layout_location = layout.location;
+ let layout_size = layout.size;
+ let parent = self.taffy.parent(id.0);
+
+ let absolute_outer_origin = match parent {
+ Some(parent_id) => {
+ let parent_id = LayoutId::from(parent_id);
+ self.layout_bounds(parent_id, scale_factor);
+ let parent_origin = *self
+ .absolute_outer_origins
+ .get(&parent_id)
+ .expect("parent absolute outer origin should be cached");
+ parent_origin + Point::from(layout_location)
+ }
+ None => Point::from(layout_location),
};
+ self.absolute_outer_origins
+ .insert(id, absolute_outer_origin);
- if let Some(parent_id) = self.taffy.parent(id.0) {
- let parent_bounds = self.layout_bounds(parent_id.into(), scale_factor);
- bounds.origin += parent_bounds.origin;
- }
- self.absolute_layout_bounds.insert(id, bounds);
+ let absolute_far = absolute_outer_origin + Point::from(Size::from(layout_size));
+ let snapped_bounds = Bounds::from_corners(
+ absolute_outer_origin.map(round_half_toward_zero),
+ absolute_far.map(round_half_toward_zero),
+ );
+ let bounds = (snapped_bounds / scale_factor).map(Pixels);
+ self.absolute_layout_bounds.insert(id, bounds);
bounds
}
}
@@ -290,6 +384,29 @@ impl From<LayoutId> for NodeId {
}
}
+fn snap_measured_size_to_device_pixels(size: Size<Pixels>, scale_factor: f32) -> Size<f32> {
+ size.map(|d| ceil_to_device_pixel(d.0.max(0.0), scale_factor))
+}
+
+fn border_widths_to_taffy(
+ widths: &Edges<AbsoluteLength>,
+ rem_size: Pixels,
+ scale_factor: f32,
+) -> TaffyRect<taffy::style::LengthPercentage> {
+ let snap = |w: &AbsoluteLength| {
+ taffy::style::LengthPercentage::length(round_stroke_to_device_pixel(
+ w.to_pixels(rem_size).0,
+ scale_factor,
+ ))
+ };
+ TaffyRect {
+ top: snap(&widths.top),
+ right: snap(&widths.right),
+ bottom: snap(&widths.bottom),
+ left: snap(&widths.left),
+ }
+}
+
trait ToTaffy<Output> {
fn to_taffy(&self, rem_size: Pixels, scale_factor: f32) -> Output;
}
@@ -350,7 +467,7 @@ impl ToTaffy<taffy::style::Style> for Style {
aspect_ratio: self.aspect_ratio,
margin: self.margin.to_taffy(rem_size, scale_factor),
padding: self.padding.to_taffy(rem_size, scale_factor),
- border: self.border_widths.to_taffy(rem_size, scale_factor),
+ border: border_widths_to_taffy(&self.border_widths, rem_size, scale_factor),
align_items: self.align_items.map(|x| x.into()),
align_self: self.align_self.map(|x| x.into()),
align_content: self.align_content.map(|x| x.into()),
@@ -380,16 +497,7 @@ impl ToTaffy<taffy::style::Style> for Style {
impl ToTaffy<f32> for AbsoluteLength {
fn to_taffy(&self, rem_size: Pixels, scale_factor: f32) -> f32 {
- match self {
- AbsoluteLength::Pixels(pixels) => {
- let pixels: f32 = pixels.into();
- pixels * scale_factor
- }
- AbsoluteLength::Rems(rems) => {
- let pixels: f32 = (*rems * rem_size).into();
- pixels * scale_factor
- }
- }
+ round_to_device_pixel(self.to_pixels(rem_size).0, scale_factor)
}
}
@@ -418,16 +526,7 @@ impl ToTaffy<taffy::style::Dimension> for Length {
impl ToTaffy<taffy::style::LengthPercentage> for DefiniteLength {
fn to_taffy(&self, rem_size: Pixels, scale_factor: f32) -> taffy::style::LengthPercentage {
match self {
- DefiniteLength::Absolute(length) => match length {
- AbsoluteLength::Pixels(pixels) => {
- let pixels: f32 = pixels.into();
- taffy::style::LengthPercentage::length(pixels * scale_factor)
- }
- AbsoluteLength::Rems(rems) => {
- let pixels: f32 = (*rems * rem_size).into();
- taffy::style::LengthPercentage::length(pixels * scale_factor)
- }
- },
+ DefiniteLength::Absolute(length) => length.to_taffy(rem_size, scale_factor),
DefiniteLength::Fraction(fraction) => {
taffy::style::LengthPercentage::percent(*fraction)
}
@@ -438,16 +537,7 @@ impl ToTaffy<taffy::style::LengthPercentage> for DefiniteLength {
impl ToTaffy<taffy::style::LengthPercentageAuto> for DefiniteLength {
fn to_taffy(&self, rem_size: Pixels, scale_factor: f32) -> taffy::style::LengthPercentageAuto {
match self {
- DefiniteLength::Absolute(length) => match length {
- AbsoluteLength::Pixels(pixels) => {
- let pixels: f32 = pixels.into();
- taffy::style::LengthPercentageAuto::length(pixels * scale_factor)
- }
- AbsoluteLength::Rems(rems) => {
- let pixels: f32 = (*rems * rem_size).into();
- taffy::style::LengthPercentageAuto::length(pixels * scale_factor)
- }
- },
+ DefiniteLength::Absolute(length) => length.to_taffy(rem_size, scale_factor),
DefiniteLength::Fraction(fraction) => {
taffy::style::LengthPercentageAuto::percent(*fraction)
}
@@ -458,15 +548,7 @@ impl ToTaffy<taffy::style::LengthPercentageAuto> for DefiniteLength {
impl ToTaffy<taffy::style::Dimension> for DefiniteLength {
fn to_taffy(&self, rem_size: Pixels, scale_factor: f32) -> taffy::style::Dimension {
match self {
- DefiniteLength::Absolute(length) => match length {
- AbsoluteLength::Pixels(pixels) => {
- let pixels: f32 = pixels.into();
- taffy::style::Dimension::length(pixels * scale_factor)
- }
- AbsoluteLength::Rems(rems) => {
- taffy::style::Dimension::length((*rems * rem_size * scale_factor).into())
- }
- },
+ DefiniteLength::Absolute(length) => length.to_taffy(rem_size, scale_factor),
DefiniteLength::Fraction(fraction) => taffy::style::Dimension::percent(*fraction),
}
}
@@ -474,16 +556,19 @@ impl ToTaffy<taffy::style::Dimension> for DefiniteLength {
impl ToTaffy<taffy::style::LengthPercentage> for AbsoluteLength {
fn to_taffy(&self, rem_size: Pixels, scale_factor: f32) -> taffy::style::LengthPercentage {
- match self {
- AbsoluteLength::Pixels(pixels) => {
- let pixels: f32 = pixels.into();
- taffy::style::LengthPercentage::length(pixels * scale_factor)
- }
- AbsoluteLength::Rems(rems) => {
- let pixels: f32 = (*rems * rem_size).into();
- taffy::style::LengthPercentage::length(pixels * scale_factor)
- }
- }
+ taffy::style::LengthPercentage::length(self.to_taffy(rem_size, scale_factor))
+ }
+}
+
+impl ToTaffy<taffy::style::LengthPercentageAuto> for AbsoluteLength {
+ fn to_taffy(&self, rem_size: Pixels, scale_factor: f32) -> taffy::style::LengthPercentageAuto {
+ taffy::style::LengthPercentageAuto::length(self.to_taffy(rem_size, scale_factor))
+ }
+}
+
+impl ToTaffy<taffy::style::Dimension> for AbsoluteLength {
+ fn to_taffy(&self, rem_size: Pixels, scale_factor: f32) -> taffy::style::Dimension {
+ taffy::style::Dimension::length(self.to_taffy(rem_size, scale_factor))
}
}
@@ -631,3 +716,36 @@ impl From<Size<Pixels>> for Size<AvailableSpace> {
}
}
}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn border_widths_to_taffy_use_stroke_snapping() {
+ let border_widths = Edges {
+ top: Pixels(0.0).into(),
+ right: Pixels(0.4).into(),
+ bottom: Pixels(0.5).into(),
+ left: Pixels(1.6).into(),
+ };
+ let taffy_border = border_widths_to_taffy(&border_widths, Pixels(16.0), 1.0);
+
+ assert_eq!(
+ taffy_border.top,
+ taffy::style::LengthPercentage::length(0.0)
+ );
+ assert_eq!(
+ taffy_border.right,
+ taffy::style::LengthPercentage::length(1.0)
+ );
+ assert_eq!(
+ taffy_border.bottom,
+ taffy::style::LengthPercentage::length(1.0)
+ );
+ assert_eq!(
+ taffy_border.left,
+ taffy::style::LengthPercentage::length(2.0)
+ );
+ }
+}
diff --git a/crates/gpui/src/text_system.rs b/crates/gpui/src/text_system.rs
index b62a0ad6fd4..c7b11ecaa4e 100644
--- a/crates/gpui/src/text_system.rs
+++ b/crates/gpui/src/text_system.rs
@@ -45,11 +45,7 @@ pub struct FontFamilyId(pub usize);
pub const SUBPIXEL_VARIANTS_X: u8 = 4;
/// Number of subpixel glyph variants along the Y axis.
-pub const SUBPIXEL_VARIANTS_Y: u8 = if cfg!(target_os = "windows") || cfg!(target_os = "linux") {
- 1
-} else {
- SUBPIXEL_VARIANTS_X
-};
+pub const SUBPIXEL_VARIANTS_Y: u8 = 1;
/// The GPUI text rendering sub system.
pub struct TextSystem {
diff --git a/crates/gpui/src/util.rs b/crates/gpui/src/util.rs
index 8a7411e0ac2..13ee752dadf 100644
--- a/crates/gpui/src/util.rs
+++ b/crates/gpui/src/util.rs
@@ -125,12 +125,106 @@ pub(crate) fn atomic_incr_if_not_zero(counter: &AtomicUsize) -> usize {
}
}
+/// Rounds to the nearest integer with 0.5 ties toward zero.
+#[inline]
+pub(crate) fn round_half_toward_zero(value: f32) -> f32 {
+ (value.abs() - 0.5).ceil().copysign(value)
+}
+
+#[inline]
+pub(crate) fn round_half_toward_zero_f64(value: f64) -> f64 {
+ (value.abs() - 0.5).ceil().copysign(value)
+}
+
+#[inline]
+pub(crate) fn round_to_device_pixel(logical: f32, scale_factor: f32) -> f32 {
+ round_half_toward_zero(logical * scale_factor)
+}
+
+#[inline]
+pub(crate) fn round_stroke_to_device_pixel(logical: f32, scale_factor: f32) -> f32 {
+ if logical == 0.0 {
+ 0.0
+ } else {
+ round_to_device_pixel(logical.max(0.0), scale_factor).max(1.0)
+ }
+}
+
+#[inline]
+pub(crate) fn floor_to_device_pixel(logical: f32, scale_factor: f32) -> f32 {
+ (logical * scale_factor).floor()
+}
+
+#[inline]
+pub(crate) fn ceil_to_device_pixel(logical: f32, scale_factor: f32) -> f32 {
+ (logical * scale_factor).ceil()
+}
+
#[cfg(test)]
mod tests {
use crate::TestAppContext;
use super::*;
+ #[test]
+ fn test_round_half_toward_zero() {
+ // Midpoint ties go toward zero
+ assert_eq!(round_half_toward_zero(0.5), 0.0);
+ assert_eq!(round_half_toward_zero(1.5), 1.0);
+ assert_eq!(round_half_toward_zero(2.5), 2.0);
+ assert_eq!(round_half_toward_zero(-0.5), 0.0);
+ assert_eq!(round_half_toward_zero(-1.5), -1.0);
+ assert_eq!(round_half_toward_zero(-2.5), -2.0);
+
+ // Non-midpoint values round to nearest
+ assert_eq!(round_half_toward_zero(1.5001), 2.0);
+ assert_eq!(round_half_toward_zero(1.4999), 1.0);
+ assert_eq!(round_half_toward_zero(-1.5001), -2.0);
+ assert_eq!(round_half_toward_zero(-1.4999), -1.0);
+
+ // Integers are unchanged
+ assert_eq!(round_half_toward_zero(0.0), 0.0);
+ assert_eq!(round_half_toward_zero(3.0), 3.0);
+ assert_eq!(round_half_toward_zero(-3.0), -3.0);
+ }
+
+ #[test]
+ fn test_device_pixel_helpers() {
+ // Snap uses half-toward-zero: 1.0 * 1.5 = 1.5 ties toward 1.0.
+ assert_eq!(round_to_device_pixel(1.0, 1.5), 1.0);
+ // Below the tie rounds down, above rounds up.
+ assert_eq!(round_to_device_pixel(0.3, 2.0), 1.0);
+ assert_eq!(round_to_device_pixel(1.4, 1.0), 1.0);
+ assert_eq!(round_to_device_pixel(1.6, 1.0), 2.0);
+
+ // Stroke uses snap, but clamps non-zero input up to at least 1dp.
+ assert_eq!(round_stroke_to_device_pixel(0.0, 1.0), 0.0);
+ assert_eq!(round_stroke_to_device_pixel(0.4, 1.0), 1.0);
+ assert_eq!(round_stroke_to_device_pixel(0.5, 1.0), 1.0);
+ assert_eq!(round_stroke_to_device_pixel(1.0, 1.5), 1.0);
+ assert_eq!(round_stroke_to_device_pixel(1.6, 1.0), 2.0);
+
+ // Cover's near edge floors, far edge ceils. Together they form a strict superset.
+ assert_eq!(floor_to_device_pixel(0.3, 2.0), 0.0);
+ assert_eq!(ceil_to_device_pixel(0.3, 2.0), 1.0);
+ assert_eq!(floor_to_device_pixel(2.1, 1.0), 2.0);
+ assert_eq!(ceil_to_device_pixel(2.1, 1.0), 3.0);
+
+ // Integer device-pixel inputs are stable under all three.
+ assert_eq!(round_to_device_pixel(2.0, 2.0), 4.0);
+ assert_eq!(floor_to_device_pixel(2.0, 2.0), 4.0);
+ assert_eq!(ceil_to_device_pixel(2.0, 2.0), 4.0);
+ }
+
+ #[test]
+ fn test_round_half_toward_zero_f64() {
+ assert_eq!(round_half_toward_zero_f64(0.5), 0.0);
+ assert_eq!(round_half_toward_zero_f64(-0.5), 0.0);
+ assert_eq!(round_half_toward_zero_f64(1.5), 1.0);
+ assert_eq!(round_half_toward_zero_f64(-1.5), -1.0);
+ assert_eq!(round_half_toward_zero_f64(2.5001), 3.0);
+ }
+
#[gpui::test]
async fn test_with_timeout(cx: &mut TestAppContext) {
Task::ready(())
diff --git a/crates/gpui/src/window.rs b/crates/gpui/src/window.rs
index 49bdf2e65cf..4d4b9ddc856 100644
--- a/crates/gpui/src/window.rs
+++ b/crates/gpui/src/window.rs
@@ -59,7 +59,10 @@ use uuid::Uuid;
mod prompts;
-use crate::util::atomic_incr_if_not_zero;
+use crate::util::{
+ atomic_incr_if_not_zero, ceil_to_device_pixel, floor_to_device_pixel, round_half_toward_zero,
+ round_half_toward_zero_f64, round_stroke_to_device_pixel, round_to_device_pixel,
+};
pub use prompts::*;
/// Default window size used when no explicit size is provided.
@@ -2309,6 +2312,76 @@ impl Window {
self.text_style().line_height_in_pixels(self.rem_size())
}
+ /// Rounds a logical value to the nearest device pixel.
+ #[inline]
+ pub fn pixel_snap(&self, value: Pixels) -> Pixels {
+ px(round_to_device_pixel(value.0, self.scale_factor()) / self.scale_factor())
+ }
+
+ /// f64 variant of [`Self::pixel_snap`].
+ #[inline]
+ pub fn pixel_snap_f64(&self, value: f64) -> f64 {
+ let scale_factor = f64::from(self.scale_factor());
+ round_half_toward_zero_f64(value * scale_factor) / scale_factor
+ }
+
+ /// Snaps a bounds' origin and size to the nearest device pixel.
+ #[inline]
+ pub fn pixel_snap_bounds(&self, bounds: Bounds<Pixels>) -> Bounds<Pixels> {
+ bounds.map(|c| self.pixel_snap(c))
+ }
+
+ /// Snaps a point's coordinates to the nearest device pixel.
+ #[inline]
+ pub fn pixel_snap_point(&self, position: Point<Pixels>) -> Point<Pixels> {
+ position.map(|c| self.pixel_snap(c))
+ }
+
+ #[inline]
+ fn snap_bounds(&self, bounds: Bounds<Pixels>) -> Bounds<ScaledPixels> {
+ let scale_factor = self.scale_factor();
+ let left = round_to_device_pixel(bounds.left().0, scale_factor);
+ let top = round_to_device_pixel(bounds.top().0, scale_factor);
+ let right = round_to_device_pixel(bounds.right().0, scale_factor).max(left);
+ let bottom = round_to_device_pixel(bounds.bottom().0, scale_factor).max(top);
+ Bounds::from_corners(
+ point(ScaledPixels(left), ScaledPixels(top)),
+ point(ScaledPixels(right), ScaledPixels(bottom)),
+ )
+ }
+
+ /// Rounds half-to-zero but clamps any non-zero input up to 1 dp so thin strokes do not disappear.
+ #[inline]
+ fn snap_stroke(&self, value: Pixels) -> ScaledPixels {
+ ScaledPixels(round_stroke_to_device_pixel(value.0, self.scale_factor()))
+ }
+
+ #[inline]
+ fn snap_border_widths(&self, edges: Edges<Pixels>) -> Edges<ScaledPixels> {
+ edges.map(|e| self.snap_stroke(*e))
+ }
+
+ /// Floors the near edge and ceils the far edge, producing a strict superset of the raw region.
+ #[inline]
+ fn cover_bounds(&self, bounds: Bounds<Pixels>) -> Bounds<ScaledPixels> {
+ let scale_factor = self.scale_factor();
+ let left = floor_to_device_pixel(bounds.left().0, scale_factor);
+ let top = floor_to_device_pixel(bounds.top().0, scale_factor);
+ let right = ceil_to_device_pixel(bounds.right().0, scale_factor).max(left);
+ let bottom = ceil_to_device_pixel(bounds.bottom().0, scale_factor).max(top);
+ Bounds::from_corners(
+ point(ScaledPixels(left), ScaledPixels(top)),
+ point(ScaledPixels(right), ScaledPixels(bottom)),
+ )
+ }
+
+ #[inline]
+ fn snapped_content_mask(&self) -> ContentMask<ScaledPixels> {
+ ContentMask {
+ bounds: self.cover_bounds(self.content_mask().bounds),
+ }
+ }
+
/// Call to prevent the default action of an event. Currently only used to prevent
/// parent elements from becoming focused on mouse down.
pub fn prevent_default(&mut self) {
@@ -3316,13 +3389,12 @@ impl Window {
pub fn paint_layer<R>(&mut self, bounds: Bounds<Pixels>, f: impl FnOnce(&mut Self) -> R) -> R {
self.invalidator.debug_assert_paint();
- let scale_factor = self.scale_factor();
let content_mask = self.content_mask();
let clipped_bounds = bounds.intersect(&content_mask.bounds);
if !clipped_bounds.is_empty() {
self.next_frame
.scene
- .push_layer(clipped_bounds.scale(scale_factor));
+ .push_layer(self.cover_bounds(clipped_bounds));
}
let result = f(self);
@@ -3346,15 +3418,15 @@ impl Window {
self.invalidator.debug_assert_paint();
let scale_factor = self.scale_factor();
- let content_mask = self.content_mask();
+ let content_mask = self.snapped_content_mask();
let opacity = self.element_opacity();
for shadow in shadows {
let shadow_bounds = (bounds + shadow.offset).dilate(shadow.spread_radius);
self.next_frame.scene.insert_primitive(Shadow {
order: 0,
blur_radius: shadow.blur_radius.scale(scale_factor),
- bounds: shadow_bounds.scale(scale_factor),
- content_mask: content_mask.scale(scale_factor),
+ bounds: self.cover_bounds(shadow_bounds),
+ content_mask,
corner_radii: corner_radii.scale(scale_factor),
color: shadow.color.opacity(opacity),
});
@@ -3373,17 +3445,17 @@ impl Window {
pub fn paint_quad(&mut self, quad: PaintQuad) {
self.invalidator.debug_assert_paint();
- let scale_factor = self.scale_factor();
- let content_mask = self.content_mask();
let opacity = self.element_opacity();
+ let snapped_bounds = self.snap_bounds(quad.bounds);
+ let snapped_border_widths = self.snap_border_widths(quad.border_widths);
self.next_frame.scene.insert_primitive(Quad {
order: 0,
- bounds: quad.bounds.scale(scale_factor),
- content_mask: content_mask.scale(scale_factor),
+ bounds: snapped_bounds,
+ content_mask: self.snapped_content_mask(),
background: quad.background.opacity(opacity),
border_color: quad.border_color.opacity(opacity),
- corner_radii: quad.corner_radii.scale(scale_factor),
- border_widths: quad.border_widths.scale(scale_factor),
+ corner_radii: quad.corner_radii.scale(self.scale_factor()),
+ border_widths: snapped_border_widths,
border_style: quad.border_style,
});
}
@@ -3417,25 +3489,25 @@ impl Window {
self.invalidator.debug_assert_paint();
let scale_factor = self.scale_factor();
+ let thickness = self.snap_stroke(style.thickness);
let height = if style.wavy {
- style.thickness * 3.
+ ScaledPixels(thickness.0 * 3.)
} else {
- style.thickness
+ thickness
};
let bounds = Bounds {
- origin,
- size: size(width, height),
+ origin: origin.map(|c| ScaledPixels(round_to_device_pixel(c.0, scale_factor))),
+ size: size(self.snap_stroke(width), height),
};
- let content_mask = self.content_mask();
let element_opacity = self.element_opacity();
self.next_frame.scene.insert_primitive(Underline {
order: 0,
pad: 0,
- bounds: bounds.scale(scale_factor),
- content_mask: content_mask.scale(scale_factor),
+ bounds,
+ content_mask: self.snapped_content_mask(),
color: style.color.unwrap_or_default().opacity(element_opacity),
- thickness: style.thickness.scale(scale_factor),
+ thickness,
wavy: if style.wavy { 1 } else { 0 },
});
}
@@ -3454,18 +3526,17 @@ impl Window {
let scale_factor = self.scale_factor();
let height = style.thickness;
let bounds = Bounds {
- origin,
- size: size(width, height),
+ origin: origin.map(|c| ScaledPixels(round_to_device_pixel(c.0, scale_factor))),
+ size: size(self.snap_stroke(width), self.snap_stroke(height)),
};
- let content_mask = self.content_mask();
let opacity = self.element_opacity();
self.next_frame.scene.insert_primitive(Underline {
order: 0,
pad: 0,
- bounds: bounds.scale(scale_factor),
- content_mask: content_mask.scale(scale_factor),
- thickness: style.thickness.scale(scale_factor),
+ bounds,
+ content_mask: self.snapped_content_mask(),
+ thickness: self.snap_stroke(style.thickness),
color: style.color.unwrap_or_default().opacity(opacity),
wavy: 0,
});
@@ -3493,10 +3564,17 @@ impl Window {
let scale_factor = self.scale_factor();
let glyph_origin = origin.scale(scale_factor);
- let subpixel_variant = Point {
- x: (glyph_origin.x.0.fract() * SUBPIXEL_VARIANTS_X as f32).floor() as u8,
- y: (glyph_origin.y.0.fract() * SUBPIXEL_VARIANTS_Y as f32).floor() as u8,
- };
+ let quantized_origin = Point::new(
+ round_half_toward_zero(glyph_origin.x.0 * SUBPIXEL_VARIANTS_X as f32)
+ / SUBPIXEL_VARIANTS_X as f32,
+ round_half_toward_zero(glyph_origin.y.0 * SUBPIXEL_VARIANTS_Y as f32)
+ / SUBPIXEL_VARIANTS_Y as f32,
+ );
+ let subpixel_variant = Point::new(
+ (quantized_origin.x.fract() * SUBPIXEL_VARIANTS_X as f32) as u8,
+ (quantized_origin.y.fract() * SUBPIXEL_VARIANTS_Y as f32) as u8,
+ );
+ let integer_origin = quantized_origin.map(|c| ScaledPixels(c.trunc()));
let subpixel_rendering = self.should_use_subpixel_rendering(font_id, font_size);
let params = RenderGlyphParams {
font_id,
@@ -3518,10 +3596,10 @@ impl Window {
})?
.expect("Callback above only errors or returns Some");
let bounds = Bounds {
- origin: glyph_origin.map(|px| px.floor()) + raster_bounds.origin.map(Into::into),
+ origin: integer_origin + raster_bounds.origin.map(Into::into),
size: tile.bounds.size.map(Into::into),
};
- let content_mask = self.content_mask().scale(scale_factor);
+ let content_mask = self.snapped_content_mask();
if subpixel_rendering {
self.next_frame.scene.insert_primitive(SubpixelSprite {
@@ -3548,100 +3626,6 @@ impl Window {
Ok(())
}
- /// Paints a monochrome glyph with pre-computed raster bounds.
- ///
- /// This is faster than `paint_glyph` because it skips the per-glyph cache lookup.
- /// Use `ShapedLine::compute_glyph_raster_data` to batch-compute raster bounds during prepaint.
- pub fn paint_glyph_with_raster_bounds(
- &mut self,
- origin: Point<Pixels>,
- _font_id: FontId,
- _glyph_id: GlyphId,
- _font_size: Pixels,
- color: Hsla,
- raster_bounds: Bounds<DevicePixels>,
- params: &RenderGlyphParams,
- ) -> Result<()> {
- self.invalidator.debug_assert_paint();
-
- let element_opacity = self.element_opacity();
- let scale_factor = self.scale_factor();
- let glyph_origin = origin.scale(scale_factor);
-
- if !raster_bounds.is_zero() {
- let tile = self
- .sprite_atlas
- .get_or_insert_with(&params.clone().into(), &mut || {
- let (size, bytes) = self.text_system().rasterize_glyph(params)?;
- Ok(Some((size, Cow::Owned(bytes))))
- })?
- .expect("Callback above only errors or returns Some");
- let bounds = Bounds {
- origin: glyph_origin.map(|px| px.floor()) + raster_bounds.origin.map(Into::into),
- size: tile.bounds.size.map(Into::into),
- };
- let content_mask = self.content_mask().scale(scale_factor);
- self.next_frame.scene.insert_primitive(MonochromeSprite {
- order: 0,
- pad: 0,
- bounds,
- content_mask,
- color: color.opacity(element_opacity),
- tile,
- transformation: TransformationMatrix::unit(),
- });
- }
- Ok(())
- }
-
- /// Paints an emoji glyph with pre-computed raster bounds.
- ///
- /// This is faster than `paint_emoji` because it skips the per-glyph cache lookup.
- /// Use `ShapedLine::compute_glyph_raster_data` to batch-compute raster bounds during prepaint.
- pub fn paint_emoji_with_raster_bounds(
- &mut self,
- origin: Point<Pixels>,
- _font_id: FontId,
- _glyph_id: GlyphId,
- _font_size: Pixels,
- raster_bounds: Bounds<DevicePixels>,
- params: &RenderGlyphParams,
- ) -> Result<()> {
- self.invalidator.debug_assert_paint();
-
- let scale_factor = self.scale_factor();
- let glyph_origin = origin.scale(scale_factor);
-
- if !raster_bounds.is_zero() {
- let tile = self
- .sprite_atlas
- .get_or_insert_with(&params.clone().into(), &mut || {
- let (size, bytes) = self.text_system().rasterize_glyph(params)?;
- Ok(Some((size, Cow::Owned(bytes))))
- })?
- .expect("Callback above only errors or returns Some");
-
- let bounds = Bounds {
- origin: glyph_origin.map(|px| px.floor()) + raster_bounds.origin.map(Into::into),
- size: tile.bounds.size.map(Into::into),
- };
- let content_mask = self.content_mask().scale(scale_factor);
- let opacity = self.element_opacity();
-
- self.next_frame.scene.insert_primitive(PolychromeSprite {
- order: 0,
- pad: 0,
- grayscale: false,
- bounds,
- corner_radii: Default::default(),
- content_mask,
- tile,
- opacity,
- });
- }
- Ok(())
- }
-
fn should_use_subpixel_rendering(&self, font_id: FontId, font_size: Pixels) -> bool {
if self.platform_window.background_appearance() != WindowBackgroundAppearance::Opaque {
return false;
@@ -3680,11 +3664,11 @@ impl Window {
let scale_factor = self.scale_factor();
let glyph_origin = origin.scale(scale_factor);
+ let integer_origin = glyph_origin.map(|c| ScaledPixels(round_half_toward_zero(c.0)));
let params = RenderGlyphParams {
font_id,
glyph_id,
font_size,
- // We don't render emojis with subpixel variants.
subpixel_variant: Default::default(),
scale_factor,
is_emoji: true,
@@ -3702,10 +3686,10 @@ impl Window {
.expect("Callback above only errors or returns Some");
let bounds = Bounds {
- origin: glyph_origin.map(|px| px.floor()) + raster_bounds.origin.map(Into::into),
+ origin: integer_origin + raster_bounds.origin.map(Into::into),
size: tile.bounds.size.map(Into::into),
};
- let content_mask = self.content_mask().scale(scale_factor);
+ let content_mask = self.snapped_content_mask();
let opacity = self.element_opacity();
self.next_frame.scene.insert_primitive(PolychromeSprite {
@@ -3737,9 +3721,8 @@ impl Window {
self.invalidator.debug_assert_paint();
let element_opacity = self.element_opacity();
- let scale_factor = self.scale_factor();
+ let bounds = self.snap_bounds(bounds);
- let bounds = bounds.scale(scale_factor);
let params = RenderSvgParams {
path,
size: bounds.size.map(|pixels| {
@@ -3759,7 +3742,7 @@ impl Window {
else {
return Ok(());
};
- let content_mask = self.content_mask().scale(scale_factor);
+ let content_mask = self.snapped_content_mask();
let svg_bounds = Bounds {
origin: bounds.center()
- Point::new(
@@ -3771,13 +3754,14 @@ impl Window {
.size
.map(|value| ScaledPixels(value.0 as f32 / SMOOTH_SVG_SCALE_FACTOR)),
};
+ let final_bounds = svg_bounds
+ .map_origin(|value| ScaledPixels(round_half_toward_zero(value.0)))
+ .map_size(|size| size.ceil());
self.next_frame.scene.insert_primitive(MonochromeSprite {
order: 0,
pad: 0,
- bounds: svg_bounds
- .map_origin(|origin| origin.round())
- .map_size(|size| size.ceil()),
+ bounds: final_bounds,
content_mask,
color: color.opacity(element_opacity),
tile,
@@ -3801,8 +3785,7 @@ impl Window {
) -> Result<()> {
self.invalidator.debug_assert_paint();
- let scale_factor = self.scale_factor();
- let bounds = bounds.scale(scale_factor);
+ let bounds = self.snap_bounds(bounds);
let params = RenderImageParams {
image_id: data.id,
frame_index,
@@ -3820,17 +3803,15 @@ impl Window {
)))
})?
.expect("Callback above only returns Some");
- let content_mask = self.content_mask().scale(scale_factor);
- let corner_radii = corner_radii.scale(scale_factor);
+ let content_mask = self.snapped_content_mask();
+ let corner_radii = corner_radii.scale(self.scale_factor());
let opacity = self.element_opacity();
self.next_frame.scene.insert_primitive(PolychromeSprite {
order: 0,
pad: 0,
grayscale,
- bounds: bounds
- .map_origin(|origin| origin.floor())
- .map_size(|size| size.ceil()),
+ bounds,
content_mask,
corner_radii,
tile,
@@ -3848,9 +3829,8 @@ impl Window {
self.invalidator.debug_assert_paint();
- let scale_factor = self.scale_factor();
- let bounds = bounds.scale(scale_factor);
- let content_mask = self.content_mask().scale(scale_factor);
+ let bounds = self.snap_bounds(bounds);
+ let content_mask = self.snapped_content_mask();
self.next_frame.scene.insert_primitive(PaintSurface {
order: 0,
bounds,
@@ -3955,7 +3935,8 @@ impl Window {
.unwrap()
.layout_bounds(layout_id, scale_factor)
.map(Into::into);
- bounds.origin += self.element_offset();
+ let snapped_offset = self.pixel_snap_point(self.element_offset());
+ bounds.origin += snapped_offset;
bounds
}
diff --git a/crates/terminal_view/src/terminal_element.rs b/crates/terminal_view/src/terminal_element.rs
index 1e07e1c49d4..dc1b63fb09a 100644
--- a/crates/terminal_view/src/terminal_element.rs
+++ b/crates/terminal_view/src/terminal_element.rs
@@ -185,15 +185,14 @@ impl LayoutRect {
let position = {
let alac_point = self.point;
point(
- (origin.x + alac_point.column as f32 * dimensions.cell_width).floor(),
+ origin.x + alac_point.column as f32 * dimensions.cell_width,
origin.y + alac_point.line as f32 * dimensions.line_height,
)
};
- let size = point(
- (dimensions.cell_width * self.num_of_cells as f32).ceil(),
+ let size = size(
+ dimensions.cell_width * self.num_of_cells as f32,
dimensions.line_height,
- )
- .into();
+ );
window.paint_quad(fill(Bounds::new(position, size), self.color));
}
@@ -959,13 +958,15 @@ impl Element for TerminalElement {
let (dimensions, line_height_px) = {
let rem_size = window.rem_size();
let font_pixels = text_style.font_size.to_pixels(rem_size);
- let line_height = f32::from(font_pixels) * line_height;
+ let line_height = window.pixel_snap(px(f32::from(font_pixels) * line_height));
let font_id = cx.text_system().resolve_font(&text_style.font());
- let cell_width = text_system
- .advance(font_id, font_pixels, 'm')
- .unwrap()
- .width;
+ let cell_width = window.pixel_snap(
+ text_system
+ .advance(font_id, font_pixels, 'm')
+ .unwrap()
+ .width,
+ );
gutter = cell_width;
let mut size = bounds.size;
@@ -982,7 +983,7 @@ impl Element for TerminalElement {
origin.x += gutter;
(
- TerminalBounds::new(px(line_height), cell_width, Bounds { origin, size }),
+ TerminalBounds::new(line_height, cell_width, Bounds { origin, size }),
line_height,
)
};
@@ -1093,10 +1094,9 @@ impl Element for TerminalElement {
// internal line number (which can be negative in Scrollable mode for
// scrollback history).
let rows_above_viewport =
- f32::from((intersection.top() - bounds.top()).max(px(0.)) / line_height_px)
- as usize;
+ ((intersection.top() - bounds.top()).max(px(0.)) / line_height_px) as usize;
let visible_row_count =
- f32::from((intersection.size.height / line_height_px).ceil()) as usize + 1;
+ (intersection.size.height / line_height_px).ceil() as usize + 1;
TerminalElement::layout_grid(
// Group cells by line and filter to only the visible screen rows.
diff --git a/crates/ui/src/components/indent_guides.rs b/crates/ui/src/components/indent_guides.rs
index 60aa23b44c2..9e78b0d4bf6 100644
--- a/crates/ui/src/components/indent_guides.rs
+++ b/crates/ui/src/components/indent_guides.rs
@@ -331,7 +331,10 @@ impl Element for IndentGuidesElement {
self.colors.default
};
- window.paint_quad(fill(indent_guide.bounds, fill_color));
+ window.paint_quad(fill(
+ window.pixel_snap_bounds(indent_guide.bounds),
+ fill_color,
+ ));
}
}
IndentGuidesElementPrepaintState::Interactive {
@@ -377,7 +380,10 @@ impl Element for IndentGuidesElement {
self.colors.default
};
- window.paint_quad(fill(indent_guide.bounds, fill_color));
+ window.paint_quad(fill(
+ window.pixel_snap_bounds(indent_guide.bounds),
+ fill_color,
+ ));
}
window.on_mouse_event({
diff --git a/crates/workspace/src/pane.rs b/crates/workspace/src/pane.rs
index 6f4e8eca5a3..de707c8eb17 100644
--- a/crates/workspace/src/pane.rs
+++ b/crates/workspace/src/pane.rs
@@ -8299,9 +8299,10 @@ mod tests {
let new_tab_button_bounds = cx.debug_bounds("ICON-Plus").unwrap();
let scroll_bounds = tab_bar_scroll_handle.bounds();
let scroll_offset = tab_bar_scroll_handle.offset();
+ assert!(scroll_offset.x < px(0.));
+ assert!(scroll_offset.x >= -tab_bar_scroll_handle.max_offset().x);
+ assert!(tab_bounds.left() >= scroll_bounds.left());
assert!(tab_bounds.right() <= scroll_bounds.right());
- // -39.5 is the magic number for this setup
- assert_eq!(scroll_offset.x, px(-39.5));
assert!(
!tab_bounds.intersects(&new_tab_button_bounds),
"Tab should not overlap with the new tab button, if this is failing check if there's been a redesign!"