Skip to content

Visual Studio Code, rebuilt in Rust

Rust

fix(gpui): snap layout and text to Chromium's LayoutUnits

rokartur26729d57c39b
diff --git a/native/crates/app/src/file_icons.rs b/native/crates/app/src/file_icons.rs
index edc87522958..c0136b38b8a 100644
--- a/native/crates/app/src/file_icons.rs
+++ b/native/crates/app/src/file_icons.rs
@@ -10,7 +10,7 @@ use anyhow::Context as _;
use exthost::scan::ScannedExtension;
use gpui::{
AnyElement, App, Bounds, Div, Edges, ElementId, GlobalElementId, InspectorElementId, LayoutId, Pixels, Position, Rgba, Style, TransformationMatrix,
- Window, div, img, prelude::*, px, size, svg,
+ Window, chromium_baseline, div, img, prelude::*, px, size, svg,
};
use serde_json::Value;
@@ -325,13 +325,11 @@ impl Element for Glyph {
fn prepaint(&mut self, _: Option<&GlobalElementId>, _: Option<&InspectorElementId>, _: Bounds<Pixels>, _: &mut LayoutId, _: &mut Window, _: &mut App) {}
- fn paint(&mut self, _: Option<&GlobalElementId>, _: Option<&InspectorElementId>, bounds: Bounds<Pixels>, _: &mut LayoutId, _: &mut (), window: &mut Window, cx: &mut App) {
+ fn paint(&mut self, _: Option<&GlobalElementId>, _: Option<&InspectorElementId>, bounds: Bounds<Pixels>, layout_id: &mut LayoutId, _: &mut (), window: &mut Window, cx: &mut App) {
let Glyph { outline, scale, glyph_size, line_height, width, color } = &*self;
- // shortcut: gpui-fast has no `layout_subpixel_x` (our Wu patch 189efc4c454), so the glyph sits on the snapped origin, up to
- // half a device pixel left of Chromium's; port it with the Chromium layout patches.
- let x = 0.;
+ let x = window.layout_subpixel_x(*layout_id).as_f32();
// An icon font's ascent is 1em, its descent 0.
- let baseline = chromium_baseline(*line_height, *glyph_size, window.scale_factor());
+ let baseline = chromium_baseline(px(*line_height), px(*glyph_size), px(0.), window.scale_factor()).as_f32();
let svg_text = format!(
r#"<svg xmlns="http://www.w3.org/2000/svg" width="{width}" height="{line_height}" viewBox="0 0 {width} {line_height}"><path transform="translate({x} {baseline}) scale({scale} -{scale})" d="{outline}"/></svg>"#
);
@@ -344,12 +342,6 @@ impl Element for Glyph {
}
}
-/// Wu's `chromium_baseline` for a font with no descent: the ascent on a device-px baseline centered in the line.
-fn chromium_baseline(line_height: f32, ascent: f32, scale_factor: f32) -> f32 {
- let ascent = (ascent * scale_factor).round();
- (((line_height * scale_factor - ascent) / 2.).floor() + ascent) / scale_factor
-}
-
pub(crate) fn glyph_outline(face: &ttf_parser::Face, character: char) -> Option<(String, f32)> {
struct SvgPath(String);
impl ttf_parser::OutlineBuilder for SvgPath {
@@ -409,10 +401,10 @@ mod tests {
/// the half leading floored in device px (rounding in px put it 1 device px low in 22px and 24px lines).
#[test]
fn a_glyph_s_baseline_is_laid_out_in_device_pixels() {
- let baseline = |line_height, scale_factor| chromium_baseline(line_height, 19.5, scale_factor);
- assert_eq!(baseline(22., 2.), 20.5);
- assert_eq!(baseline(24., 2.), 21.5);
- assert_eq!(baseline(22., 1.), 21.);
+ let baseline = |line_height, scale_factor| chromium_baseline(px(line_height), px(19.5), px(0.), scale_factor);
+ assert_eq!(baseline(22., 2.), px(20.5));
+ assert_eq!(baseline(24., 2.), px(21.5));
+ assert_eq!(baseline(22., 1.), px(21.));
}
#[test]
diff --git a/native/crates/app/src/workbench/icon_label.rs b/native/crates/app/src/workbench/icon_label.rs
index 9bc2496ae86..4cb37a1f7c1 100644
--- a/native/crates/app/src/workbench/icon_label.rs
+++ b/native/crates/app/src/workbench/icon_label.rs
@@ -3,9 +3,9 @@ use gpui::{Div, div, prelude::*, px};
/// iconlabel.css `.label-description` after a 13px name: `font-size: 0.9em`, `margin-left: 0.5em` of its own size.
/// It is an inline span, so the name's 13px strut sets its line box and baseline.
pub(super) fn label_description() -> Div {
- // shortcut: gpui-fast has no `strut_size` (our Wu patch 189efc4c454), so the line box follows the 11.7px text, not
- // the name's 13px strut; port the strut with the Chromium text patches.
- div().ml(px(5.85)).text_size(px(11.7))
+ let mut description = div().ml(px(5.85)).text_size(px(11.7));
+ description.text_style().strut_size = Some(px(13.).into());
+ description
}
#[cfg(test)]
diff --git a/native/vendor/gpui-fast/crates/gpui/src/elements/div.rs b/native/vendor/gpui-fast/crates/gpui/src/elements/div.rs
index 58e56ffcce2..1a153603abc 100644
--- a/native/vendor/gpui-fast/crates/gpui/src/elements/div.rs
+++ b/native/vendor/gpui-fast/crates/gpui/src/elements/div.rs
@@ -5836,14 +5836,14 @@ mod tests {
_window: &mut Window,
_cx: &mut Context<Self>,
) -> impl IntoElement {
- // 4.25px of padding snaps to 4px in layout, so a 42px child
+ // 4.2px of padding snaps to 4px in layout, so a 42px child
// fits the 50px box exactly.
div().size_full().child(
div()
.id("container")
.h(px(50.))
.w(px(100.))
- .py(px(4.25))
+ .py(px(4.2))
.overflow_y_scroll()
.track_scroll(&self.scroll_handle)
.child(div().w_full().h(px(42.))),
diff --git a/native/vendor/gpui-fast/crates/gpui/src/elements/text.rs b/native/vendor/gpui-fast/crates/gpui/src/elements/text.rs
index a7d97d7d6c9..21deb6f2ecb 100644
--- a/native/vendor/gpui-fast/crates/gpui/src/elements/text.rs
+++ b/native/vendor/gpui-fast/crates/gpui/src/elements/text.rs
@@ -579,7 +579,10 @@ impl Element for StyledText {
/// The Layout for TextElement. This can be used to map indices to pixels and vice versa.
#[derive(Default, Clone)]
-pub struct TextLayout(pub(crate) Rc<RefCell<Option<TextLayoutInner>>>);
+pub struct TextLayout(
+ pub(crate) Rc<RefCell<Option<TextLayoutInner>>>,
+ pub(crate) Rc<Cell<Option<LayoutId>>>,
+);
#[derive(Clone, Copy)]
enum TextPaintPass {
diff --git a/native/vendor/gpui-fast/crates/gpui/src/fast/taffy.rs b/native/vendor/gpui-fast/crates/gpui/src/fast/taffy.rs
index c38929d0bf4..e7705620e43 100644
--- a/native/vendor/gpui-fast/crates/gpui/src/fast/taffy.rs
+++ b/native/vendor/gpui-fast/crates/gpui/src/fast/taffy.rs
@@ -16,8 +16,7 @@ use crate::{
AbsoluteLength, App, Bounds, DefiniteLength, Edges, GridTemplate, Length, Pixels, Point, Size,
Style, Window, size,
util::{
- ceil_to_device_pixel, round_half_toward_zero, round_stroke_to_device_pixel,
- round_to_device_pixel,
+ ceil_to_layout_unit, round_half_up, round_stroke_to_device_pixel,
},
};
use collections::FxHashSet;
@@ -304,7 +303,7 @@ impl TaffyLayoutEngine {
known_dimensions,
available_space,
);
- snap_measured_size_to_device_pixels(measured_size, scale_factor).into()
+ measured_size.map(|d| ceil_to_layout_unit(d.0.max(0.0), scale_factor)).into()
},
)
},
@@ -331,17 +330,17 @@ impl TaffyLayoutEngine {
// 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.
+ // Midpoints round up, as Chromium's LayoutUnit::Round: authored lengths
+ // keep 1/64px, so a 0.25px offset at 2x reaches here as a 0.5 dp edge.
//
// 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
+ // authored absolute lengths go to 1/64 device px 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.
+ // to 1/64 device px, Chromium's LayoutUnit; whole px added up to
+ // 1 dp per leaf along a row (editor tabs drifted right).
//
// 2. Post-layout edge snapping. After Taffy resolves the tree, layout
// relationships such as flex shares, grid tracks, percentages, and
@@ -416,14 +415,25 @@ impl TaffyLayoutEngine {
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),
+ absolute_outer_origin.map(round_half_up),
+ absolute_far.map(round_half_up),
);
let bounds = (snapped_bounds / scale_factor).map(Pixels);
self.absolute_layout_bounds.insert(id, bounds);
bounds
}
+
+ /// How far right of its snapped `layout_bounds` the node's unsnapped origin lies, in px.
+ pub fn subpixel_x(&mut self, id: LayoutId, scale_factor: f32) -> Pixels {
+ self.layout_bounds(id, scale_factor);
+ let origin = self
+ .absolute_outer_origins
+ .get(&id)
+ .expect("layout_bounds caches the absolute origin")
+ .x;
+ Pixels((origin - round_half_up(origin)) / scale_factor)
+ }
}
/// A unique identifier for a layout node, generated when requesting a layout from Taffy
@@ -456,10 +466,6 @@ 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,
@@ -569,7 +575,9 @@ impl ToTaffy<taffy::style::Style> for Style {
impl ToTaffy<f32> for AbsoluteLength {
fn to_taffy(&self, rem_size: Pixels, scale_factor: f32) -> f32 {
- round_to_device_pixel(self.to_pixels(rem_size).0, scale_factor)
+ // Chromium keeps a margin or padding in 1/64px LayoutUnits; only box edges snap, in `layout_bounds`.
+ // A device pixel round here put a 5.85px description margin 0.15px late, on top of the edge snap.
+ ceil_to_layout_unit(self.to_pixels(rem_size).0, scale_factor)
}
}
diff --git a/native/vendor/gpui-fast/crates/gpui/src/fast/tests/text.rs b/native/vendor/gpui-fast/crates/gpui/src/fast/tests/text.rs
index c13c0630b24..286422e11ab 100644
--- a/native/vendor/gpui-fast/crates/gpui/src/fast/tests/text.rs
+++ b/native/vendor/gpui-fast/crates/gpui/src/fast/tests/text.rs
@@ -524,21 +524,22 @@ fn text_laid_out_from_the_cache_paints_the_lines_of_its_box() {
})
.unwrap();
draw(&mut cx, window.into());
- let (lines, bounds, line_height) = window
- .update(&mut cx, |view, _, _| {
+ let (lines, bounds, line_height, scale) = window
+ .update(&mut cx, |view, window, _| {
let layout = view.layout.borrow().clone().unwrap();
(
layout.wrapped_text().lines().count(),
layout.bounds(),
layout.line_height(),
+ window.scale_factor(),
)
})
.unwrap();
assert!(lines > 1, "the text should wrap in its column: {lines}");
- assert_eq!(
- bounds.size.height,
- line_height * lines as f32,
- "frame {frame}: {lines} lines painted in {bounds:?}"
+ // The box snaps to device pixels; the lines keep their fractional height (d066288ea59).
+ assert!(
+ (bounds.size.height - line_height * lines as f32).abs() <= px(0.5 / scale),
+ "frame {frame}: {lines} lines of {line_height:?} painted in {bounds:?}"
);
}
}
diff --git a/native/vendor/gpui-fast/crates/gpui/src/fast/text.rs b/native/vendor/gpui-fast/crates/gpui/src/fast/text.rs
index e7ba98dec0a..5f1cd1dd3f5 100644
--- a/native/vendor/gpui-fast/crates/gpui/src/fast/text.rs
+++ b/native/vendor/gpui-fast/crates/gpui/src/fast/text.rs
@@ -204,13 +204,15 @@ pub(crate) fn layout_text(
cx: &mut App,
) -> LayoutId {
let inputs = measure_inputs(layout, text, runs.unwrap_or_default(), window);
- window.request_carried_measured_layout(
+ let layout_id = window.request_carried_measured_layout(
inputs,
adopt_measurement,
forget_measurement,
measure_text,
cx,
- )
+ );
+ layout.1.set(Some(layout_id));
+ layout_id
}
/// The inputs of text laid out in the text style in effect, keeping its
@@ -223,11 +225,14 @@ fn measure_inputs(
) -> TextMeasureInputs {
let text_style = crate::fast::text_style::text_style(window);
let font_size = text_style.font_size.to_pixels(window.rem_size());
- let line_height = window.pixel_snap(
- text_style
- .line_height
- .to_pixels(font_size.into(), window.rem_size()),
- );
+ // Unsnapped as Chromium's LayoutUnit line boxes: 13 lines of 18.2px end 2.6px lower than 13 snapped to 18px.
+ // The glyphs still snap where `paint_glyph` quantizes their origin.
+ let strut_size = text_style
+ .strut_size
+ .map_or(font_size, |size| size.to_pixels(window.rem_size()));
+ let line_height = text_style
+ .line_height
+ .to_pixels(strut_size.into(), window.rem_size());
TextMeasureInputs {
text,
runs,
@@ -256,6 +261,9 @@ pub(crate) fn prepaint_text(
window: &mut Window,
cx: &mut App,
) {
+ let layout_id = layout.1.get().expect("layout is requested before prepaint");
+ let mut bounds = bounds;
+ bounds.origin.x += window.layout_subpixel_x(layout_id);
if layout.0.borrow().is_none() {
report_unmeasured(
"text reached prepaint unmeasured; measured there as plain text",
@@ -528,7 +536,7 @@ fn measure_text(
for line in &lines {
let line_size = line.size(line_height);
size.height += line_size.height;
- size.width = size.width.max(line_size.width).ceil();
+ size.width = size.width.max(line_size.width);
}
layout.0.borrow_mut().replace(TextLayoutInner {
lines,
diff --git a/native/vendor/gpui-fast/crates/gpui/src/style.rs b/native/vendor/gpui-fast/crates/gpui/src/style.rs
index 23312b15094..45989123579 100644
--- a/native/vendor/gpui-fast/crates/gpui/src/style.rs
+++ b/native/vendor/gpui-fast/crates/gpui/src/style.rs
@@ -480,6 +480,10 @@ pub struct TextStyle {
/// The number of lines to display before truncating the text
pub line_clamp: Option<usize>,
+
+ /// CSS's strut: the parent's font size, which sets the line's height and baseline when this text is an inline
+ /// span with its own `font-size`, so the span sits on the parent's baseline.
+ pub strut_size: Option<AbsoluteLength>,
}
impl Default for TextStyle {
@@ -501,6 +505,7 @@ impl Default for TextStyle {
text_overflow: None,
text_align: TextAlign::default(),
line_clamp: None,
+ strut_size: None,
}
}
}
@@ -552,7 +557,7 @@ impl TextStyle {
/// Returns the rounded line height in pixels.
pub fn line_height_in_pixels(&self, rem_size: Pixels) -> Pixels {
- self.line_height.to_pixels(self.font_size, rem_size).round()
+ self.line_height.to_pixels(self.strut_size.unwrap_or(self.font_size), rem_size).round()
}
/// Convert this text style into a [`TextRun`], for the given length of the text.
diff --git a/native/vendor/gpui-fast/crates/gpui/src/text_system.rs b/native/vendor/gpui-fast/crates/gpui/src/text_system.rs
index 5b0d556091d..df60651f146 100644
--- a/native/vendor/gpui-fast/crates/gpui/src/text_system.rs
+++ b/native/vendor/gpui-fast/crates/gpui/src/text_system.rs
@@ -56,6 +56,19 @@ pub const SUBPIXEL_VARIANTS_Y: u8 = 1;
// Leave enough room below the underline for its stroke while keeping it below the baseline.
const UNDERLINE_DESCENT_OFFSET_FACTOR: f32 = 0.618;
+/// The baseline's offset from the top of a line, as Blink's `FontHeight::AddLeading` lays it out in device px: the
+/// font's ascent and descent rounded, then the half leading above them floored.
+pub fn chromium_baseline(
+ line_height: Pixels,
+ ascent: Pixels,
+ descent: Pixels,
+ scale_factor: f32,
+) -> Pixels {
+ let ascent = (ascent.0 * scale_factor).round();
+ let descent = (descent.0 * scale_factor).round();
+ px((((line_height.0 * scale_factor - ascent - descent) / 2.).floor() + ascent) / scale_factor)
+}
+
/// Returns the vertical offset used to paint an underline within a line.
pub fn underline_y_offset(line_height: Pixels, ascent: Pixels, descent: Pixels) -> Pixels {
let padding_top = (line_height - ascent - descent) / 2.;
diff --git a/native/vendor/gpui-fast/crates/gpui/src/text_system/line.rs b/native/vendor/gpui-fast/crates/gpui/src/text_system/line.rs
index e3019b566f3..ab81af909e5 100644
--- a/native/vendor/gpui-fast/crates/gpui/src/text_system/line.rs
+++ b/native/vendor/gpui-fast/crates/gpui/src/text_system/line.rs
@@ -1,7 +1,7 @@
use crate::{
App, Bounds, DevicePixels, Half, Hsla, LineLayout, Pixels, Point, RenderGlyphParams, Result,
SharedString, StrikethroughStyle, TextAlign, UnderlineStyle, Window, WrapBoundary,
- WrappedLineLayout, black, fill, point, px, size, underline_y_offset,
+ WrappedLineLayout, black, chromium_baseline, fill, point, px, size, underline_y_offset,
};
use derive_more::{Deref, DerefMut};
use smallvec::SmallVec;
@@ -552,8 +552,19 @@ fn paint_line(
wrap_boundaries,
);
window.paint_layer(line_bounds, |window| {
- let padding_top = (line_height - layout.ascent - layout.descent) / 2.;
- let baseline_offset = point(px(0.), padding_top + layout.ascent);
+ let strut = window
+ .text_style()
+ .strut_size
+ .map_or(1., |size| size.to_pixels(window.rem_size()) / layout.font_size);
+ let baseline_offset = point(
+ px(0.),
+ chromium_baseline(
+ line_height,
+ layout.ascent * strut,
+ layout.descent * strut,
+ window.scale_factor(),
+ ),
+ );
let underline_y_offset = underline_y_offset(line_height, layout.ascent, layout.descent);
let mut decoration_runs = decoration_runs.iter();
let mut wraps = wrap_boundaries.iter().peekable();
diff --git a/native/vendor/gpui-fast/crates/gpui/src/text_system/line_layout.rs b/native/vendor/gpui-fast/crates/gpui/src/text_system/line_layout.rs
index b9fb9216ee9..f2c404d2d0f 100644
--- a/native/vendor/gpui-fast/crates/gpui/src/text_system/line_layout.rs
+++ b/native/vendor/gpui-fast/crates/gpui/src/text_system/line_layout.rs
@@ -269,7 +269,8 @@ impl LineLayout {
let next_x = glyphs.peek().map_or(self.width, |(_, _, x)| *x);
let width = next_x - last_boundary_x;
- if width > wrap_width && boundary > last_boundary {
+ // A space past the wrap width hangs, as in Chromium: only the next word wraps.
+ if width > wrap_width && boundary > last_boundary && byte != b' ' {
// When used line_clamp, we should limit the number of lines.
if let Some(max_lines) = max_lines
&& boundaries.len() >= max_lines.saturating_sub(1)
diff --git a/native/vendor/gpui-fast/crates/gpui/src/util.rs b/native/vendor/gpui-fast/crates/gpui/src/util.rs
index 13ee752dadf..7f27ca2228a 100644
--- a/native/vendor/gpui-fast/crates/gpui/src/util.rs
+++ b/native/vendor/gpui-fast/crates/gpui/src/util.rs
@@ -136,9 +136,15 @@ pub(crate) fn round_half_toward_zero_f64(value: f64) -> f64 {
(value.abs() - 0.5).ceil().copysign(value)
}
+/// Chromium's LayoutUnit::Round, floor(x + 0.5): a .5 device px edge moves right or down, as in a web page.
+#[inline]
+pub(crate) fn round_half_up(value: f32) -> f32 {
+ (value + 0.5).floor()
+}
+
#[inline]
pub(crate) fn round_to_device_pixel(logical: f32, scale_factor: f32) -> f32 {
- round_half_toward_zero(logical * scale_factor)
+ round_half_up(logical * scale_factor)
}
#[inline]
@@ -146,7 +152,7 @@ pub(crate) fn round_stroke_to_device_pixel(logical: f32, scale_factor: f32) -> f
if logical == 0.0 {
0.0
} else {
- round_to_device_pixel(logical.max(0.0), scale_factor).max(1.0)
+ round_half_toward_zero(logical.max(0.0) * scale_factor).max(1.0)
}
}
@@ -155,6 +161,12 @@ pub(crate) fn floor_to_device_pixel(logical: f32, scale_factor: f32) -> f32 {
(logical * scale_factor).floor()
}
+/// Chromium's LayoutUnit::FromFloatCeil in device px: LayoutNG keeps 1/64 px sizes and snaps only at paint.
+#[inline]
+pub(crate) fn ceil_to_layout_unit(logical: f32, scale_factor: f32) -> f32 {
+ (logical * scale_factor * 64.).ceil() / 64.
+}
+
#[inline]
pub(crate) fn ceil_to_device_pixel(logical: f32, scale_factor: f32) -> f32 {
(logical * scale_factor).ceil()
@@ -190,8 +202,11 @@ mod tests {
#[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);
+ // Snap uses half-up: 1.0 * 1.5 = 1.5 ties toward 2.0, -0.5 toward 0.0.
+ assert_eq!(round_to_device_pixel(1.0, 1.5), 2.0);
+ assert_eq!(round_to_device_pixel(-0.25, 2.0), 0.0);
+ // A LayoutUnit is 1/64 device px, rounded up.
+ assert_eq!(ceil_to_layout_unit(5.85, 1.0), 375. / 64.);
// 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);
diff --git a/native/vendor/gpui-fast/crates/gpui/src/window.rs b/native/vendor/gpui-fast/crates/gpui/src/window.rs
index cc3d8752754..1406d4305e2 100644
--- a/native/vendor/gpui-fast/crates/gpui/src/window.rs
+++ b/native/vendor/gpui-fast/crates/gpui/src/window.rs
@@ -5940,6 +5940,13 @@ impl Window {
bounds
}
+ /// How far right of its snapped `layout_bounds` the node's LayoutUnit origin lies. Chromium paints text and
+ /// icon glyphs there, positioned horizontally at subpixels, while the boxes around them snap to device pixels.
+ pub fn layout_subpixel_x(&mut self, layout_id: LayoutId) -> Pixels {
+ let scale_factor = self.scale_factor();
+ self.layout_engine.as_mut().unwrap().subpixel_x(layout_id, scale_factor)
+ }
+
/// This method should be called during `prepaint`. You can use
/// the returned [Hitbox] during `paint` or in an event handler
/// to determine whether the inserted hitbox was the topmost.
@@ -10463,18 +10470,18 @@ mod tests {
3.0 => (3, 1),
scale => panic!("unexpected scale {scale}"),
};
+ // Origins round half up (floor(x + 0.5)), strokes half toward zero.
+ let divisor = 4 * denominator;
let snap = |quarters: i32| {
- let scaled = quarters * numerator;
- let divisor = 4 * denominator;
- let rounded =
- scaled.abs() / divisor + i32::from(2 * (scaled.abs() % divisor) > divisor);
- ScaledPixels((scaled.signum() * rounded) as f32)
+ ScaledPixels((2 * quarters * numerator + divisor).div_euclid(2 * divisor) as f32)
};
- let stroke = |quarters| {
+ let stroke = |quarters: i32| {
+ let scaled = quarters * numerator;
+ let rounded = scaled / divisor + i32::from(2 * (scaled % divisor) > divisor);
if quarters == 0 {
ScaledPixels(0.)
} else {
- snap(quarters).max(ScaledPixels(1.))
+ ScaledPixels(rounded as f32).max(ScaledPixels(1.))
}
};