-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhtml2xterm.go
266 lines (230 loc) · 6.61 KB
/
html2xterm.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
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
package html2xterm
import (
"encoding/hex"
"errors"
"fmt"
"html"
"strings"
)
// Convert converts HTML to an Output which can be used to extract ANSI or xterm.js strings.
//
// Specifically, this function looks for <span> and <font> tags with "color" attributes or "style"
// attributes which specify a color. Tags surrounded in <div></div> are treated as individual lines
// and <br> creates a new line.
//
// It's known to work with the HTML output of a few sites:
// - http://patorjk.com/text-color-fader/
// - https://asciiart.club/
// - https://www.text-image.com/convert/
func Convert(html string) (Output, error) {
var result Output
html, err := tidyHTML(html)
if err != nil {
return Output{}, err
}
for {
start := strings.Index(html, "<div>")
useDiv := start != -1
var end int
if useDiv {
html = html[start+len("<div>"):]
end = strings.Index(html, "</div>")
if end == -1 {
end = len(html)
}
} else {
end = strings.Index(html, "<br>")
if end == -1 {
end = len(html)
}
}
line, err := parseLine(html[:end])
if err != nil {
return result, fmt.Errorf("fragment: '%v': %w", []byte(html[:end]), err)
}
// don't add blank lines to the beginning
if len(line.Segments) != 0 || len(result.Lines) != 0 {
result.Lines = append(result.Lines, line)
}
if useDiv {
end += len("</div>")
if end > len(html) {
break
}
html = html[end:]
} else {
end += len("<br>")
if end > len(html) {
break
}
html = html[end:]
}
}
// trim trailing blank lines
for i := len(result.Lines) - 1; i >= 0; i-- {
line := result.Lines[i]
if len(line.Segments) != 0 {
break
}
result.Lines = result.Lines[:i]
}
return result, nil
}
func tidyHTML(html string) (string, error) {
html = strings.ReplaceAll(html, "\n", "")
html = strings.ReplaceAll(html, "\r", "")
html = strings.ReplaceAll(html, "</body>", "")
html = strings.ReplaceAll(html, "</html>", "")
html = strings.ReplaceAll(html, "<pre>", "")
html = strings.ReplaceAll(html, "</pre>", "")
html = strings.ReplaceAll(html, " ", " ")
html = strings.ReplaceAll(html, "<DIV>", "<div>")
html = strings.ReplaceAll(html, "</DIV>", "</div>")
html = strings.ReplaceAll(html, "<SPAN", "<span")
html = strings.ReplaceAll(html, "</SPAN", "</span>")
html = strings.ReplaceAll(html, "<FONT", "<font")
html = strings.ReplaceAll(html, "</FONT>", "</font>")
html = strings.ReplaceAll(html, "<br/>", "<br>")
html = strings.ReplaceAll(html, "<br />", "<br>")
html = strings.ReplaceAll(html, "<BR>", "<br>")
html = strings.ReplaceAll(html, "<BR/>", "<br>")
html = strings.ReplaceAll(html, "<BR />", "<br>")
bodyStart := strings.Index(html, "<body")
if bodyStart != -1 {
end := strings.Index(html[bodyStart:], ">")
if end == -1 {
return html, fmt.Errorf("found '<body' but could not find closing '>'")
}
html = html[bodyStart+end+1:]
}
const beginComment = "<!-- IMAGE BEGINS HERE -->"
const endComment = "<!-- IMAGE ENDS HERE -->"
commentStart := strings.Index(html, beginComment)
if commentStart != -1 {
html = html[commentStart+len(beginComment):]
commentEnd := strings.Index(html, endComment)
if commentEnd != -1 {
html = html[:commentEnd]
}
}
if strings.HasPrefix(html, "<font size=") {
start := strings.Index(html, ">")
html = html[start+1:]
html = strings.TrimSuffix(html, "</font>")
}
return html, nil
}
func parseLine(text string) (Line, error) {
if len(text) == 0 {
return Line{}, nil
}
var lines []string
switch {
case strings.Contains(text, "<span"):
lines = strings.SplitAfter(text, "</span>")
case strings.Contains(text, "<font"):
lines = strings.SplitAfter(text, "</font>")
default:
return Line{}, fmt.Errorf("line: '%s', can't find <span> or <font>", text)
}
var line Line
for _, s := range lines {
s = strings.TrimSpace(s)
s = strings.TrimSuffix(s, "</font>")
s = strings.TrimSuffix(s, "</span>")
if len(s) == 0 {
continue
}
if !strings.HasPrefix(s, "<font") && !strings.HasPrefix(s, "<span") {
return line, fmt.Errorf("fragment: '%s ...', unhandled html tag", s)
}
textStart := strings.Index(s, ">")
if textStart == -1 {
return line, fmt.Errorf("fragment: '%s ...', missing '>'", s)
}
text := html.UnescapeString(s[textStart+1:])
if len(text) == 0 {
continue
}
segColor, err := parseColor(s[5:textStart])
if err != nil {
return line, fmt.Errorf("fragment: '%s ...': %w", s, err)
}
segment := Segment{
Text: text,
Color: segColor,
}
line.Segments = append(line.Segments, segment)
}
line.Segments = combineSimilarSegments(line.Segments)
return line, nil
}
func combineSimilarSegments(segments []Segment) []Segment {
for i := 1; i < len(segments); i++ {
prev := i - 1
// combine segments that are either the same color or both only whitespace
if segments[prev].Color == segments[i].Color ||
strings.TrimSpace(segments[prev].Text) == "" && strings.TrimSpace(segments[i].Text) == "" {
segments[prev].Text += segments[i].Text
segments = append(segments[:i], segments[i+1:]...)
i--
}
}
// trim trailing whitespace
for i := len(segments) - 1; i >= 0; i-- {
seg := segments[i]
if strings.TrimSpace(seg.Text) != "" {
break
}
segments = segments[:i]
}
return segments
}
func parseColor(attrs string) (Color, error) {
// look for color= or style= ...
// anything after '>' is text
var r, g, b uint8
colorIndex := strings.Index(attrs, "color")
if colorIndex == -1 {
return Color{}, fmt.Errorf("can't find 'color' in '%s'", attrs)
}
attrs = attrs[colorIndex:]
attrs = strings.ReplaceAll(attrs, `'`, `"`)
attrs = strings.ReplaceAll(attrs, `="`, `:`)
semiEnd := strings.Index(attrs, `;`)
quotEnd := strings.Index(attrs, `"`)
switch {
case semiEnd < quotEnd && semiEnd != -1:
attrs = attrs[:semiEnd]
case quotEnd != -1:
attrs = attrs[:quotEnd]
default:
return Color{}, errors.New("missing ';' or '\"'")
}
attrs = strings.TrimSpace(strings.TrimPrefix(attrs, "color:"))
if strings.HasPrefix(attrs, "#") {
attrs = attrs[1:] // trim '#' prefix
if len(attrs) == 3 {
// convert 'abc' to 'aabbcc'
attrs = fmt.Sprintf("%[1]c%[1]c%[2]c%[2]c%[3]c%[3]c", attrs[0], attrs[1], attrs[2])
}
if len(attrs) != 6 {
return Color{}, fmt.Errorf("unknown color '%s', expected len=6", attrs)
}
col, err := hex.DecodeString(attrs)
if err != nil {
return Color{}, fmt.Errorf("error decoding color '%s': %w", attrs, err)
}
r, g, b = col[0], col[1], col[2]
} else {
switch strings.ToLower(attrs) {
case "black":
r, g, b = 0, 0, 0
case "white":
r, g, b = 255, 255, 255
default:
return Color{}, fmt.Errorf("unknown color '%s'", attrs)
}
}
return Color{R: r, G: g, B: b}, nil
}