~adnano/astronaut

ref: 5b2ba7d7bffd153f57a7eac22f172a5d4d56c6a9 astronaut/browser.go -rw-r--r-- 13.9 KiB
5b2ba7d7Adnan Maolood ui/view: Remove focus variable 2 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
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
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
package main

import (
	"astronaut/styles"
	"astronaut/ui"
	"fmt"
	"log"
	"math"
	"math/rand"
	"net/url"
	"os"
	"path/filepath"
	"strings"
	"sync"

	"git.sr.ht/~adnano/go-gemini"
	"git.sr.ht/~adnano/go-gemini/certificate"
	"git.sr.ht/~adnano/go-gemini/tofu"
	"git.sr.ht/~adnano/go-xdg"
	"github.com/gdamore/tcell/v2"
	"github.com/mattn/go-runewidth"
)

type Mode int

const (
	ModeNormal Mode = iota
	ModeCommand
	ModeInput
	ModeFollow
)

// Browser represents a browser.
// The browser contains tabs.
type Browser struct {
	view       *ui.View
	tablist    *ui.View
	tabView    *ui.View
	statusView *ui.View
	inputView  *ui.View

	hosts     tofu.KnownHosts
	hostsFile *tofu.HostWriter
	certs     certificate.Store
	bookmarks Bookmarks
	config    *Config

	tabs      []*Tab
	tabWidths []int
	tab       int
	tabsize   int

	input   ui.Input
	mode    Mode
	mu      sync.Mutex
	inputch chan string

	hint    string
	hints   []Hint
	hintMap map[string]Hint

	message struct {
		text string
		err  bool
	}
}

type Hint struct {
	Label string
	Index int
	Y     int
}

// NewBrowser returns a new browser.
func NewBrowser(ui *ui.UI, config *Config) *Browser {
	b := &Browser{
		view:       ui.View(),
		tablist:    ui.View(),
		tabView:    ui.View(),
		statusView: ui.View(),
		inputView:  ui.View(),
		config:     config,
	}

	b.input.SetView(b.inputView)

	// Load known hosts
	knownHostsPath := filepath.Join(xdg.DataHome(), "astronaut", "known_hosts")
	os.MkdirAll(filepath.Dir(knownHostsPath), 0700)
	if err := b.hosts.Load(knownHostsPath); err != nil {
		log.Print(err)
	}
	var err error
	b.hostsFile, err = tofu.OpenHostsFile(knownHostsPath)
	if err != nil {
		log.Print(err)
	}

	// Load client certificates
	certsDir := filepath.Join(xdg.DataHome(), "astronaut", "certificates")
	os.MkdirAll(certsDir, 0700)
	if err := b.certs.Load(certsDir); err != nil {
		log.Print(err)
	}

	// Load bookmarks
	bookmarks := filepath.Join(xdg.DataHome(), "astronaut", "bookmarks.gmi")
	if err := b.bookmarks.Open(bookmarks); err != nil {
		log.Print(err)
	}

	// Insert new tab
	tab := b.NewTab()
	b.InsertTab(0, tab)
	tab.Do(&gemini.Request{
		URL: &url.URL{
			Scheme: "about",
			Host:   "welcome",
		},
	})

	return b
}

func (b *Browser) Layout(x, y, w, h int) {
	tab := b.tabs[b.tab]
	if text := tab.Text(); text != nil {
		text.Invalidate()
	}

	b.view.Layout(x, y, w, h)
	b.tablist.Layout(x, y, w, 1)
	b.tabView.Layout(x, y+1, w, h-3)
	b.statusView.Layout(x, y+h-2, w, 1)
	b.inputView.Layout(x, y+h-1, w, 1)
}

