~adnano/astronaut

ref: 5b2ba7d7bffd153f57a7eac22f172a5d4d56c6a9 astronaut/text.go -rw-r--r-- 6.3 KiB
5b2ba7d7Adnan Maolood ui/view: Remove focus variable 4 months ago
                                                                                
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
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
package main

import (
	"astronaut/styles"
	"astronaut/ui"
	"bufio"
	"io"
	"strings"
	"sync"

	"github.com/gdamore/tcell/v2"
)

// Wrapped represents a line that has been wrapped.
type Wrapped struct {
	Index   int
	Type    LineType
	Text    string
	Wrapped bool
}

// Text represents a text document.
type Text struct {
	mediatype string
	view      *ui.View
	cfg       DisplayConfig
	rc        io.ReadCloser
	mu        sync.RWMutex
	lines     []Line    // parsed lines
	tabindex  []int     // list of tabbable lines
	processed int       // number of processed lines
	wrapped   []Wrapped // wrapped lines
	pos       []int     // list of line positions
	nwrapped  int       // number of lines which have been wrapped
	title     string    // document title
	focus     int       // focused link
	action    func(string)
}

// NewText returns a new text document with the given media type.
func NewText(view *ui.View, tab *Tab, rc io.ReadCloser, mediatype string) *Text {
	return &Text{
		mediatype: mediatype,
		view:      view,
		cfg:       tab.browser.config.Display,
		rc:        rc,
		focus:     -1,
	}
}

// NewParsedGemText returns a new, already parsed Gemini text document.
func NewParsedGemText(view *ui.View, tab *Tab, rc io.ReadCloser) *Text {
	defer rc.Close()
	text := NewText(view, tab, rc, "text/gemini")
	text.Parse()
	return text
}

// Parse parses the text document.
func (t *Text) Parse() error {
	switch t.mediatype {
	case "text/gemini":
		return t.parseGemtext()
	default:
		return t.parsePlaintext()
	}
}

// Close stops the parsing of the text document.
func (t *Text) Close() error {
	return t.rc.Close()
}

func (t *Text) parseGemtext() error {
	// Add an empty newline
	t.appendLine(Line{})

	scanner := bufio.NewScanner(t.rc)
	parser := NewParser()
	var graphic bool

loop:
	for scanner.Scan() {
		line := parser.ParseLine(scanner.Text())
		switch line.Type {
		case LinePreformattingStart:
			// Trim whitespace
			line.Text = strings.TrimSpace(line.Text)
			// The presence of alt text indicates that the preformatted text
			// is a graphic (i.e., not accessible).
			graphic = len(line.Text) != 0

			if !t.cfg.AltText {
				// Hide alt text
				continue loop
			}
		case LinePreformattingEnd:
			graphic = false
			continue loop
		case LinePreformattedText:
			if graphic && !t.cfg.Graphics {
				// Hide graphics
				continue loop
			}
		}
		t.appendLine(line)
	}
	return scanner.Err()
}

func (t *Text) parsePlaintext() error {
	scanner := bufio.NewScanner(t.rc)
	for scanner.Scan() {
		t.appendLine(Line{
			Type: LinePreformattedText,
			Text: scanner.Text(),
		})
	}
	return scanner.Err()
}

func (t *Text) appendLine(line Line) {
	t.mu.Lock()
	defer t.mu.Unlock()
	t.lines = append(t.lines, line)
	t.view.Invalidate()
}

// Title returns the title of the text document.
func (t *Text) Title() string {
	return t.title
}

