diff --git a/interfaces/ImsdMessages-Wrap.cppm b/interfaces/ImsdMessages-Wrap.cppm index 19e174f..25c6a43 100644 --- a/interfaces/ImsdMessages-Wrap.cppm +++ b/interfaces/ImsdMessages-Wrap.cppm @@ -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(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(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; + + 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& 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 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 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 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> cache; + }; } diff --git a/project.cpp b/project.cpp index dc4f922..2e29ea5 100644 --- a/project.cpp +++ b/project.cpp @@ -135,6 +135,7 @@ extern "C" Configuration CrafterBuildProject(std::span a cfg.AddTest("Number").Dependencies({ Core.get() }); cfg.AddTest("Time").Dependencies({ Core.get() }); + cfg.AddTest("Wrap").Dependencies({ Core.get() }); LintRules::AddRules(cfg); return cfg; diff --git a/tests/Wrap/main.cpp b/tests/Wrap/main.cpp new file mode 100644 index 0000000..99d659a --- /dev/null +++ b/tests/Wrap/main.cpp @@ -0,0 +1,88 @@ +// SPDX-License-Identifier: GPL-3.0-only +// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts® + +// Word wrap and ellipsis over a fixed-advance measure (every code point +// ten pixels), so the expected byte offsets and widths are exact. +import std; +import ImsdMessages; +using namespace ImsdMessages; + +namespace { + +std::int32_t failures = 0; + +void Check(bool ok, std::string_view what) { + std::println("{} {}", ok ? "PASS" : "FAIL", what); + if (!ok) ++failures; +} + +void CheckEqual(std::string_view actual, std::string_view expected, std::string_view what) { + const bool ok = actual == expected; + if (ok) std::println("PASS {}", what); + else std::println("FAIL {} — expected \"{}\", got \"{}\"", what, expected, actual); + if (!ok) ++failures; +} + +} + +std::string Show(const std::vector& lines) { + std::string out; + for (const WrappedLine& l : lines) out += std::format("[{},{}){} ", l.begin, l.end, l.width); + return out; +} + +void CheckLines(const std::vector& actual, const std::vector& expected, std::string_view what) { + const bool ok = actual == expected; + if (ok) std::println("PASS {}", what); + else std::println("FAIL {} — expected {} got {}", what, Show(expected), Show(actual)); + if (!ok) ++failures; +} + +int main() { + WordWrapper wrap([](std::uint32_t, float) { return 10.0f; }); + + CheckLines(wrap.Wrap("hello world", 10, 200), { { 0, 11, 110 } }, "fits on one line"); + CheckLines(wrap.Wrap("hello world", 10, 60), { { 0, 5, 50 }, { 6, 11, 50 } }, "breaks at the space, the space in neither line"); + CheckLines(wrap.Wrap("hello world", 10, 60), { { 0, 5, 50 }, { 7, 12, 50 } }, "a run of spaces is skipped at the break"); + CheckLines(wrap.Wrap("ab cdef", 10, 50), { { 0, 2, 20 }, { 4, 8, 40 } }, "a run of spaces before the overflow goes to neither line"); + CheckLines(wrap.Wrap("abcdef ghi", 10, 60), { { 0, 6, 60 }, { 7, 10, 30 } }, "a split forced at a space starts the next line after it"); + CheckLines(wrap.Wrap("abcdefghij", 10, 35), { { 0, 3, 30 }, { 3, 6, 30 }, { 6, 9, 30 }, { 9, 10, 10 } }, "a long word splits between code points"); + CheckLines(wrap.Wrap("a\nb", 10, 100), { { 0, 1, 10 }, { 2, 3, 10 } }, "a newline is a hard break"); + CheckLines(wrap.Wrap("a\n\nb", 10, 100), { { 0, 1, 10 }, { 2, 2, 0 }, { 3, 4, 10 } }, "an empty line between two newlines"); + CheckLines(wrap.Wrap("ab\n", 10, 50), { { 0, 2, 20 }, { 3, 3, 0 } }, "a text ending in a newline has an empty last line"); + CheckLines(wrap.Wrap("", 10, 100), { { 0, 0, 0 } }, "empty text is one empty line"); + CheckLines(wrap.Wrap("well-known word", 10, 60), { { 0, 5, 50 }, { 5, 10, 50 }, { 11, 15, 40 } }, "a hyphen is a break opportunity that stays on its line"); + CheckLines(wrap.Wrap("héllo wörld", 10, 60), { { 0, 6, 50 }, { 7, 13, 50 } }, "multi-byte code points count once"); + CheckLines(wrap.Wrap("x", 10, 5), { { 0, 1, 10 } }, "a single code point wider than the line is kept"); + CheckLines(wrap.Wrap("ab cd ef", 10, 50), { { 0, 5, 50 }, { 6, 8, 20 } }, "a space that overflows ends the line after the words that fit"); + CheckLines(wrap.Wrap("abcde ", 10, 50), { { 0, 5, 50 } }, "a trailing space that overflows opens no empty line"); + CheckLines(wrap.Wrap("abcd ", 10, 50), { { 0, 4, 40 } }, "nor does a run of them"); + CheckLines(wrap.Wrap(" \nabc", 10, 30), { { 0, 3, 30 }, { 6, 9, 30 } }, "a run of spaces wider than the line, before a newline: the split forced at a space opens no blank line either"); + CheckLines(wrap.Wrap("x\n ", 10, 30), { { 0, 1, 10 }, { 2, 5, 30 } }, "nor at the text's end"); + CheckLines(wrap.Wrap("abcde \nx", 10, 50), { { 0, 5, 50 }, { 7, 8, 10 } }, "a space that overflows before a newline leaves no blank line between the two"); + CheckLines(wrap.Wrap("abcde \n", 10, 50), { { 0, 5, 50 }, { 7, 7, 0 } }, "a text ending in a newline keeps its empty last line"); + CheckLines(wrap.Wrap(" abcdef", 10, 30), { { 0, 3, 30 }, { 3, 6, 30 }, { 6, 7, 10 } }, "a leading space is no break: no empty first line, the space stays on its line"); + CheckLines(wrap.Wrap("x\n abcd", 10, 30), { { 0, 1, 10 }, { 2, 5, 30 }, { 5, 7, 20 } }, "nor is a space right after a newline"); + CheckLines(wrap.Wrap(" abcdef", 10, 30), { { 0, 3, 30 }, { 3, 6, 30 }, { 6, 8, 20 } }, "nor is a run of them: the line opens with its first word, the spaces before it on that line"); + CheckLines(wrap.Wrap("x\n abcd", 10, 30), { { 0, 1, 10 }, { 2, 5, 30 }, { 5, 8, 30 } }, "the same after a newline"); + + const std::vector& first = wrap.Wrap("cached text", 10, 60); + const std::vector& again = wrap.Wrap("cached text", 10, 60); + Check(&first == &again, "the same text, width and size hit the cache"); + const std::size_t before = wrap.CacheSize(); + wrap.Wrap("cached text", 10, 70); + Check(wrap.CacheSize() == before + 1, "another width is another entry"); + + CheckEqual(wrap.Ellipsize("hello world", 10, 200), "hello world", "ellipsis: fits"); + CheckEqual(wrap.Ellipsize("hello world", 10, 60), "hello…", "ellipsis: cut with room for the mark"); + CheckEqual(wrap.Ellipsize("hello world", 10, 110), "hello world", "ellipsis: exactly fits"); + CheckEqual(wrap.Ellipsize("x", 10, 5), "…", "ellipsis: nothing fits"); + CheckEqual(wrap.Ellipsize("line one\nline two", 10, 200), "line one…", "ellipsis: a preview stops at the first newline"); + + std::size_t i = 0; + Check(DecodeUtf8("é", i) == 0xE9 && i == 2, "DecodeUtf8 of a two-byte sequence"); + i = 0; + Check(DecodeUtf8("\xff", i) == 0xFFFD && i == 1, "DecodeUtf8 of a stray byte consumes it"); + + return failures == 0 ? 0 : 1; +}