diff --git a/src/text/paragraph.cpp b/src/text/paragraph.cpp index 79fa5f8..a42d694 100644 --- a/src/text/paragraph.cpp +++ b/src/text/paragraph.cpp @@ -546,6 +546,8 @@ Paragraph Typesetter::set(const std::vector& spans, float ascent = strut.ascent; float descent = strut.descent; size_t end = range.end; + // A line that ends its paragraph is not justified, as in print. + const bool endsAtBreak = end > range.begin && clusters[end - 1].newline; // Trailing spaces hang past the line's end. while (end > range.begin && (clusters[end - 1].space || clusters[end - 1].newline)) { @@ -630,7 +632,8 @@ Paragraph Typesetter::set(const std::vector& spans, } else if (options.align == ParagraphOptions::Align::End) { pen = options.maxWidth - line.width; } else if (options.align == ParagraphOptions::Align::Justify && - !lastLine && std::isfinite(options.maxWidth)) { + !lastLine && !endsAtBreak && + std::isfinite(options.maxWidth)) { const auto spaces = std::count_if( placed.begin(), placed.end(), [](const Cluster& cluster) { return cluster.space; }); diff --git a/tests/paragraph_test.cpp b/tests/paragraph_test.cpp index 20a2658..9d5a1e4 100644 --- a/tests/paragraph_test.cpp +++ b/tests/paragraph_test.cpp @@ -251,6 +251,32 @@ TEST_CASE("a centered line offsets its glyphs once, by the line") { CHECK(paragraph.lines[0].glyphs[0].x == 0); } +TEST_CASE("a justified line that wraps reaches the far edge") { + Setting setting; + bureau::text::ParagraphOptions options; + options.maxWidth = 120; + const auto start = setting.set("one two three four five six", options); + options.align = bureau::text::ParagraphOptions::Align::Justify; + const auto justified = setting.set("one two three four five six", options); + + REQUIRE(justified.lines.size() > 1); + CHECK(justified.lines[0].glyphs.back().x > start.lines[0].glyphs.back().x); +} + +TEST_CASE("a justified line that ends its paragraph keeps its words together") { + Setting setting; + bureau::text::ParagraphOptions options; + options.maxWidth = 400; + options.preserveBreaks = true; + const auto start = setting.set("one two\nthree four", options); + options.align = bureau::text::ParagraphOptions::Align::Justify; + const auto justified = setting.set("one two\nthree four", options); + + REQUIRE(justified.lines.size() == 2); + CHECK(justified.lines[0].glyphs.back().x == + doctest::Approx(start.lines[0].glyphs.back().x)); +} + TEST_CASE("text shrinks no narrower than its longest word") { Setting setting; const auto words = setting.set("a supercalifragilistic word");