// Update updates the text document.
func (t *Text) Update() {
	t.mu.RLock()
	defer t.mu.RUnlock()

	const padding = 4
	width, height := t.view.Size()
	width -= padding * 2

	// Process new lines
	// Processing happens only once per line
	for ; t.processed < len(t.lines); t.processed++ {
		line := t.lines[t.processed]

		// Set title
		if len(t.title) == 0 && line.Type == LineHeading1 {
			t.title = line.Text
			t.view.Invalidate()
		}

		// Populate tab index
		if line.Tabindex != 0 {
			t.tabindex = append(t.tabindex, t.processed)
		}
	}

	if t.nwrapped < len(t.lines) {
		vy := t.view.ScrollY()
		y := len(t.wrapped)
		// If the new lines are within the view area
		if y >= vy && y < vy+height {
			// Invalidate the view
			t.view.Invalidate()
		}
	}

	// Wrap newly added lines
	// Wrapping happens every time the screen is resized
	for ; t.nwrapped < len(t.lines); t.nwrapped++ {
		line := t.lines[t.nwrapped]
		text := line.Text
		// Store line position
		t.pos = append(t.pos, len(t.wrapped))

		if line.Type == LinePreformattedText {
			// Don't wrap
			t.wrapped = append(t.wrapped, Wrapped{
				Index: t.nwrapped,
				Type:  LinePreformattedText,
				Text:  text,
			})
			continue
		}

		if line.Type == LineLink && len(text) == 0 {
			text = line.URL
		}

		wrapped := ui.WordWrap(text, width)
		for i, text := range wrapped {
			t.wrapped = append(t.wrapped, Wrapped{
				Index:   t.nwrapped,
				Type:    line.Type,
				Text:    text,
				Wrapped: i != 0,
			})
		}
	}
}

// Draw draws the text document.
func (t *Text) Draw() {
	t.mu.RLock()
	defer t.mu.RUnlock()

	t.view.Fill(' ', styles.Default)

	const padding = 4
	w, h := t.view.Size()
	w -= padding * 2

	vy := t.view.ScrollY()
	for y := vy; y < vy+h && y < len(t.wrapped); y++ {
		var style tcell.Style
		var prefix string
		var pstyle tcell.Style
		x := padding

		line := t.wrapped[y]
		switch line.Type {
		case LineHeading1:
			style = styles.Heading1
			if !line.Wrapped {
				prefix = "  # "
				pstyle = style
			}
		case LineHeading2:
			style = styles.Heading2
			if !line.Wrapped {
				prefix = " ## "
				pstyle = style
			}
		case LineHeading3:
			style = styles.Heading3
			if !line.Wrapped {
				prefix = "### "
				pstyle = style
			}
		case LineQuote:
			style = styles.Quote
			prefix = "  > "
			pstyle = style
		case LineLink:
			style = styles.Link
			if line.Index == t.focus {
				style = style.Reverse(true)
			}
			if !line.Wrapped {
				prefix = " => "
				pstyle = styles.Link.Underline(false)
			}
		case LineListItem:
			style = styles.ListItem
			if !line.Wrapped {
				prefix = "  • "
				pstyle = style
			}
		case LineText:
			style = styles.Text
		case LinePreformattedText:
			// Don't use padding
			w, _ := t.view.Size()
			x = 0
			style = styles.Pre
			for i := 0; i < w; i++ {
				t.view.SetContent(x+i, y, ' ', nil, style)
			}
		}
		if len(prefix) != 0 {
			t.view.DrawText(0, y, prefix, pstyle)
		}
		t.view.DrawText(x, y, line.Text, style)
	}

	t.view.SetContentSize(w, len(t.wrapped)+h-1, true)
}

// Invalidate invalidates the text document, forcing a redraw of all the text.
func (t *Text) Invalidate() {
	t.wrapped = nil
	t.nwrapped = 0
	t.pos = nil
}

// LinkAt reports whether there is a link at y, returning the link index if so.
func (t *Text) LinkAt(y int) (int, bool) {
	if y >= len(t.wrapped) {
		return -1, false
	}
	line := t.wrapped[y]
	if line.Type != LineLink {
		return -1, false
	}
	return line.Index, true
}

// LinkURL returns the URL of the link at the given index.
func (t *Text) LinkURL(idx int) string {
	return t.lines[idx].URL
}