forked from taylorskalyo/goreader
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathparse.go
More file actions
235 lines (216 loc) · 5.32 KB
/
parse.go
File metadata and controls
235 lines (216 loc) · 5.32 KB
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
package main
import (
"bufio"
"bytes"
"fmt"
"image"
"image/color"
"io"
"strings"
"unicode"
_ "image/jpeg"
_ "image/png"
"github.com/nfnt/resize"
termbox "github.com/nsf/termbox-go"
"github.com/nico385412/goreader/epub"
"golang.org/x/net/html"
"golang.org/x/net/html/atom"
)
type parser struct {
tagStack []atom.Atom
tokenizer *html.Tokenizer
doc cellbuf
items []epub.Item
}
type cellbuf struct {
cells []termbox.Cell
width int
lmargin int
col int
row int
space bool
fg, bg termbox.Attribute
}
// setCell changes a cell's attributes in the cell buffer document at the given
// position.
func (c *cellbuf) setCell(x, y int, ch rune, fg, bg termbox.Attribute) {
// Grow in steps of 1024 when out of space.
for y*c.width+x >= len(c.cells) {
c.cells = append(c.cells, make([]termbox.Cell, 1024)...)
}
c.cells[y*c.width+x] = termbox.Cell{Ch: ch, Fg: fg, Bg: bg}
}
// style sets the foreground/background attributes for future cells in the cell
// buffer document based on HTML tags in the tag stack.
func (c *cellbuf) style(tags []atom.Atom) {
fg := termbox.ColorDefault
for _, tag := range tags {
switch tag {
case atom.B, atom.Strong, atom.Em:
fg |= termbox.AttrBold
case atom.I:
fg |= termbox.ColorYellow
case atom.Title:
fg |= termbox.ColorRed
case atom.H1:
fg |= termbox.ColorMagenta
case atom.H2:
fg |= termbox.ColorBlue
case atom.H3, atom.H4, atom.H5, atom.H6:
fg |= termbox.ColorCyan
}
}
c.fg = fg
}
// appendText appends text to the cell buffer document.
func (c *cellbuf) appendText(str string) {
if len(str) <= 0 {
return
}
if c.col < c.lmargin {
c.col = c.lmargin
}
runes := []rune(str)
if unicode.IsSpace(runes[0]) {
c.space = true
}
scanner := bufio.NewScanner(strings.NewReader(strings.TrimSpace(str)))
scanner.Split(bufio.ScanWords)
for scanner.Scan() {
if c.col != c.lmargin && c.space {
c.col++
}
word := []rune(scanner.Text())
if len(word) > c.width-c.col {
c.row++
c.col = c.lmargin
}
for _, r := range word {
c.setCell(c.col, c.row, r, c.fg, c.bg)
c.col++
}
c.space = true
}
if !unicode.IsSpace(runes[len(runes)-1]) {
c.space = false
}
}
// parseText takes in html content via an io.Reader and returns a buffer
// containing only plain text.
func parseText(r io.Reader, items []epub.Item) (cellbuf, error) {
tokenizer := html.NewTokenizer(r)
doc := cellbuf{width: 80}
p := parser{tokenizer: tokenizer, doc: doc, items: items}
err := p.parse(r)
if err != nil {
return p.doc, err
}
return p.doc, nil
}
// parse walks an html document and renders elements to a cell buffer document.
func (p *parser) parse(io.Reader) (err error) {
for {
tokenType := p.tokenizer.Next()
token := p.tokenizer.Token()
switch tokenType {
case html.ErrorToken:
err = p.tokenizer.Err()
case html.StartTagToken:
p.tagStack = append(p.tagStack, token.DataAtom) // push element
fallthrough
case html.SelfClosingTagToken:
p.handleStartTag(token)
case html.TextToken:
p.handleText(token)
case html.EndTagToken:
p.tagStack = p.tagStack[:len(p.tagStack)-1] // pop element
}
if err == io.EOF {
return nil
} else if err != nil {
return err
}
}
}
// handleText appends text elements to the parser buffer. It filters elements
// that should not be displayed as text (e.g. style blocks).
func (p *parser) handleText(token html.Token) {
// Skip style tags
if len(p.tagStack) > 0 && p.tagStack[len(p.tagStack)-1] == atom.Style {
return
}
p.doc.style(p.tagStack)
p.doc.appendText(string(token.Data))
}
// handleStartTag appends text representations of non-text elements (e.g. image alt
// tags) to the parser buffer.
func (p *parser) handleStartTag(token html.Token) {
switch token.DataAtom {
case atom.Img:
// Display alt text in place of images.
for _, a := range token.Attr {
switch atom.Lookup([]byte(a.Key)) {
case atom.Alt:
text := fmt.Sprintf("Alt text: %s", a.Val)
p.doc.appendText(text)
p.doc.row++
p.doc.col = p.doc.lmargin
case atom.Src:
for _, item := range p.items {
if item.HREF == a.Val {
for _, line := range imageToText(item) {
p.doc.appendText(line)
p.doc.col = p.doc.lmargin
p.doc.row++
}
break
}
}
}
}
case atom.Br:
p.doc.row++
p.doc.col = p.doc.lmargin
case atom.H1, atom.H2, atom.H3, atom.H4, atom.H5, atom.H6, atom.Title,
atom.Div, atom.Tr:
p.doc.row += 2
p.doc.col = p.doc.lmargin
case atom.P:
p.doc.row += 2
p.doc.col = p.doc.lmargin
p.doc.col += 2
case atom.Hr:
p.doc.row++
p.doc.col = 0
p.doc.appendText(strings.Repeat("-", p.doc.width))
}
}
func imageToText(item epub.Item) []string {
lines := []string{}
r, err := item.Open()
if err != nil {
return lines
}
img, _, err := image.Decode(r)
if err != nil {
return lines
}
bounds := img.Bounds()
// Assume a character height to width ratio of 2:1.
w := 80
h := (bounds.Max.Y * w) / (bounds.Max.X * 2)
img = resize.Resize(uint(w), uint(h), img, resize.Lanczos3)
charGradient := []rune("MND8OZ$7I?+=~:,..")
buf := new(bytes.Buffer)
for y := 0; y < h; y++ {
for x := 0; x < w; x++ {
c := color.GrayModel.Convert(img.At(x, y))
y := c.(color.Gray).Y
pos := (len(charGradient) - 1) * int(y) / 255
buf.WriteRune(charGradient[pos])
}
lines = append(lines, buf.String())
buf = new(bytes.Buffer)
}
return lines
}