~adnano/astronaut

ref: c2cbc6b7e5ba6ccdb1e473261a134a4e897e6d46 astronaut/browser.go -rw-r--r-- 9.3 KiB
c2cbc6b7Adnan Maolood settings: Remove unused code 3 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
package main

import (
	"astronaut/binds"
	"astronaut/styles"
	"astronaut/text"
	"astronaut/ui"
	"fmt"
	"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
)

// 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
	settings  *Settings

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

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

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

	b.status.SetView(b.statusView)
	b.input.SetView(b.inputView)

	// TODO: Handle errors here better

	// Load settings
	settingsPath := filepath.Join(xdg.ConfigHome(), "astronaut", "settings.json")
	os.MkdirAll(filepath.Dir(settingsPath), 0755)
	b.settings = &Settings{}
	b.settings.Load(settingsPath)

	// Load known hosts
	knownHostsPath := filepath.Join(xdg.DataHome(), "astronaut", "known_hosts")
	os.MkdirAll(filepath.Dir(knownHostsPath), 0700)
	b.hosts.Load(knownHostsPath)
	b.hostsFile, _ = tofu.OpenHostsFile(knownHostsPath)

	// Load client certificates
	certsDir := filepath.Join(xdg.DataHome(), "astronaut", "certificates")
	os.MkdirAll(certsDir, 0700)
	b.certs.Load(certsDir)

	// Load bookmarks
	bookmarks := filepath.Join(xdg.DataHome(), "astronaut", "bookmarks.gmi")
	b.bookmarks.Open(bookmarks)

	// Create cache directory
	cacheDir = filepath.Join(xdg.CacheHome(), "astronaut")
	os.MkdirAll(cacheDir, 0755)

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

	b.input.Callback(b.onInput)

	return b
}

// onInput is called on input from the status bar.
func (b *Browser) onInput(input string, ok bool) {
	b.mu.Lock()
	defer b.mu.Unlock()
	if b.mode == ModeCommand {
		b.mode = ModeNormal
		if !ok {
			return
		}
		b.RunCommand(input)
	} else if b.inputch != nil {
		if ok {
			b.inputch <- input
		} else {
			close(b.inputch)
		}
		b.inputch = nil
		b.status.Clear()
		b.view.Invalidate()
	}
}

func (b *Browser) Resize(x, y, w, h int) {
	b.view.Resize(x, y, w, h)
	b.tablist.Resize(x, y, w, 1)
	b.tabView.Resize(x, y+1, w, h-3)
	b.statusView.Resize(x, y+h-2, w, 1)
	b.inputView.Resize(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, _ = text.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()
	}

	b.status.Draw()
	b.input.Draw()
}

func (b *Browser) Update() {
	// Calculate scroll indicator
	_, y := b.tabView.Visible()
	_, vh := b.tabView.Size()
	_, h := b.tabView.GetContentSize()
	h -= vh - 1
	var scroll string
	switch {
	case y == 0 && h <= vh:
		scroll = "All"
	case y == 0:
		scroll = "Top"
	case y >= h-vh:
		scroll = "Bot"
	default:
		x := int(float64(y) / float64(h-vh) * 100)
		scroll = fmt.Sprintf("%d%%", x)
	}

	tab := b.tabs[b.tab]
	b.status.Update(tab.URL(), tab.MediaType(), scroll)
	b.status.Spinner.Update(b.view, tab.Busy())
}

