~adnano/astronaut

ref: 72ba913688a9d2dafb0bfdf11a5cee16685ce98a astronaut/gemtext.go -rw-r--r-- 7.2 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
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
package main

import (
	"astronaut/styles"
	"astronaut/text"
	"astronaut/ui"
	"fmt"
	"io"
	"strings"
	"sync"
	"sync/atomic"

	"git.sr.ht/~adnano/go-gemini"
	"github.com/gdamore/tcell/v2"
)

// GemText represents a Gemini text document.
type GemText struct {
	view    *ui.View
	tab     *Tab
	rc      io.ReadCloser
	mu      sync.RWMutex
	text    gemini.Text // parsed gemtext
	pos     []int       // cached line positions from last draw
	links   []int       // which lines are links
	focused bool        // a link is focused
	focus   int         // index of focused link in links
	title   string      // document title
	done    int32       // document finished loading
	action  func(string)
}

func NewGemText(view *ui.View, tab *Tab, rc io.ReadCloser) *GemText {
	return &GemText{
		view:  view,
		tab:   tab,
		rc:    rc,
		focus: -1,
	}
}

func NewParsedGemText(view *ui.View, tab *Tab, rc io.ReadCloser) *GemText {
	defer rc.Close()
	gem := NewGemText(view, tab, rc)
	gem.Parse()
	return gem
}

func (g *GemText) Parse() error {
	atomic.StoreInt32(&g.done, 0)
	defer atomic.StoreInt32(&g.done, 1)

	g.tab.browser.settings.RLock()
	settings := g.tab.browser.settings.Display
	g.tab.browser.settings.RUnlock()

	var title bool
	var i int
	var pre bool
	var graphic bool
	// Add an empty newline
	g.appendLine(gemini.LineText(""))
	i++
	err := gemini.ParseLines(g.rc, func(line gemini.Line) {
		if !title {
			if h1, ok := line.(gemini.LineHeading1); ok {
				g.setTitle(string(h1))
				title = true
			}
		}
		switch line := line.(type) {
		case gemini.LineLink:
			g.appendLink(i)
			g.appendLine(line)
			i++
		case gemini.LinePreformattingToggle:
			pre = !pre
			graphic = false
			if pre {
				alt := strings.TrimSpace(string(line))
				// The presence of alt text indicates that the preformatted text
				// is a graphic (i.e., not accessible).
				graphic = alt != ""
				// Show alt-text at the user's request
				if settings.AltText {
					g.appendLine(gemini.LineText(alt))
					i++
				}
			}
		case gemini.LinePreformattedText:
			// Hide graphics at the user's request
			if !graphic || settings.Graphics {
				g.appendLine(line)
				i++
			}
		default:
			g.appendLine(line)
			i++
		}
	})
	return err
}

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

func (g *GemText) Close() error {
	return g.rc.Close()
}

func (g *GemText) appendLine(line gemini.Line) {
	g.mu.Lock()
	defer g.mu.Unlock()
	g.text = append(g.text, line)
	g.pos = append(g.pos, 0)
	g.view.Invalidate()
}

func (g *GemText) setTitle(title string) {
	g.mu.Lock()
	defer g.mu.Unlock()
	g.title = title
	g.view.Invalidate()
}

func (g *GemText) appendLink(i int) {
	g.mu.Lock()
	defer g.mu.Unlock()
	g.links = append(g.links, i)
	g.view.Invalidate()
}

func (g *GemText) Title() string {
	g.mu.RLock()
	defer g.mu.RUnlock()
	return g.title
}