// Draw draws the browser.
func (b *Browser) Draw() {
	b.tabs[b.tab].Draw()

	// Draw tab titles
	b.tablist.Fill(' ', styles.Tab().Reverse(true))
	var x int
	for i, tab := range b.tabs {
		style := styles.Tab()
		if i != b.tab {
			style = style.Reverse(true)
			if (i & 1) != 0 {
				style = style.Dim(true)
			}
		}
		x += b.tablist.DrawText(x, 0, " ", style)

		title := tab.Title()
		if runewidth.StringWidth(title) > 32 {
			title, _ = ui.Splice(title, 31)
			title += "…"
		}

		width := b.tablist.DrawText(x, 0, title, style)
		x += width
		x += b.tablist.DrawText(x, 0, " ", style)
		b.tabWidths[i] = width
	}
	if b.tabsize != x {
		b.tabsize = x
		b.tablist.SetContentSize(x, 1, false)
		b.makeTabVisible()
		b.view.Invalidate()
	}

	switch b.mode {
	case ModeNormal:
		// Draw overlay message
		if len(b.message.text) != 0 {
			style := styles.Status()
			if b.message.err {
				style = styles.Error
			}
			b.statusView.Fill(' ', style)
			b.statusView.DrawText(0, 0, b.message.text, style)
		}

	case ModeCommand, ModeInput:
		b.input.Draw()

	case ModeFollow:
		// Draw hint labels
		for _, hint := range b.hints {
			// Filter out hints that don't match
			if !strings.HasPrefix(hint.Label, b.hint) {
				continue
			}

			prefix := "[" + hint.Label + "]"
			style := styles.Default.Bold(true).
				Background(tcell.ColorYellow).
				Foreground(tcell.ColorBlack)
			b.tabView.DrawText(0, hint.Y, prefix, style)
		}
	}
}

func (b *Browser) Update() {
	b.tabs[b.tab].Update()
}

func (b *Browser) Message(message string) {
	b.message.text = message
	b.message.err = false
}

func (b *Browser) Error(err error) {
	b.message.text = err.Error()
	b.message.err = true
}

func (b *Browser) clearMessage() {
	b.message.text = ""
	b.message.err = false
}

// Event handles events.
func (b *Browser) Event(event tcell.Event) {
	b.mu.Lock()
	defer b.mu.Unlock()

	tab := b.tabs[b.tab]

	switch b.mode {
	case ModeCommand:
		input, ok := b.input.Event(event)
		if !ok {
			return
		}
		b.mode = ModeNormal
		if input == "" {
			return
		}
		b.RunCommand(strings.Fields(input)...)

	case ModeInput:
		input, ok := b.input.Event(event)
		if !ok {
			return
		}
		b.mode = ModeNormal
		if input == "" {
			close(b.inputch)
			b.inputch = nil
			return
		}
		b.inputch <- input
		b.inputch = nil

	case ModeFollow:
		text := tab.Text()
		if text == nil {
			return
		}

		switch event := event.(type) {
		case *tcell.EventKey:
			switch event.Key() {
			case tcell.KeyRune:
				r := event.Rune()
				b.hint += string(r)
				if hint, ok := b.hintMap[b.hint]; ok {
					text.focus = hint.Index
					b.mode = ModeNormal
					b.hint = ""
					b.hints = nil
					b.hintMap = nil
					b.Message("=> " + text.LinkURL(hint.Index))
				}
				b.view.Invalidate()

			case tcell.KeyBackspace:
				if len(b.hint) != 0 {
					b.hint = b.hint[:len(b.hint)-1]
				}

			case tcell.KeyESC:
				b.mode = ModeNormal
				b.hint = ""
				b.hints = nil
				b.hintMap = nil
				b.view.Invalidate()
			}
		}

	default:
		switch event := event.(type) {
		case *tcell.EventKey:
			if cmd, ok := b.config.Binds.Match(event); ok {
				b.Command(cmd...)
				b.view.Invalidate()
				return
			}

			text := tab.Text()
			if text == nil {
				return
			}
			switch event.Key() {
			case tcell.KeyTab:
				if len(text.tabindex) == 0 {
					return
				}

				if text.focus == -1 {
					text.focus = text.tabindex[0]
				} else {
					tabindex := text.lines[text.focus].Tabindex - 1
					tabindex++
					if tabindex < len(text.tabindex) {
						text.focus = text.tabindex[tabindex]
					} else {
						text.focus = -1
					}
				}
				if text.focus != -1 {
					b.tabView.MakeVisible(0, text.pos[text.focus])
					b.Message("=> " + text.LinkURL(text.focus))
				} else {
					b.clearMessage()
				}
				b.view.Invalidate()

			case tcell.KeyBacktab:
				if len(text.tabindex) == 0 {
					return
				}

				if text.focus == -1 {
					text.focus = text.tabindex[len(text.tabindex)-1]
				} else {
					tabindex := text.lines[text.focus].Tabindex - 1
					tabindex--
					if tabindex >= 0 {
						text.focus = text.tabindex[tabindex]
					} else {
						text.focus = -1
					}
				}
				if text.focus != -1 {
					b.tabView.MakeVisible(0, text.pos[text.focus])
					b.Message("=> " + text.LinkURL(text.focus))
				} else {
					b.clearMessage()
				}
				b.view.Invalidate()

			case tcell.KeyEnter:
				if text.focus == -1 {
					return
				}
				b.clearMessage()
				newtab := (event.Modifiers() & tcell.ModAlt) != 0
				url := text.LinkURL(text.focus)
				b.open(tab, text, url, newtab)
				b.view.Invalidate()
			case tcell.KeyESC:
				if len(b.message.text) != 0 {
					b.clearMessage()
					b.view.Invalidate()
				}
				if text.focus == -1 {
					return
				}
				text.focus = -1
				b.view.Invalidate()
			}

		case *tcell.EventMouse:
			switch {
			case b.tabView.Contains(event.Position()):
				text := tab.Text()
				if text == nil {
					return
				}

				// Handle scroll events
				buttons := event.Buttons()
				if buttons&tcell.WheelDown != 0 {
					b.tabView.ScrollDown(3)
					b.view.Invalidate()
					return
				}
				if buttons&tcell.WheelUp != 0 {
					b.tabView.ScrollUp(3)
					b.view.Invalidate()
					return
				}

				// Handle button clicks
				button1 := buttons&tcell.Button1 != 0
				button2 := buttons&tcell.Button2 != 0
				if !button1 && !button2 {
					return
				}

				// Get clicked link
				_, y := b.tabView.GetLocal(event.Position())
				y += b.tabView.ScrollY()
				idx, ok := text.LinkAt(y)
				if !ok {
					if text.focus != -1 {
						// Lose focus
						text.focus = -1
						b.clearMessage()
						b.view.Invalidate()
					}
					return
				}

				url := text.LinkURL(idx)
				if text.focus == idx {
					// Double click -> open
					// Right click -> open in new tab
					text.focus = -1
					b.clearMessage()
					b.open(tab, text, url, button2)
					b.view.Invalidate()
					return
				}

				// Focus on link
				text.focus = idx
				b.Message("=> " + url)
				b.view.Invalidate()

			case b.tablist.Contains(event.Position()):
				// Scroll through tabs
				button := event.Buttons()
				if button&tcell.WheelUp != 0 {
					b.Previous()
					b.view.Invalidate()
				}
				if button&tcell.WheelDown != 0 {
					b.Next()
					b.view.Invalidate()
				}
				if button&tcell.Button1 != 0 {
					// Switch to a tab
					x, _ := event.Position()
					var tx int
					for i := range b.tabs {
						tx += b.tabWidths[i] + 2
						if x < tx {
							b.tab = i
							b.makeTabVisible()
							b.view.Invalidate()
							break
						}
					}
				}
				if button&tcell.Button2 != 0 {
					// Close a tab
					x, _ := event.Position()
					var tx int
					for i := range b.tabs {
						tx += b.tabWidths[i] + 2
						if x < tx {
							b.CloseTab(i)
							b.makeTabVisible()
							b.view.Invalidate()
							break
						}
					}
				}
			}
		}
	}
}

