/
formattext.go
228 lines (207 loc) · 5.27 KB
/
formattext.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
package parser
import (
"encoding/json"
"fmt"
"io/ioutil"
"regexp"
"strings"
)
// FontWidthsConfig holds the pixel widths of characters in various game fonts.
type FontWidthsConfig struct {
Fonts map[string]map[string]int `json:"fonts"`
DefaultFontID string `json:"defaultFontId"`
}
// LoadFontWidths reads a font width config JSON file.
func LoadFontWidths(filepath string) (FontWidthsConfig, error) {
var config FontWidthsConfig
bytes, err := ioutil.ReadFile(filepath)
if err != nil {
return config, err
}
if err := json.Unmarshal(bytes, &config); err != nil {
return config, err
}
return config, err
}
const testFontID = "TEST"
// FormatText automatically inserts line breaks into text
// according to in-game text box widths.
func (fw *FontWidthsConfig) FormatText(text string, maxWidth int, fontID string) (string, error) {
if !fw.isFontIDValid(fontID) && len(fontID) > 0 && fontID != testFontID {
validFontIDs := make([]string, len(fw.Fonts))
i := 0
for k := range fw.Fonts {
validFontIDs[i] = k
i++
}
return "", fmt.Errorf("Unknown fontID '%s' used in format(). List of valid fontIDs are '%s'", fontID, validFontIDs)
}
text = strings.ReplaceAll(text, "\n", " ")
var formattedSb strings.Builder
var curLineSb strings.Builder
curWidth := 0
isFirstLine := true
isFirstWord := true
pos := 0
for pos < len(text) {
endPos, word, err := fw.getNextWord(text[pos:])
if err != nil {
return "", err
}
if len(word) == 0 {
break
}
pos += endPos
if fw.isLineBreak(word) {
curWidth = 0
formattedSb.WriteString(curLineSb.String())
formattedSb.WriteString(word)
formattedSb.WriteByte('\n')
if fw.isParagraphBreak(word) {
isFirstLine = true
} else {
isFirstLine = false
}
isFirstWord = true
curLineSb.Reset()
} else {
wordWidth := 0
if !isFirstWord {
wordWidth += fw.getRunePixelWidth(' ', fontID)
}
wordWidth += fw.getWordPixelWidth(word, fontID)
if curWidth+wordWidth > maxWidth && curLineSb.Len() > 0 {
formattedSb.WriteString(curLineSb.String())
if isFirstLine {
formattedSb.WriteString(`\n`)
isFirstLine = false
} else {
formattedSb.WriteString(`\l`)
}
formattedSb.WriteByte('\n')
isFirstWord = false
curLineSb.Reset()
curLineSb.WriteString(word)
curWidth = wordWidth
} else {
curWidth += wordWidth
if !isFirstWord {
curLineSb.WriteByte(' ')
}
curLineSb.WriteString(word)
isFirstWord = false
}
}
}
if curLineSb.Len() > 0 {
formattedSb.WriteString(curLineSb.String())
}
return formattedSb.String(), nil
}
func (fw *FontWidthsConfig) getNextWord(text string) (int, string, error) {
escape := false
endPos := 0
startPos := 0
foundNonSpace := false
foundRegularRune := false
endOnNext := false
controlCodeLevel := 0
for pos, char := range text {
if endOnNext {
return pos, text[startPos:pos], nil
}
if escape && (char == 'l' || char == 'n' || char == 'p') {
if foundRegularRune {
return endPos, text[startPos:endPos], nil
}
endOnNext = true
} else if char == '\\' && controlCodeLevel == 0 {
escape = true
if !foundRegularRune {
startPos = pos
}
foundNonSpace = true
endPos = pos
} else {
if char == ' ' {
if foundNonSpace && controlCodeLevel == 0 {
return pos, text[startPos:pos], nil
}
} else {
if !foundNonSpace {
startPos = pos
}
foundRegularRune = true
foundNonSpace = true
if char == '{' {
controlCodeLevel++
} else if char == '}' {
if controlCodeLevel > 0 {
controlCodeLevel--
}
}
}
escape = false
}
}
if !foundNonSpace {
return len(text), "", nil
}
return len(text), text[startPos:], nil
}
func (fw *FontWidthsConfig) isLineBreak(word string) bool {
return word == `\n` || word == `\l` || word == `\p`
}
func (fw *FontWidthsConfig) isParagraphBreak(word string) bool {
return word == `\p`
}
func (fw *FontWidthsConfig) getWordPixelWidth(word string, fontID string) int {
word, wordWidth := fw.processControlCodes(word, fontID)
for _, r := range word {
wordWidth += fw.getRunePixelWidth(r, fontID)
}
return wordWidth
}
func (fw *FontWidthsConfig) processControlCodes(word string, fontID string) (string, int) {
width := 0
re := regexp.MustCompile(`{[^}]*}`)
positions := re.FindAllStringIndex(word, -1)
for _, pos := range positions {
code := word[pos[0]:pos[1]]
width += fw.getControlCodePixelWidth(code, fontID)
}
strippedWord := re.ReplaceAllString(word, "")
return strippedWord, width
}
func (fw *FontWidthsConfig) getRunePixelWidth(r rune, fontID string) int {
if fontID == testFontID {
return 10
}
return fw.readWidthFromFontConfig(string(r), fontID)
}
func (fw *FontWidthsConfig) getControlCodePixelWidth(code string, fontID string) int {
if fontID == testFontID {
return 100
}
return fw.readWidthFromFontConfig(code, fontID)
}
func (fw *FontWidthsConfig) isFontIDValid(fontID string) bool {
_, ok := fw.Fonts[fontID]
return ok
}
const fallbackWidth = 0
func (fw *FontWidthsConfig) readWidthFromFontConfig(value string, fontID string) int {
font, ok := fw.Fonts[fontID]
if !ok {
return fallbackWidth
}
width, ok := font[value]
if !ok {
defaultWidth, ok := font["default"]
if !ok {
return fallbackWidth
}
return defaultWidth
}
return width
}