Portals0.7.0 · dev (544a5c68c72e · 2026-11-28 UTC)
Loading...
Searching...
No Matches
scroll_geometry.hpp
1// Copyright (c) 2026 ttldtor.
2// SPDX-License-Identifier: BSL-1.0
3#pragma once
4
5#include <algorithm>
6#include <bit>
7#include <cstdint>
8#include <expected>
9#include <limits>
10#include <portals/frame.hpp>
11#include <portals/widget_types.hpp>
12
13namespace portals {
19
21enum class ScrollBarPolicy {
23 AUTO,
25};
26
33
36 std::uint64_t raster{};
37 double fraction{};
38};
39
42 std::uint64_t extent{};
43 std::uint64_t viewport{};
44};
45
48 std::uint64_t width{};
49 std::uint64_t height{};
50};
51
54 std::uint64_t maximum{};
55 std::uint64_t count{1};
56};
57
63[[nodiscard]] constexpr ScrollRange scrollRange(ScrollAxisMetrics metrics) noexcept {
64 const auto maximum =
65 metrics.viewport != 0 && metrics.extent > metrics.viewport ? metrics.extent - metrics.viewport : 0;
66
67 return {maximum, maximum + 1};
68}
69
74[[nodiscard]] constexpr bool validScrollOffset(ScrollOffset offset) noexcept {
75 return offset.fraction >= 0 && offset.fraction < 1;
76}
77
83[[nodiscard]] constexpr std::uint64_t scrollPageStep(std::uint64_t viewport, std::uint64_t overlap = 1) noexcept {
84 if (viewport == 0) {
85 return 0;
86 }
87
88 return viewport > overlap ? viewport - overlap : 1;
89}
90
91namespace detail {
94 std::uint64_t quotient{};
95 std::uint64_t remainder{};
96};
97
98// Exact a*b/d for a<=d and d>0. A quotient/remainder recurrence avoids a wide product.
99// Every prefix quotient is bounded by that prefix of b; doubled remainders use subtraction.
100constexpr ScrollDivision scrollMultiplyDivide(std::uint64_t a, std::uint64_t b, std::uint64_t d) noexcept {
101 if (a == d) {
102 return {b, 0};
103 }
104
105 ScrollDivision result;
106
107 for (int bit = 63; bit >= 0; --bit) {
108 result.quotient *= 2;
109
110 if (result.remainder >= d - result.remainder) {
111 result.remainder -= d - result.remainder;
112 ++result.quotient;
113 } else {
114 result.remainder += result.remainder;
115 }
116
117 if (((b >> bit) & 1) != 0) {
118 if (result.remainder >= d - a) {
119 result.remainder -= d - a;
120 ++result.quotient;
121 } else {
122 result.remainder += a;
123 }
124 }
125 }
126
127 return result;
128}
129
130// Preserve floor(fraction*units) exactly from binary64, including subnormals.
131constexpr std::uint64_t scrollFractionUnits(double fraction, std::uint64_t units) noexcept {
132 static_assert(std::numeric_limits<double>::is_iec559 && std::numeric_limits<double>::digits == 53);
133 constexpr std::uint32_t MANTISSA_BITS = 52;
134 constexpr std::uint32_t EXPONENT_BIAS = 1023;
135 constexpr std::uint64_t EXPONENT_MASK = 0x7ff;
136 constexpr auto INTEGER_BITS = std::numeric_limits<std::uint64_t>::digits;
137 const auto bits = std::bit_cast<std::uint64_t>(fraction);
138 const auto exponent = static_cast<std::uint32_t>((bits >> MANTISSA_BITS) & EXPONENT_MASK);
139 auto mantissa = bits & ((std::uint64_t{1} << MANTISSA_BITS) - 1);
140 const auto shift = exponent ? MANTISSA_BITS + EXPONENT_BIAS - exponent : MANTISSA_BITS + EXPONENT_BIAS - 1;
141
142 if (exponent != 0) {
143 mantissa |= std::uint64_t{1} << MANTISSA_BITS;
144 }
145
146 const auto divisionShift = std::min(shift, static_cast<std::uint32_t>(INTEGER_BITS - 1));
147 const auto remainingShift = shift - divisionShift;
148
149 if (remainingShift >= INTEGER_BITS) {
150 return 0;
151 }
152
153 return scrollMultiplyDivide(mantissa, units, std::uint64_t{1} << divisionShift).quotient >> remainingShift;
154}
155
156// Position and travel share arbitrary integral units; the logical raster remains exact.
157[[nodiscard]] constexpr ScrollOffset preciseScrollOffsetForThumb(std::uint64_t position, std::uint64_t travel,
158 std::uint64_t maximum) noexcept {
159 if (travel == 0 || maximum == 0) {
160 return {};
161 }
162
163 const auto value = scrollMultiplyDivide(std::min(position, travel), maximum, travel);
164 constexpr double MAXIMUM_FRACTION = 0x1.fffffffffffffp-1;
165 const auto fraction = static_cast<double>(value.remainder) / static_cast<double>(travel);
166
167 // Rounded division can reach one; do not carry it into the exact integral quotient.
168 return {value.quotient, std::min(fraction, MAXIMUM_FRACTION)};
169}
170} // namespace detail
171
174 std::int32_t start{};
175 std::int32_t length{};
176 std::int32_t travel{};
177};
178
187[[nodiscard]] constexpr std::expected<ScrollThumb, TreeError> scrollThumb(ScrollAxisMetrics metrics,
188 std::uint64_t offset,
189 std::int32_t trackLength,
190 std::int32_t minimumThumb = 1) noexcept {
191 if (trackLength < 0 || minimumThumb <= 0) {
192 return std::unexpected(TreeError::INVALID_ARGUMENT);
193 }
194
195 if (trackLength == 0) {
196 return ScrollThumb{};
197 }
198
199 const auto range = scrollRange(metrics);
200
201 if (range.maximum == 0) {
202 return ScrollThumb{0, trackLength, 0};
203 }
204
205 const auto proportional = detail::scrollMultiplyDivide(std::min(metrics.viewport, metrics.extent),
206 static_cast<std::uint64_t>(trackLength), metrics.extent);
207 const auto length =
208 std::clamp(static_cast<std::int32_t>(proportional.quotient), std::min(minimumThumb, trackLength), trackLength);
209 const auto travel = trackLength - length;
210 const auto start =
211 detail::scrollMultiplyDivide(std::min(offset, range.maximum), static_cast<std::uint64_t>(travel), range.maximum);
212
213 return ScrollThumb{static_cast<std::int32_t>(start.quotient), length, travel};
214}
215
218 std::int64_t startEighths{};
219 std::int64_t lengthEighths{};
220 std::int64_t travelEighths{};
221};
222
231[[nodiscard]] constexpr std::expected<ScrollFractionalThumb, TreeError>
232scrollFractionalThumb(ScrollAxisMetrics metrics, ScrollOffset offset, std::int32_t trackLength,
233 std::int32_t minimumThumb = 1) noexcept {
234 if (!validScrollOffset(offset) || trackLength < 0 || minimumThumb <= 0) {
235 return std::unexpected(TreeError::INVALID_ARGUMENT);
236 }
237 if (trackLength == 0) {
238 return ScrollFractionalThumb{};
239 }
240 constexpr std::uint64_t EIGHTHS_PER_CELL = 8;
241 const auto maximum = scrollRange(metrics).maximum;
242 const auto track = static_cast<std::uint64_t>(trackLength) * EIGHTHS_PER_CELL;
243 if (maximum == 0) {
244 return ScrollFractionalThumb{0, static_cast<std::int64_t>(track), 0};
245 }
246 const auto proportional =
247 detail::scrollMultiplyDivide(std::min(metrics.viewport, metrics.extent), track, metrics.extent);
248 const auto minimum = static_cast<std::uint64_t>(std::min(minimumThumb, trackLength)) * EIGHTHS_PER_CELL;
249 const auto length = static_cast<std::int64_t>(std::clamp(proportional.quotient, minimum, track));
250 const auto travel = track - static_cast<std::uint64_t>(length);
251 if (maximum == 0 || travel == 0) {
252 return ScrollFractionalThumb{0, length, static_cast<std::int64_t>(travel)};
253 }
254 if (offset.raster >= maximum) {
255 return ScrollFractionalThumb{static_cast<std::int64_t>(travel), length, static_cast<std::int64_t>(travel)};
256 }
257 const auto position = detail::scrollMultiplyDivide(offset.raster, travel, maximum);
258 const auto fraction = detail::scrollFractionUnits(offset.fraction, travel);
259 const auto remainder = fraction % maximum;
260 // The discarded fractional part is <1; the saved integral remainder retains every possible carry.
261 const auto start = position.quotient + fraction / maximum + (position.remainder >= maximum - remainder ? 1 : 0);
262 return ScrollFractionalThumb{static_cast<std::int64_t>(start), length, static_cast<std::int64_t>(travel)};
263}
264
272[[nodiscard]] constexpr std::expected<std::uint64_t, TreeError>
273scrollOffsetForThumb(std::int64_t position, std::int32_t travel, std::uint64_t maximum) noexcept {
274 if (travel < 0) {
275 return std::unexpected(TreeError::INVALID_ARGUMENT);
276 }
277
278 if (position <= 0 || travel == 0 || maximum == 0) {
279 return 0;
280 }
281
282 if (position >= travel) {
283 return maximum;
284 }
285
286 const auto denominator = static_cast<std::uint64_t>(travel);
287 auto value = detail::scrollMultiplyDivide(static_cast<std::uint64_t>(position), maximum, denominator);
288
289 if (value.remainder > denominator - value.remainder) {
290 ++value.quotient;
291 }
292
293 return value.quotient;
294}
295
304
308 std::int32_t length{};
309};
310
326
336[[nodiscard]] constexpr std::expected<ScrollAreaGeometry, TreeError>
337solveScrollLayout(CellSize allocation, ScrollExtent extent, ScrollLayoutOptions options = {}) noexcept {
338 const auto validPolicy = [](ScrollBarPolicy policy) {
339 return policy == ScrollBarPolicy::NEVER || policy == ScrollBarPolicy::AUTO || policy == ScrollBarPolicy::ALWAYS;
340 };
341
342 if (!validPolicy(options.horizontal) || !validPolicy(options.vertical) ||
343 (options.placement != ScrollPlacement::RESERVED && options.placement != ScrollPlacement::OVERLAY &&
344 options.placement != ScrollPlacement::ON_FRAME) ||
345 (options.placement == ScrollPlacement::ON_FRAME &&
346 (!options.frame || (options.horizontal != ScrollBarPolicy::NEVER && !options.frameSides.bottom) ||
347 (options.vertical != ScrollBarPolicy::NEVER && !options.frameSides.right)))) {
348 return std::unexpected(TreeError::INVALID_ARGUMENT);
349 }
350
351 const auto width = std::max(allocation.width, 0);
352 const auto height = std::max(allocation.height, 0);
353 const auto padding = options.frame ? options.frameSides.insets() : LayoutPadding{};
354 const auto innerWidth = std::max(width - padding.left - padding.right, 0);
355 const auto innerHeight = std::max(height - padding.top - padding.bottom, 0);
356 ScrollAreaGeometry result;
357
358 result.viewportOrigin = {std::min(width, padding.left), std::min(height, padding.top)};
359 result.horizontalBar = options.horizontal == ScrollBarPolicy::ALWAYS;
360 result.verticalBar = options.vertical == ScrollBarPolicy::ALWAYS;
361
362 const auto viewport = [&] {
363 return CellSize{std::max(innerWidth - (result.verticalBar ? 1 : 0), 0),
364 std::max(innerHeight - (result.horizontalBar ? 1 : 0), 0)};
365 };
366
367 // Start from forced bars on every solve. Monotone additions find the least fixed point.
368 for (int pass = 0; pass < 3; ++pass) {
369 const auto visible =
370 options.placement == ScrollPlacement::RESERVED ? viewport() : CellSize{innerWidth, innerHeight};
371
372 result.horizontalBar |=
373 options.horizontal == ScrollBarPolicy::AUTO && extent.width > static_cast<std::uint64_t>(visible.width);
374 result.verticalBar |=
375 options.vertical == ScrollBarPolicy::AUTO && extent.height > static_cast<std::uint64_t>(visible.height);
376 }
377
378 result.viewport = options.placement == ScrollPlacement::RESERVED ? viewport() : CellSize{innerWidth, innerHeight};
379 result.childClipSize = options.placement == ScrollPlacement::ON_FRAME ? result.viewport : viewport();
380
381 if (options.placement == ScrollPlacement::ON_FRAME) {
382 // Opposite sides sharing a collapsed row/column retain the legacy empty-track behavior.
383 // A single bottom or right side can still own that physical row or column.
384 if (result.horizontalBar && innerWidth != 0 && height > padding.top) {
385 result.horizontal = {{padding.left, height - 1}, innerWidth};
386 }
387
388 if (result.verticalBar && innerHeight != 0 && width > padding.left) {
389 result.vertical = {{width - 1, padding.top}, innerHeight};
390 }
391
392 return result;
393 }
394
395 if (result.horizontalBar && innerHeight != 0 && result.childClipSize.width != 0) {
396 result.horizontal = {{result.viewportOrigin.x, result.viewportOrigin.y + innerHeight - 1},
397 result.childClipSize.width};
398 }
399
400 if (result.verticalBar && innerWidth != 0 && result.childClipSize.height != 0) {
401 result.vertical = {{result.viewportOrigin.x + innerWidth - 1, result.viewportOrigin.y},
402 result.childClipSize.height};
403 }
404
405 result.hasCorner = result.horizontalBar && result.verticalBar && innerWidth != 0 && innerHeight != 0;
406
407 if (result.hasCorner) {
408 result.corner = {result.viewportOrigin.x + innerWidth - 1, result.viewportOrigin.y + innerHeight - 1};
409 }
410
411 return result;
412}
413} // namespace portals
Public Portals API.
Definition action.hpp:8
constexpr ScrollRange scrollRange(ScrollAxisMetrics metrics) noexcept
Compute an exact range without unsigned subtraction or addition overflow.
Definition scroll_geometry.hpp:63
ScrollBarPolicy
Presence policy, independent of whether the content can scroll.
Definition scroll_geometry.hpp:21
@ NEVER
Do not allocate or paint a bar.
Definition scroll_geometry.hpp:22
@ AUTO
Show a bar only when its logical extent exceeds the viewport.
Definition scroll_geometry.hpp:23
@ ALWAYS
Show a bar even when its thumb cannot move.
Definition scroll_geometry.hpp:24
constexpr std::expected< ScrollAreaGeometry, TreeError > solveScrollLayout(CellSize allocation, ScrollExtent extent, ScrollLayoutOptions options={}) noexcept
Solve both bar policies together without cross-frame oscillation.
Definition scroll_geometry.hpp:337
ScrollPlacement
Explicit relationship between bars, content and an optional frame.
Definition scroll_geometry.hpp:28
@ OVERLAY
Bars obscure edge cells of the unchanged logical viewport.
Definition scroll_geometry.hpp:30
@ ON_FRAME
Bars occupy the right/bottom frame lines, excluding corners.
Definition scroll_geometry.hpp:31
@ RESERVED
Bars occupy one-cell gutters outside the logical viewport.
Definition scroll_geometry.hpp:29
constexpr std::uint64_t scrollPageStep(std::uint64_t viewport, std::uint64_t overlap=1) noexcept
Compute one page movement using guarded unsigned subtraction.
Definition scroll_geometry.hpp:83
constexpr std::expected< ScrollThumb, TreeError > scrollThumb(ScrollAxisMetrics metrics, std::uint64_t offset, std::int32_t trackLength, std::int32_t minimumThumb=1) noexcept
Map exact logical position to a thumb without a floating-point index round trip.
Definition scroll_geometry.hpp:187
constexpr bool validScrollOffset(ScrollOffset offset) noexcept
Validate an offset remainder without losing its integral index.
Definition scroll_geometry.hpp:74
ScrollAxis
Logical scrolling axis; X increases right and Y increases down.
Definition scroll_geometry.hpp:15
@ VERTICAL
Rows.
Definition scroll_geometry.hpp:17
@ HORIZONTAL
Columns.
Definition scroll_geometry.hpp:16
constexpr std::expected< std::uint64_t, TreeError > scrollOffsetForThumb(std::int64_t position, std::int32_t travel, std::uint64_t maximum) noexcept
Inverse thumb mapping, rounded to nearest integer with ties toward the start.
Definition scroll_geometry.hpp:273
constexpr std::expected< ScrollFractionalThumb, TreeError > scrollFractionalThumb(ScrollAxisMetrics metrics, ScrollOffset offset, std::int32_t trackLength, std::int32_t minimumThumb=1) noexcept
Map an exact logical position to eighth-cell thumb placement.
Definition scroll_geometry.hpp:232
@ INVALID_ARGUMENT
An option, enum value or operation argument is invalid.
Definition widget_types.hpp:27
An owning value in terminal columns/rows, x right and y down.
Definition geometry.hpp:24
An owning available extent in terminal columns/rows.
Definition geometry.hpp:44
std::int32_t height
Available number of rows, possibly negative before normalization.
Definition geometry.hpp:48
std::int32_t width
Available number of columns, possibly negative before normalization.
Definition geometry.hpp:46
Present frame sides, also defining one-cell content insets.
Definition frame.hpp:19
Owning nonnegative padding in terminal cells.
Definition layout.hpp:185
Owning normalized placement result; every represented cell lies in the allocation....
Definition scroll_geometry.hpp:315
bool verticalBar
Policy result, even when a tiny allocation leaves no track.
Definition scroll_geometry.hpp:324
CellPoint viewportOrigin
Local content origin after the optional frame inset.
Definition scroll_geometry.hpp:316
CellSize childClipSize
Nonnegative descendant clip size at viewportOrigin.
Definition scroll_geometry.hpp:318
CellPoint corner
Shared gutter/overlay corner when hasCorner is true.
Definition scroll_geometry.hpp:321
bool hasCorner
False for ON_FRAME, whose corners belong to its outline.
Definition scroll_geometry.hpp:322
ScrollTrack horizontal
Bottom horizontal track, excluding corners.
Definition scroll_geometry.hpp:319
bool horizontalBar
Policy result, even when a tiny allocation leaves no track.
Definition scroll_geometry.hpp:323
CellSize viewport
Nonnegative logical viewport extent.
Definition scroll_geometry.hpp:317
ScrollTrack vertical
Right vertical track, excluding corners.
Definition scroll_geometry.hpp:320
Owning one-axis logical metrics, independent of materialized content.
Definition scroll_geometry.hpp:41
std::uint64_t extent
Total logical cells.
Definition scroll_geometry.hpp:42
std::uint64_t viewport
Visible logical cells; zero admits only position zero.
Definition scroll_geometry.hpp:43
Logical content extent; ordinary retained layout still has int32 cell bounds.
Definition scroll_geometry.hpp:47
std::uint64_t height
Rows.
Definition scroll_geometry.hpp:49
std::uint64_t width
Columns.
Definition scroll_geometry.hpp:48
Owning thumb interval in eighths of a track cell; no references or invalidation.
Definition scroll_geometry.hpp:217
std::int64_t startEighths
Inclusive start, relative to the trimmed track.
Definition scroll_geometry.hpp:218
std::int64_t travelEighths
Exact maximum start, including the endpoint.
Definition scroll_geometry.hpp:220
std::int64_t lengthEighths
Proportional length quantized directly to eighths of a cell.
Definition scroll_geometry.hpp:219
Value-only placement inputs, without a frame painter or widget lifetime.
Definition scroll_geometry.hpp:297
FrameSides frameSides
Present frame sides; ignored when frame is false.
Definition scroll_geometry.hpp:302
bool frame
One-cell frame inset; ON_FRAME requires true.
Definition scroll_geometry.hpp:301
ScrollPlacement placement
Explicit bar placement.
Definition scroll_geometry.hpp:300
ScrollBarPolicy vertical
Vertical presence policy.
Definition scroll_geometry.hpp:299
ScrollBarPolicy horizontal
Horizontal presence policy.
Definition scroll_geometry.hpp:298
Owning exact integral position and sub-cell remainder; no affinity or invalidation.
Definition scroll_geometry.hpp:35
std::uint64_t raster
Exact logical cell index, including indices above 2^53.
Definition scroll_geometry.hpp:36
double fraction
Finite remainder in [0,1).
Definition scroll_geometry.hpp:37
Derived viewport-start range, preserving the existing ScrollState count contract.
Definition scroll_geometry.hpp:53
std::uint64_t count
Number of permitted integral starts; always positive.
Definition scroll_geometry.hpp:55
std::uint64_t maximum
Inclusive maximum integral offset; no fraction at this endpoint.
Definition scroll_geometry.hpp:54
Owning one-cell-track thumb geometry; values are relative to the track start.
Definition scroll_geometry.hpp:173
std::int32_t length
Occupied cells, zero only for an empty track.
Definition scroll_geometry.hpp:175
std::int32_t travel
Maximum thumb-start cell; zero disables dragging.
Definition scroll_geometry.hpp:176
std::int32_t start
First occupied track cell.
Definition scroll_geometry.hpp:174
Owning local one-cell track; axis determines whether length is rows or columns.
Definition scroll_geometry.hpp:306
std::int32_t length
Nonnegative track cells, excluding any corner.
Definition scroll_geometry.hpp:308
CellPoint origin
Local first track cell; zero for an absent track.
Definition scroll_geometry.hpp:307
Exact quotient and remainder used by bounded scroll geometry arithmetic.
Definition scroll_geometry.hpp:93
std::uint64_t quotient
Integral quotient of the bounded product division.
Definition scroll_geometry.hpp:94
std::uint64_t remainder
Nonnegative remainder, strictly smaller than the divisor.
Definition scroll_geometry.hpp:95