func (b *Browser) open(tab *Tab, text *Text, rawurl string, newtab bool) {
	if text.action != nil {
		text.action(rawurl)
		return
	}

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

	if newtab {
		b.Command("newtab", "&&", "open", url.String())
	} else {
		tab.DoBackground(&gemini.Request{URL: url})
	}
}

func (b *Browser) makeTabVisible() {
	// Make current tab visible
	var x int
	for i := range b.tabs {
		w := b.tabWidths[i] + 2
		if i == b.tab {
			b.tablist.MakeVisible(x+w-1, 0)
			b.tablist.MakeVisible(x, 0)
			break
		}
		x += w
	}
}

func (b *Browser) Command(args ...string) {
	var cmd []string
	for _, s := range args {
		if s == "&&" {
			b.RunCommand(cmd...)
			cmd = nil
			continue
		}
		if s == "$url" {
			s = b.tabs[b.tab].URL()
		}
		cmd = append(cmd, s)
	}
	b.RunCommand(cmd...)
}

func (b *Browser) CommandMode() {
	b.mode = ModeCommand
	b.input.Prompt(":")
}

func (b *Browser) RunCommand(args ...string) {
	if len(args) == 0 {
		return
	}
	b.clearMessage()
	c, ok := commands[args[0]]
	if ok {
		if err := c(b, args[1:]...); err != nil {
			b.Error(err)
		}
	} else {
		b.Error(fmt.Errorf("%q is not a command", args[0]))
	}
}

// Previous switches to the previous tab.
func (b *Browser) Previous() {
	if b.tab > 0 {
		b.tab--
	}
	b.makeTabVisible()
}