// Event handles events.
func (b *Browser) Event(event tcell.Event) {
	if event, ok := event.(*tcell.EventResize); ok {
		b.view.Clear()
		b.view.Invalidate()
		w, h := event.Size()
		b.Resize(0, 0, w, h)
		return
	}

	if b.input.Event(event) {
		return
	}
	if b.tabs[b.tab].Event(event) {
		return
	}

	switch event := event.(type) {
	case *tcell.EventKey:
		switch {
		case event.Rune() == ':':
			b.CommandPrompt()
		case binds.Match(binds.Open, event):
			b.Command("open ")
			b.view.Invalidate()
		case binds.Match(binds.OpenNew, event):
			b.Command("newtab\nopen ")
			b.view.Invalidate()
		case binds.Match(binds.Edit, event):
			t := b.tabs[b.tab]
			b.Command("open " + t.URL())
			b.view.Invalidate()
		case binds.Match(binds.EditNew, event):
			t := b.tabs[b.tab]
			b.Command("newtab\nopen " + t.URL())
			b.view.Invalidate()
		case binds.Match(binds.Clone, event):
			b.Command("clone\n")
			b.view.Invalidate()
		case binds.Match(binds.Reload, event):
			b.Command("reload\n")
			b.view.Invalidate()
		case event.Key() == tcell.KeyESC:
			b.status.Clear()
		case binds.Match(binds.Cancel, event):
			b.Command("cancel\n")
			b.view.Invalidate()
		case binds.Match(binds.Back, event):
			b.Command("back\n")
			b.view.Invalidate()
		case binds.Match(binds.Forward, event):
			b.Command("forward\n")
			b.view.Invalidate()
		case binds.Match(binds.Previous, event):
			b.Command("prev\n")
			b.view.Invalidate()
		case binds.Match(binds.Next, event):
			b.Command("next\n")
			b.view.Invalidate()
		case binds.Match(binds.Quit, event):
			b.Command("quit\n")
			b.view.Invalidate()
		case binds.Match(binds.NewTab, event):
			b.Command("newtab\n")
			b.view.Invalidate()
		case binds.Match(binds.CloseTab, event):
			b.Command("close\n")
			b.view.Invalidate()
		case binds.Match(binds.Bookmark, event):
			b.Command("bookmark\n")
			b.view.Invalidate()
		case binds.Match(binds.Search, event):
			b.Command("search ")
			b.view.Invalidate()
		case binds.Match(binds.Bookmarks, event):
			b.tabs[b.tab].Get("about://bookmarks")
			b.view.Invalidate()
		case binds.Match(binds.History, event):
			b.tabs[b.tab].Get("about://history")
			b.view.Invalidate()
		}

	case *tcell.EventMouse:
		if _, y := event.Position(); y == 0 {
			button := event.Buttons()
			// Scroll through tabs
			if button&tcell.WheelUp != 0 {
				b.Previous()
				b.makeTabVisible()
				b.view.Invalidate()
			}
			if button&tcell.WheelDown != 0 {
				b.Next()
				b.makeTabVisible()
				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) 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(cmd string) {
	// Run all commands followed by a newline
	// Leave any remaining text in the prompt
	s := strings.Split(cmd, "\n")
	for i := 0; i < len(s)-1; i++ {
		b.RunCommand(s[i])
	}
	if len(s) != 0 && s[len(s)-1] != "" {
		b.CommandPrompt()
		b.input.SetInput(s[len(s)-1])
	}
}

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

func (b *Browser) RunCommand(cmd string) {
	args := strings.Split(cmd, " ")
	if len(args) == 0 {
		return
	}
	c, ok := commands[args[0]]
	if ok {
		c(b, args[1:]...)
	} else {
		b.status.Info(fmt.Sprintf("Error: %q is not a command", args[0]))
	}
}

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

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

// NewTab returns a new tab.
func (b *Browser) NewTab() *Tab {
	return &Tab{
		view:    b.tabView,
		status:  &b.status,
		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()
	}
}

func (b *Browser) Inputch() chan string {
	ch := make(chan string)
	b.mu.Lock()
	defer b.mu.Unlock()
	b.inputch = ch
	return ch
}

// getInput is called to retrieve input when a server requests it.
func (b *Browser) getInput(prompt string, sensitive bool) (string, bool) {
	b.mu.Lock()
	b.input.Prompt(prompt + " ")
	b.input.Sensitive(sensitive)
	b.mu.Unlock()

	ch := b.Inputch()
	input, ok := <-ch
	if ok {
		return input, true
	}
	return "", false
}