func (g *GemText) Draw() {
	g.mu.RLock()
	defer g.mu.RUnlock()

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

	focus := -1
	if g.focused && g.focus != -1 {
		focus = g.links[g.focus]
	}

	var y int
	for i, line := range g.text {
		g.pos[i] = y

		const padding = 4
		x := padding
		w, _ := g.view.Size()
		w -= padding * 2

		switch line := line.(type) {
		case gemini.LineHeading1:
			g.view.DrawText(0, y, "  # ", styles.Heading1)
			y = g.drawWrapped(x, y, string(line), w, styles.Heading1)
		case gemini.LineHeading2:
			g.view.DrawText(0, y, " ## ", styles.Heading2)
			y = g.drawWrapped(x, y, string(line), w, styles.Heading2)
		case gemini.LineHeading3:
			g.view.DrawText(0, y, "### ", styles.Heading3)
			y = g.drawWrapped(x, y, string(line), w, styles.Heading3)
		case gemini.LineQuote:
			newY := g.drawWrapped(x, y, string(line), w, styles.Quote)
			for ; y < newY; y++ {
				g.view.DrawText(0, y, "  > ", styles.Quote)
			}
		case gemini.LineLink:
			s := line.Name
			if s == "" {
				s = line.URL
			}
			style := styles.Link
			g.view.DrawText(1, y, "=>", style.Underline(false))
			if i == focus {
				style = style.Reverse(true)
			}
			y = g.drawWrapped(x, y, s, w, style)
		case gemini.LineListItem:
			g.view.DrawText(0, y, "  • ", styles.ListItem)
			y = g.drawWrapped(x, y, string(line), w, styles.ListItem)
		case gemini.LineText:
			y = g.drawWrapped(x, y, string(line), w, styles.Text)
		case gemini.LinePreformattedText:
			// Don't wrap preformatted text
			for i := 0; i < w; i++ {
				g.view.SetContent(x+i, y, ' ', nil, styles.Pre)
			}
			g.view.DrawText(x, y, string(line), styles.Pre)
			y++
		}
	}
	w, h := g.view.Size()
	g.view.SetContentSize(w, y+h-1, true)
}

func (g *GemText) drawWrapped(x, y int, s string, w int, style tcell.Style) int {
	wrapped := text.WordWrap(s, w)
	if len(wrapped) == 0 {
		y++
	} else {
		for _, wrap := range wrapped {
			g.view.DrawText(x, y, wrap, style)
			y++
		}
	}
	return y
}

func (g *GemText) Event(event tcell.Event) bool {
	g.mu.Lock()
	defer g.mu.Unlock()

	switch event := event.(type) {
	case *tcell.EventKey:
		switch event.Key() {
		case tcell.KeyTab:
			if !g.focused {
				g.focused = true
				if g.focus == -1 {
					g.focus++
				}
			} else {
				g.focus++
			}
			if g.focus > len(g.links)-1 {
				g.focus = -1
			}
			if g.focus != -1 {
				g.view.MakeVisible(0, g.pos[g.links[g.focus]])
				g.tab.status.Info("=> " + g.text[g.links[g.focus]].(gemini.LineLink).URL)
			} else {
				g.tab.status.Clear()
			}
			g.view.Invalidate()
			return true
		case tcell.KeyBacktab:
			if !g.focused {
				g.focused = true
				if g.focus == -1 {
					g.focus--
				}
			} else {
				g.focus--
			}
			if g.focus < -1 {
				g.focus = len(g.links) - 1
			}
			if g.focus != -1 {
				g.view.MakeVisible(0, g.pos[g.links[g.focus]])
				g.tab.status.Info("=> " + g.text[g.links[g.focus]].(gemini.LineLink).URL)
			} else {
				g.tab.status.Clear()
			}
			g.view.Invalidate()
			return true
		case tcell.KeyEnter:
			if g.focus != -1 {
				g.tab.status.Clear()
				newtab := (event.Modifiers() & tcell.ModAlt) != 0
				g.click(newtab)
				g.view.Invalidate()
				return true
			}
		case tcell.KeyESC:
			g.focused = false
			g.view.Invalidate()
			// allow others to handle ESC key
			return false
		}
	case *tcell.EventMouse:
		if !g.view.Contains(event.Position()) {
			break
		}
		buttons := event.Buttons()
		button1 := buttons&tcell.Button1 != 0
		button2 := buttons&tcell.Button2 != 0
		if button1 || button2 {
			// Click a link
			_, vy := g.view.Visible()
			_, y := g.view.GetLocal(event.Position())
			y += vy
			for i, l := range g.links {
				if y == g.pos[l] {
					if g.focused && g.focus == i {
						// Double click -> open
						g.focused = false
						g.tab.status.Clear()
						// Right click -> open in new tab
						g.click(button2)
					} else {
						g.focused = true
						g.focus = i
						g.tab.status.Info("=> " + g.text[l].(gemini.LineLink).URL)
					}
					g.view.Invalidate()
					return true
				}
			}
			// Lose focus
			g.focused = false
			g.tab.status.Clear()
			g.view.Invalidate()
			return true
		}
	}
	return g.view.HandleScrollEvent(event)
}

func (g *GemText) click(newtab bool) {
	link := g.text[g.links[g.focus]].(gemini.LineLink)
	if g.action != nil {
		g.action(link.URL)
		return
	}

	url, err := g.tab.ResolveReference(link.URL)
	if err != nil {
		g.tab.Error(err)
		return
	}

	if newtab {
		g.tab.browser.Command(fmt.Sprintf("newtab\nopen %s\n", url.String()))
	} else {
		g.tab.GetURL(url)
	}
}