AMFP Enhanced
C++ reference: the code this unofficial fork added
Loading...
Searching...
No Matches
WordWrap.h
Go to the documentation of this file.
1/*
2 * AMFP-2026: greedy word wrap with pluggable width and break rules, unit tested in
3 * tests/cpp/test_word_wrap.cpp. Used by iFontData::GetWordWrapRows when native CJK is on.
4 *
5 * Break opportunities:
6 * - at a space (the space is dropped at the break),
7 * - before character i when afCanBreak(s[i-1], s[i]) (nothing dropped; CJK, 避頭尾),
8 * - '\n' always ends a row (dropped).
9 * A row ends at the last opportunity that still fits; a single unit wider than the row stays
10 * whole on its own row (never split mid-word, never an empty row).
11 */
12#ifndef HPL_WORD_WRAP_H
13#define HPL_WORD_WRAP_H
14
15#include <cstddef>
16#include <utility>
17#include <vector>
18
19namespace hpl {
20
21typedef std::vector<std::pair<size_t, size_t> > tWrapRows; // [start, end) per row
22
23/**
24 * afWidth(start, end) gives the drawn width of s[start, end).
25 */
26template<class TWidth, class TCanBreak>
27void WordWrapRows(const wchar_t* apText, size_t alLen, float afMaxWidth,
28 TWidth afWidth, TCanBreak afCanBreak, tWrapRows& aRows)
29{
30 size_t lFirst = 0;
31 bool bHasBreak = false;
32 size_t lBreakEnd = 0, lBreakNext = 0; // row end / next row start of the last opportunity
33
34 for(size_t pos = 0; pos < alLen; ++pos)
35 {
36 wchar_t c = apText[pos];
37 if(c == L'\n')
38 {
39 aRows.push_back(std::make_pair(lFirst, pos));
40 lFirst = pos + 1;
41 bHasBreak = false;
42 continue;
43 }
44
45 bool bCandidate = false;
46 size_t lEnd = pos, lNext = pos;
47 if(c == L' ')
48 {
49 bCandidate = true;
50 lNext = pos + 1;
51 }
52 // After a space the space itself is the opportunity (so the row drops it).
53 else if(pos > lFirst && apText[pos - 1] != L' ' && afCanBreak(apText[pos - 1], c))
54 {
55 bCandidate = true;
56 }
57 if(!bCandidate) continue;
58
59 if(bHasBreak && afWidth(lFirst, lEnd) > afMaxWidth)
60 {
61 aRows.push_back(std::make_pair(lFirst, lBreakEnd));
62 lFirst = lBreakNext;
63 bHasBreak = false;
64 }
65 if(lEnd > lFirst)
66 {
67 bHasBreak = true;
68 lBreakEnd = lEnd;
69 lBreakNext = lNext;
70 }
71 }
72
73 if(bHasBreak && afWidth(lFirst, alLen) > afMaxWidth)
74 {
75 aRows.push_back(std::make_pair(lFirst, lBreakEnd));
76 lFirst = lBreakNext;
77 }
78 aRows.push_back(std::make_pair(lFirst, alLen));
79}
80
81}
82
83#endif
void WordWrapRows(const wchar_t *apText, size_t alLen, float afMaxWidth, TWidth afWidth, TCanBreak afCanBreak, tWrapRows &aRows)
afWidth(start, end) gives the drawn width of s[start, end).
Definition WordWrap.h:27
std::vector< std::pair< size_t, size_t > > tWrapRows
Definition WordWrap.h:21