10using System.Collections.Generic;
14 public static class TextWrapper {
33 return source[
start] ==
'\n';
37 return char.IsWhiteSpace(source[
start]);
40 public float GetWidth(
string source, Func<char, float> charWidth) {
42 for (
int i = 0; i <
length; i++) {
43 width += charWidth(source[i +
start]);
66 public void TrimEnd(
string source, Func<char, float> charWidth) {
69 if (
char.IsWhiteSpace(
end)) {
86 public static void Tokenize(
string text, List<Token> tokens) {
88 int textLength = text.Length;
92 if (index >= textLength) {
96 if (!
char.IsWhiteSpace(text[index])) {
100 tokens.Add(
new Token() {
108 Token token =
new Token() {
113 while (index < textLength && !
char.IsWhiteSpace(text[index])) {
117 token.length = index - token.start;
134 public static void Wrap(
string source, List<Token> tokens, List<Line> lines, Func<char, float> widthFunc,
float maxLineWidth) {
135 if (tokens.Count == 0) {
140 Token token = tokens[0];
143 if (token.IsNewline(source)) {
144 lines.Add(
new Line() {
153 NEW_LINE_CONTINUE_TOKEN:
155 float firstTokenWidth = widthFunc(source[token.start]);
158 Line line =
new Line() {
161 width = firstTokenWidth
165 for (
int i = token.start + 1; i < token.end; i++) {
166 float charWidth = widthFunc(source[i]);
169 if (firstTokenWidth + charWidth > maxLineWidth) {
171 line.width = firstTokenWidth;
177 goto NEW_LINE_CONTINUE_TOKEN;
180 firstTokenWidth += charWidth;
184 line.width = firstTokenWidth;
185 line.length = token.length;
189 if (tokenIndex >= tokens.Count) {
194 token = tokens[tokenIndex];
199 if (token.IsNewline(source)) {
200 line.TrimEnd(source, widthFunc);
206 float tokenWidth = token.GetWidth(source, widthFunc);
207 if (line.width + tokenWidth > maxLineWidth && !token.IsWhitespace(source)) {
208 line.TrimEnd(source, widthFunc);
212 goto NEW_LINE_CONTINUE_TOKEN;
216 line.length += token.length;
217 line.width += tokenWidth;
220 if (tokenIndex >= tokens.Count) {
224 token = tokens[tokenIndex];
230 if (tokenIndex >= tokens.Count) {
233 token = tokens[tokenIndex];
References a contiguous sequence of characters in a string
void TrimEnd(string source, Func< char, float > charWidth)
References a contiguous sequence of characters in a string.
bool IsNewline(string source)
float GetWidth(string source, Func< char, float > charWidth)
bool IsWhitespace(string source)