~adnano/astronaut

astronaut/text.go -rw-r--r-- 9.8 KiB
947cfac7Adnan Maolood Update default bindings 12 days 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
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
package main

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

	"github.com/gdamore/tcell/v2"
	"github.com/mattn/go-runewidth"
)

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

// 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
	headings   []int       // list of heading 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
	highlight  int         // current highlight
	highlights []Highlight // search results
	action     func(string)
}

// Highlight represents a highlighted portion of text.
type Highlight struct {
	Line  int
	Start int
	End   int
}

// 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 {
	if t.rc == nil {
		return nil
	}
	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 headings
		switch line.Type {
		case LineHeading1, LineHeading2, LineHeading3:
			t.headings = append(t.headings, t.processed)
		}

		// 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)
		offs := 0
		for _, text := range wrapped {
			t.wrapped = append(t.wrapped, Wrapped{
				Index:  t.nwrapped,
				Offset: offs,
				Type:   line.Type,
				Text:   text,
			})
			offs += runewidth.StringWidth(text)
		}
	}
}

// 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.Offset == 0 {
				prefix = "  # "
				pstyle = style
			}
		case LineHeading2:
			style = styles.Heading2
			if line.Offset == 0 {
				prefix = " ## "
				pstyle = style
			}
		case LineHeading3:
			style = styles.Heading3
			if line.Offset == 0 {
				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.Offset == 0 {
				prefix = " => "
				pstyle = styles.Link.Underline(false)
			}
		case LineListItem:
			style = styles.ListItem
			if line.Offset == 0 {
				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)
	}

	// Draw highlights
	for i, hl := range t.highlights {
		y := t.LinePos(hl.Line)
		if y == -1 {
			break
		}
		for x := hl.Start; x < hl.End; x++ {
			for y+1 < len(t.wrapped) &&
				t.wrapped[y+1].Offset != 0 &&
				t.wrapped[y+1].Offset <= x {
				y++
			}
			offs := t.wrapped[y].Offset
			ch, comb, style, _ := t.view.GetContent(x-offs+padding, y)
			if i == t.highlight {
				style = style.
					Background(tcell.ColorYellow).
					Foreground(tcell.ColorBlack)
			} else {
				style = style.Reverse(true)

			}
			t.view.SetContent(x-offs+padding, y, ch, comb, style)
		}
	}

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

// TableOfContents returns the table of contents of the document.
// Returns nil if there are no headings in the document.
func (t *Text) TableOfContents() *Text {
	t.mu.RLock()
	defer t.mu.RUnlock()

	if len(t.headings) == 0 {
		return nil
	}

	toc := &Text{
		view:  t.view,
		cfg:   t.cfg,
		focus: -1,
	}

	toc.lines = append(toc.lines, Line{})
	toc.lines = append(toc.lines, Line{
		Type: LineHeading1,
		Text: "Table of contents",
	})
	toc.lines = append(toc.lines, Line{})

	tabindex := 1
	for _, idx := range t.headings {
		line := t.lines[idx]

		var prefix string
		switch line.Type {
		case LineHeading1:
			prefix = "# "
		case LineHeading2:
			prefix = "## "
		case LineHeading3:
			prefix = "### "
		}

		toc.lines = append(toc.lines, Line{
			Type:     LineLink,
			URL:      strconv.Itoa(idx),
			Text:     prefix + line.Text,
			Tabindex: tabindex,
		})
		tabindex++
	}

	return toc
}

// 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 {
	t.mu.RLock()
	defer t.mu.RUnlock()
	return t.lines[idx].URL
}

// LinePos returns the y-position of the given line number in the text view.
func (t *Text) LinePos(line int) int {
	if line >= len(t.pos) {
		return -1
	}
	return t.pos[line]
}

// Find searches the text document and highlights matches for the given query.
func (t *Text) Find(query string) error {
	t.mu.RLock()
	defer t.mu.RUnlock()
	t.highlight = 0
	t.highlights = nil
	if query == "" {
		return nil
	}
	re, err := regexp.Compile(query)
	if err != nil {
		return err
	}
	for i := range t.lines {
		text := t.lines[i].Text
		loc := re.FindAllStringIndex(text, -1)
		pos := 0
		start := 0
		for j := range loc {
			start += runewidth.StringWidth(text[pos:loc[j][0]])
			pos = loc[j][0]
			end := start + runewidth.StringWidth(text[pos:loc[j][1]])
			t.highlights = append(t.highlights, Highlight{
				Line:  i,
				Start: start,
				End:   end,
			})
		}
	}
	return nil
}

func (t *Text) FindPrev() {
	if len(t.highlights) == 0 {
		return
	}
	if t.highlight > 0 {
		t.highlight--
	}
	hl := t.highlights[t.highlight]
	y := t.LinePos(hl.Line)
	if y == -1 {
		return
	}
	for y+1 < len(t.wrapped) &&
		t.wrapped[y+1].Offset != 0 &&
		t.wrapped[y+1].Offset <= hl.Start {
		y++
	}
	t.view.MakeVisible(0, y)
}

func (t *Text) FindNext() {
	if len(t.highlights) == 0 {
		return
	}
	if t.highlight < len(t.highlights)-1 {
		t.highlight++
	}
	hl := t.highlights[t.highlight]
	y := t.LinePos(hl.Line)
	if y == -1 {
		return
	}
	for y+1 < len(t.wrapped) &&
		t.wrapped[y+1].Offset != 0 &&
		t.wrapped[y+1].Offset <= hl.Start {
		y++
	}
	t.view.MakeVisible(0, y)
}