// Next switches to the next tab.
func (b *Browser) Next() {
	if b.tab < len(b.tabs)-1 {
		b.tab++
	}
	b.makeTabVisible()
}

// NewTab returns a new tab.
func (b *Browser) NewTab() *Tab {
	return &Tab{
		view:    b.tabView,
		status:  b.statusView,
		browser: b,
	}
}

// InsertTab inserts a tab at the position i.
func (b *Browser) InsertTab(i int, tab *Tab) {
	b.tabs = append(b.tabs, nil)
	b.tabWidths = append(b.tabWidths, 0)
	copy(b.tabs[i+1:], b.tabs[i:])
	b.tabs[i] = tab
}

// CloseTab closes the current tab.
// If only one tab remains, it will quit the browser.
func (b *Browser) CloseTab(i int) {
	if len(b.tabs) > 1 {
		b.tabs[i].Cancel()
		b.tabs[i] = nil
		copy(b.tabs[i:], b.tabs[i+1:])
		b.tabs = b.tabs[:len(b.tabs)-1]
		copy(b.tabWidths[i:], b.tabWidths[i+1:])
		b.tabWidths = b.tabWidths[:len(b.tabWidths)-1]
		if b.tab >= i && b.tab > 0 {
			b.tab--
		}
	} else {
		// Exit
		b.view.Exit()
	}
}

// Input retrieves input from the user.
func (b *Browser) Input(prompt, input string, sensitive bool) (string, bool) {
	ch := make(chan string)

	b.mu.Lock()
	b.mode = ModeInput
	b.input.Prompt(prompt + " ")
	b.input.SetInput(input)
	b.input.Sensitive(sensitive)
	b.inputch = ch
	b.mu.Unlock()

	input, ok := <-ch
	if ok {
		return input, true
	}
	return "", false
}

func (b *Browser) FollowMode() error {
	text := b.tabs[b.tab].Text()
	if text == nil {
		return nil
	}

	// Collect hints
	hints := []Hint{}
	vy := b.tabView.ScrollY()
	_, h := b.tabView.Size()
	for y := vy; y < vy+h && y < len(text.wrapped); y++ {
		line := text.wrapped[y]
		if line.Type != LineLink || line.Wrapped {
			continue
		}
		hints = append(hints, Hint{
			Index: line.Index,
			Y:     y,
		})
	}

	// Don't enter follow mode if there are no hints
	if len(hints) == 0 {
		return nil
	}

	letters := b.config.Follow.Letters
	if len(letters) == 0 {
		return fmt.Errorf("no label letters configured")
	}

	// Label hints
	hintMap := map[string]Hint{}
	for i, label := range makeHintLabels(letters, len(hints)) {
		hints[i].Label = label
		hintMap[label] = hints[i]
	}

	b.mode = ModeFollow
	b.hints = hints
	b.hintMap = hintMap
	b.view.Invalidate()
	return nil
}

// Based on Qutebrowser's 'scattered' hints algorithm.
func makeHintLabels(chars string, length int) []string {
	needed := ceilLog(length, len(chars))

	nshort := 0
	if needed > 1 {
		space := int(math.Pow(float64(len(chars)), float64(needed)))
		nshort = (space - length) / (len(chars) - 1)
	}

	var hints []string
	if needed > 1 {
		for i := 0; i < nshort; i++ {
			hints = append(hints, makeHintLabel(i, chars, needed-1))
		}
	}
	start := nshort * len(chars)
	nlong := length - nshort
	for i := start; i < start+nlong; i++ {
		hints = append(hints, makeHintLabel(i, chars, needed))
	}
	// Shuffle hints
	rand := rand.New(rand.NewSource(int64(length)))
	rand.Shuffle(len(hints), func(i, j int) {
		hints[i], hints[j] = hints[j], hints[i]
	})
	return hints
}

func ceilLog(x, base int) int {
	if x < 1 || base < 2 {
		panic(fmt.Errorf("ceilLog(%d, %d): invalid arguments", x, base))
	}
	result := 1
	accum := base
	for accum < x {
		result += 1
		accum *= base
	}
	return result
}

func makeHintLabel(num int, chars string, length int) string {
	var hint []byte
	base := len(chars)
	for {
		remainder := num % base
		hint = append(hint, 0)
		copy(hint[1:], hint[0:])
		hint[0] = chars[remainder]
		num -= remainder
		num /= base
		if num <= 0 {
			break
		}
	}
	// Pad the hint string to length
	for i := 0; i < length-len(hint); i++ {
		hint = append(hint, chars[0])
	}
	return string(hint)
}