~adnano/astronaut

ref: 72ba913688a9d2dafb0bfdf11a5cee16685ce98a astronaut/plaintext.go -rw-r--r-- 1.3 KiB
72ba9136Adnan Maolood Use scfg to configure settings 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
package main

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

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

// PlainText represents a plain text document.
type PlainText struct {
	view  *ui.View
	rc    io.ReadCloser
	mu    sync.RWMutex
	lines []string
	done  int32
	err   error
}

func NewPlainText(view *ui.View, rc io.ReadCloser) *PlainText {
	return &PlainText{
		view: view,
		rc:   rc,
	}
}

func (p *PlainText) Parse() error {
	atomic.StoreInt32(&p.done, 0)
	defer atomic.StoreInt32(&p.done, 1)
	scanner := bufio.NewScanner(p.rc)
	for scanner.Scan() {
		p.appendLine(scanner.Text())
	}
	return scanner.Err()
}

func (p *PlainText) Done() bool {
	return atomic.LoadInt32(&p.done) == 1
}

func (p *PlainText) Close() error {
	return p.rc.Close()
}

func (p *PlainText) appendLine(line string) {
	p.mu.Lock()
	defer p.mu.Unlock()
	p.lines = append(p.lines, line)
	p.view.Invalidate()
}

func (p *PlainText) Title() string {
	return ""
}

func (p *PlainText) Draw() {
	p.mu.RLock()
	defer p.mu.RUnlock()
	p.view.Fill(' ', styles.Default)
	for y, line := range p.lines {
		p.view.DrawText(0, y, line, styles.Default)
	}
	w, h := p.view.Size()
	p.view.SetContentSize(w, len(p.lines)+h-1, true)
}

func (p *PlainText) Event(event tcell.Event) bool {
	p.mu.RLock()
	defer p.mu.RUnlock()
	return p.view.HandleScrollEvent(event)
}