Wrap: word wrap and ellipsis over a measure function

Crafter.Graphics shapes one line at a time and drops newlines, so the app
breaks text itself: a greedy wrap with breaks after spaces and hyphens
(a space that itself overflows ends the line after the words that fit,
and opens no line of its own when it ends the text or a newline
follows; one at a line's start is no break at all, nor is a run of
them: a break is recorded only once the line holds a word, and a run of
spaces wider than the line splits like a word, with the same rule at the
text's end and before a newline), hard breaks at
newlines, over-long words split between code points, and
the run of spaces where a line wraps left out of both lines. Results are
cached per (text, width, size). The measure is a function, so the caller
supplies the advances; the tests use a constant ten-pixel advance.

Tested: tests/Wrap on a ten-pixel monospace measure, a leading run of
spaces among the cases.
This commit is contained in:
Jorijn van der Graaf 2026-10-17 23:25:41 +02:00
commit 335b27b72d
Signed by: jorijnvdgraaf
GPG key ID: 2937E59CDCC1BCFB
3 changed files with 288 additions and 0 deletions

View file

@ -1,8 +1,207 @@
// SPDX-License-Identifier: GPL-3.0-only
// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
/*
ImsdMessages:Wrap — word wrap and ellipsis. The window library shapes one
line at a time and knows no line breaks, so the app breaks the text
itself, with the font's advances supplied as a function; the tests pass a
constant ten-pixel advance.
*/
export module ImsdMessages:Wrap;
import std;
export namespace ImsdMessages {
// The code point at text[i], advancing i past it: 0 at the end, U+FFFD
// for a malformed sequence (at least one byte consumed, so a loop always
// ends).
std::uint32_t DecodeUtf8(std::string_view text, std::size_t& i) {
if (i >= text.size()) return 0;
const std::uint8_t b0 = static_cast<std::uint8_t>(text[i]);
if (b0 < 0x80) {
++i;
return b0;
}
std::size_t extra = 0;
std::uint32_t cp = 0;
if ((b0 & 0xE0) == 0xC0) {
extra = 1;
cp = b0 & 0x1F;
} else if ((b0 & 0xF0) == 0xE0) {
extra = 2;
cp = b0 & 0x0F;
} else if ((b0 & 0xF8) == 0xF0) {
extra = 3;
cp = b0 & 0x07;
} else {
++i;
return 0xFFFD;
}
++i;
for (std::size_t k = 0; k < extra; ++k) {
if (i >= text.size()) return 0xFFFD;
const std::uint8_t b = static_cast<std::uint8_t>(text[i]);
if ((b & 0xC0) != 0x80) return 0xFFFD;
cp = (cp << 6) | (b & 0x3Fu);
++i;
}
return cp;
}
// The advance of a code point at a size, in pixels.
using MeasureFn = std::function<float(std::uint32_t codepoint, float sizePx)>;
struct WrappedLine {
std::size_t begin = 0; // byte offsets into the text
std::size_t end = 0; // exclusive; a space or a newline broken at is not part of the line, a hyphen is
float width = 0;
friend bool operator==(const WrappedLine&, const WrappedLine&) = default;
};
// Greedy word wrap: a break after a space or a hyphen, a hard break at
// '\n', a word wider than the line split between code points; the run of
// spaces where a line wraps goes to neither line. Results are cached per
// (text, width, size).
class WordWrapper {
public:
static constexpr std::size_t cacheLimit = 512;
explicit WordWrapper(MeasureFn measure) : measure(std::move(measure)) {}
const std::vector<WrappedLine>& Wrap(std::string_view text, float sizePx, float maxWidthPx) {
const CacheKey key{ std::string(text), std::lround(maxWidthPx), std::lround(sizePx * 4) };
if (const auto it = cache.find(key); it != cache.end()) return it->second;
// A bounded cache without bookkeeping: on overflow everything goes
// and the next frame refills what it needs.
if (cache.size() >= cacheLimit) cache.clear();
return cache.emplace(key, Compute(text, sizePx, maxWidthPx)).first->second;
}
// The text that fits in the width, "…" appended when it was cut.
std::string Ellipsize(std::string_view text, float sizePx, float maxWidthPx) const {
const float ellipsis = measure(0x2026, sizePx);
float width = 0;
std::size_t i = 0;
std::size_t fit = 0; // the longest prefix that leaves room for the ellipsis
bool cut = false;
while (i < text.size()) {
const std::size_t at = i;
const std::uint32_t cp = DecodeUtf8(text, i);
if (cp == '\n') {
cut = true;
i = at;
break;
}
width += measure(cp, sizePx);
if (width > maxWidthPx) {
cut = true;
i = at;
break;
}
if (width + ellipsis <= maxWidthPx) fit = i;
}
if (!cut) return std::string(text);
return std::format("{}…", text.substr(0, fit));
}
std::size_t CacheSize() const noexcept { return cache.size(); }
private:
struct CacheKey {
std::string text;
std::int64_t width;
std::int64_t size;
friend auto operator<=>(const CacheKey&, const CacheKey&) = default;
};
std::vector<WrappedLine> Compute(std::string_view text, float sizePx, float maxWidthPx) const {
struct Break {
std::size_t end; // where the line ends
std::size_t next; // where the next line begins
float width; // the line's width up to `end`
};
std::vector<WrappedLine> lines;
std::size_t lineBegin = 0;
float lineWidth = 0;
bool lineHasText = false; // a non-space code point since lineBegin: before the first, a space is no break and opens no line
std::optional<Break> lastBreak;
std::size_t i = 0;
while (i < text.size()) {
const std::size_t at = i;
const std::uint32_t cp = DecodeUtf8(text, i);
if (cp == '\n') {
lines.push_back({ lineBegin, at, lineWidth });
lineBegin = i;
lineWidth = 0;
lineHasText = false;
lastBreak.reset();
continue;
}
const float w = measure(cp, sizePx);
if (lineWidth + w > maxWidthPx && at > lineBegin) {
if (cp == ' ' && lineHasText) {
// The space itself overflows: the line ends before
// it — before the run of spaces it continues — with
// every word that fit.
const bool run = lastBreak && lastBreak->next == at;
lines.push_back({ lineBegin, run ? lastBreak->end : at, run ? lastBreak->width : lineWidth });
lineBegin = i;
while (lineBegin < text.size() && text[lineBegin] == ' ') ++lineBegin;
// Spaces that end the text, or that a hard break
// follows, hang off the line just ended and open
// no line of their own.
if (lineBegin == text.size()) return lines;
if (text[lineBegin] == '\n') ++lineBegin;
lineWidth = 0;
lineHasText = false;
i = lineBegin;
lastBreak.reset();
continue;
}
if (lastBreak) {
lines.push_back({ lineBegin, lastBreak->end, lastBreak->width });
lineBegin = lastBreak->next;
// The next line starts at its first non-space, which may
// be past the space being looked at right now.
while (lineBegin < text.size() && text[lineBegin] == ' ') ++lineBegin;
i = std::max(at, lineBegin);
lineWidth = at > lineBegin ? Measure(text.substr(lineBegin, at - lineBegin), sizePx) : 0;
lineHasText = at > lineBegin;
} else {
lines.push_back({ lineBegin, at, lineWidth });
lineBegin = at;
// A split forced at a space starts the next line
// after the spaces too — and, as above, spaces that
// end the text or that a hard break follows open no
// line of their own.
while (lineBegin < text.size() && text[lineBegin] == ' ') ++lineBegin;
if (lineBegin == text.size()) return lines;
if (text[lineBegin] == '\n') ++lineBegin;
lineWidth = 0;
lineHasText = false;
i = lineBegin;
}
lastBreak.reset();
continue;
}
lineWidth += w;
if (cp != ' ') lineHasText = true;
// A run of spaces is one break: the line ends before the run.
if (cp == ' ' && lastBreak && lastBreak->next == at) lastBreak->next = i;
else if (cp == ' ' && lineHasText) lastBreak = Break{ at, i, lineWidth - w }; // not before a line's first word: the line before such a break would be empty
else if (cp == '-') lastBreak = Break{ i, i, lineWidth };
}
lines.push_back({ lineBegin, text.size(), lineWidth });
return lines;
}
float Measure(std::string_view text, float sizePx) const {
float width = 0;
std::size_t i = 0;
while (i < text.size()) width += measure(DecodeUtf8(text, i), sizePx);
return width;
}
MeasureFn measure;
std::map<CacheKey, std::vector<WrappedLine>> cache;
};
}