-
Notifications
You must be signed in to change notification settings - Fork 1
/
main.go
1735 lines (1600 loc) · 39.6 KB
/
main.go
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
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package main
import (
"bufio"
"bytes"
"context"
"crypto/sha256"
"crypto/tls"
"encoding/hex"
"fmt"
"io"
"io/ioutil"
"mime"
"net/url"
"os"
"os/signal"
"path"
"sort"
"strconv"
"strings"
"syscall"
"time"
"unicode"
"github.com/a-h/gemini"
"github.com/a-h/gemini/cert"
"github.com/gdamore/tcell"
"github.com/mattn/go-runewidth"
"github.com/natefinch/atomic"
"github.com/pkg/browser"
"golang.org/x/text/encoding/ianaindex"
"golang.org/x/text/transform"
)
var version string
type ClientCertPrefix string
func (cc ClientCertPrefix) fileName() string {
ss := sha256.New()
ss.Write([]byte(cc))
fn := hex.EncodeToString(ss.Sum(nil))
return path.Join(configPath, fn)
}
func (cc ClientCertPrefix) Load() (tls.Certificate, error) {
fn := cc.fileName()
return tls.LoadX509KeyPair(fn+".cert", fn+".key")
}
func (cc ClientCertPrefix) Save(cert, key []byte) error {
fn := cc.fileName()
if err := atomic.WriteFile(fn+".cert", bytes.NewReader(cert)); err != nil {
return err
}
return atomic.WriteFile(fn+".key", bytes.NewReader(key))
}
var configPath = func() string {
configPath, _ := os.UserConfigDir()
return path.Join(configPath, ".min")
}()
type Config struct {
Home string
Width int
MaximumHistory int
HostCertificates map[string]string
ClientCertPrefixes map[ClientCertPrefix]struct{}
}
func (c *Config) Save() error {
b := new(bytes.Buffer)
fmt.Fprintf(b, "home=%v\n", c.Home)
fmt.Fprintf(b, "width=%v\n", c.Width)
fmt.Fprintf(b, "maxhistory=%v\n", c.MaximumHistory)
for prefix := range c.ClientCertPrefixes {
fmt.Fprintf(b, "clientcert=%v\n", prefix)
}
for host, cert := range c.HostCertificates {
fmt.Fprintf(b, "hostcert/%v=%v\n", host, cert)
}
fn := path.Join(configPath, "config.ini")
return atomic.WriteFile(fn, b)
}
func NewConfig() (c *Config, err error) {
c = &Config{
Home: "gemini://gus.guru",
Width: 80,
MaximumHistory: 128,
HostCertificates: map[string]string{},
ClientCertPrefixes: map[ClientCertPrefix]struct{}{},
}
os.MkdirAll(configPath, os.ModePerm)
lines, err := readLines(path.Join(configPath, "config.ini"))
if err != nil {
return
}
for _, l := range lines {
kv := strings.SplitN(l, "=", 2)
if len(kv) != 2 {
continue
}
k, v := strings.ToLower(strings.TrimSpace(kv[0])), strings.TrimSpace(kv[1])
switch k {
case "home":
c.Home = v
case "width":
w, err := strconv.ParseInt(v, 10, 64)
if err != nil {
return c, err
}
c.Width = int(w)
case "maxhistory":
m, err := strconv.ParseInt(v, 10, 64)
if err != nil {
return c, err
}
c.MaximumHistory = int(m)
case "clientcert":
c.ClientCertPrefixes[ClientCertPrefix(v)] = struct{}{}
}
if strings.HasPrefix(k, "hostcert/") {
host := strings.TrimPrefix(k, "hostcert/")
c.HostCertificates[host] = v
}
}
return
}
func readLines(fn string) (lines []string, err error) {
f, err := os.Open(fn)
if err != nil {
if os.IsNotExist(err) {
err = nil
}
return
}
defer f.Close()
scanner := bufio.NewScanner(f)
for scanner.Scan() {
lines = append(lines, scanner.Text())
}
err = scanner.Err()
return
}
var defaultStyle = tcell.StyleDefault.
Foreground(tcell.ColorWhite).
Background(tcell.ColorBlack)
var preformattedStyle = tcell.StyleDefault.
Foreground(tcell.ColorGray).
Background(tcell.ColorBlack)
func main() {
if len(os.Args) > 1 && strings.TrimLeft(os.Args[1], "-") == "version" {
fmt.Println(version)
return
}
// Configure the context to handle SIGINT.
ctx, cancel := context.WithCancel(context.Background())
c := make(chan os.Signal)
signal.Notify(c, os.Interrupt, syscall.SIGTERM)
defer func() {
signal.Stop(c)
cancel()
}()
go func() {
select {
case <-c:
cancel()
case <-ctx.Done():
}
os.Exit(2)
}()
// Setup config.
conf, err := NewConfig()
if err != nil {
fmt.Println("Error loading config:", err)
os.Exit(1)
}
// Create the history file.
h, historyCloser, err := NewHistory(conf.MaximumHistory, path.Join(configPath, "history.tsv"))
if err != nil {
fmt.Println("Error loading history:", err)
os.Exit(1)
}
defer historyCloser()
// Create the boookmarks file.
b, bookmarksCloser, err := NewBookmarks(path.Join(configPath, "bookmarks.tsv"))
if err != nil {
fmt.Println("Error loading bookmarks:", err)
os.Exit(1)
}
defer bookmarksCloser()
// State.
state := &State{
URL: conf.Home,
History: h,
Bookmarks: b,
Conf: conf,
Context: ctx,
}
// Use a URL passed via the command-line URL, if provided.
if len(os.Args) > 1 {
state.URL = strings.Join(os.Args[1:], "")
}
// Create client.
state.Client = gemini.NewClient()
for host, cert := range conf.HostCertificates {
state.Client.AddServerCertificate(host, cert)
}
for prefix := range conf.ClientCertPrefixes {
cert, err := prefix.Load()
if err != nil {
NewOptions(state.Screen, fmt.Sprintf("Error loading client certificate\n\nURL: %v\nMessage: %v", prefix, err), "Continue").Focus()
continue
}
state.Client.AddClientCertificate(string(prefix), cert)
}
// Create a screen.
tcell.SetEncodingFallback(tcell.EncodingFallbackASCII)
s, err := tcell.NewScreen()
if err != nil {
fmt.Println("Error creating screen:", err)
os.Exit(1)
}
if err = s.Init(); err != nil {
fmt.Println("Error initializing screen:", err)
os.Exit(1)
}
defer s.Fini()
s.SetStyle(defaultStyle)
state.Screen = s
run(state)
}
type State struct {
URL string
History *History
Bookmarks *Bookmarks
Screen tcell.Screen
Client *gemini.Client
Conf *Config
RedirectCount int
U *url.URL
Response *gemini.Response
Context context.Context
}
type Action string
const (
ActionHome Action = ""
ActionAskForURL Action = "AskForURL"
ActionNavigate Action = "Navigate"
ActionDisplay Action = "Display"
ActionToggleBookmark Action = "ToggleBookmark"
ActionViewHistory Action = "ViewHistory"
ActionViewBookmarks Action = "ViewBookmarks"
ActionGoBack Action = "Back"
ActionGoForward Action = "Forward"
ActionViewHelp Action = "Help"
ActionExit Action = "Exit"
)
func run(state *State) {
var action Action
for {
switch action {
case ActionExit:
return
case ActionHome:
action = handleActionHome(state)
case ActionGoBack:
state.History.Back()
action = ActionDisplay
case ActionGoForward:
state.History.Forward()
action = ActionDisplay
case ActionViewBookmarks:
action = handleActionView(state, action)
case ActionViewHelp:
action = handleActionView(state, action)
case ActionViewHistory:
action = handleActionView(state, action)
case ActionToggleBookmark:
action = handleActionToggleBookmark(state)
case ActionAskForURL:
action = handleActionAskForURL(state)
case ActionNavigate:
action = handleActionNavigate(state)
case ActionDisplay:
action = handleActionDisplay(state)
}
}
}
func handleActionHome(state *State) Action {
switch NewOptions(state.Screen, "Welcome to the min browser", "Enter URL", "View History", "View Bookmarks", "Help", "Exit").Focus() {
case "Enter URL":
return ActionAskForURL
case "View History":
return ActionViewHistory
case "View Bookmarks":
return ActionViewBookmarks
case "Help":
return ActionViewHelp
case "Exit":
return ActionExit
}
return ActionExit
}
func handleActionView(state *State, action Action) Action {
var vu *url.URL
var vr *gemini.Response
switch action {
case ActionViewHistory:
vu, vr = state.History.All()
case ActionViewBookmarks:
vu, vr = state.Bookmarks.All()
case ActionViewHelp:
vu, vr = Help()
}
b, err := NewBrowser(state.Screen, state.Conf.Width, vu, vr.Body)
if err != nil {
NewOptions(state.Screen, fmt.Sprintf("Error loading %v: %v", b.URL.String(), err), "Continue").Focus()
return action
}
if err = state.History.Add(b); err != nil {
NewOptions(state.Screen, fmt.Sprintf("Unable to persist history to disk: %v", err), "OK").Focus()
}
return ActionDisplay
}
func handleActionToggleBookmark(state *State) Action {
if state.Bookmarks.Contains(state.U) {
if NewOptions(state.Screen, fmt.Sprintf("Remove bookmark: %v", state.U), "Yes", "No").Focus() == "Yes" {
state.Bookmarks.Remove(state.U)
}
} else {
if NewOptions(state.Screen, fmt.Sprintf("Add bookmark: %v", state.U), "Yes", "No").Focus() == "Yes" {
state.Bookmarks.Add(state.U)
}
}
return ActionDisplay
}
func handleActionAskForURL(state *State) (action Action) {
var ok bool
state.URL, ok = NewInput(state.Screen, "Enter URL:", state.URL).Focus()
if !ok {
return ActionHome
}
var err error
state.U, err = url.Parse(state.URL)
if err != nil {
NewOptions(state.Screen, fmt.Sprintf("Error parsing URL\n\nURL: %v\nMessage: %v", state.URL, err), "Continue").Focus()
return ActionAskForURL
}
return ActionNavigate
}
func handleActionNavigate(state *State) (action Action) {
var certificates []string
out:
for {
var ok bool
var err error
state.Response, certificates, _, ok, err = state.Client.RequestURL(state.Context, state.U)
if err != nil {
switch NewOptions(state.Screen, fmt.Sprintf("Error making request\n\nURL: %v\nMessage: %v", state.U, err), "Retry", "Cancel").Focus() {
case "Retry":
continue
case "Cancel":
break out
}
}
if !ok {
// TOFU check required.
switch NewOptions(state.Screen, fmt.Sprintf("Accept server certificate?\n %v", certificates[0]), "Accept (Permanent)", "Accept (Temporary)", "Reject").Focus() {
case "Accept (Permanent)":
state.Conf.HostCertificates[state.U.Host] = certificates[0]
state.Conf.Save()
state.Client.AddServerCertificate(state.U.Host, certificates[0])
continue
case "Accept (Temporary)":
state.Client.AddServerCertificate(state.U.Host, certificates[0])
continue
case "Reject":
break out
}
}
break
}
if state.Response == nil {
return ActionGoBack
}
if strings.HasPrefix(string(state.Response.Header.Code), "3") { // Redirect
return handleRedirectResponse(state)
}
state.RedirectCount = 0
if strings.HasPrefix(string(state.Response.Header.Code), "6") { // Client certificate required
return handleClientCertificateResponse(state)
}
if strings.HasPrefix(string(state.Response.Header.Code), "1") { // Input
text, ok := NewInput(state.Screen, state.Response.Header.Meta, "").Focus()
if !ok {
return ActionDisplay
}
// Post the input back.
state.U.RawQuery = url.QueryEscape(text)
state.URL = state.U.String()
return ActionNavigate
}
if strings.HasPrefix(string(state.Response.Header.Code), "2") { // Success
handleSuccessResponse(state)
return ActionDisplay
}
NewOptions(state.Screen, fmt.Sprintf("Error returned by server\n\nURL: %v\nCode: %v\nMeta: %s", state.U.String(), state.Response.Header.Code, state.Response.Header.Meta), "OK").Focus()
return ActionDisplay
}
func handleActionDisplay(state *State) (action Action) {
if state.History.Current() == nil {
return ActionHome
}
browserAction, navigateTo, err := state.History.Current().Focus()
if err != nil {
NewOptions(state.Screen, fmt.Sprintf("Error displaying URL\n\nURL: %v\nMessage: %v", navigateTo, err), "OK").Focus()
return ActionGoBack
}
if browserAction == ActionNavigate {
if navigateTo != nil {
if navigateTo.Scheme != "gemini" {
if open := NewOptions(state.Screen, fmt.Sprintf("Open in browser?\n\n %v", navigateTo.String()), "Yes", "No").Focus(); open == "Yes" {
browser.OpenURL(navigateTo.String())
}
state.History.Back()
return ActionNavigate
}
state.URL = navigateTo.String()
state.U = navigateTo
}
}
return browserAction
}
func handleClientCertificateResponse(state *State) Action {
msg := fmt.Sprintf("The server has requested a certificate\n\nURL: %s\nCode: %s\nMeta: %s", state.U.String(), state.Response.Header.Code, state.Response.Header.Meta)
certificateOption := NewOptions(state.Screen, msg, "Create (Permanent)", "Create (Temporary)", "Cancel").Focus()
if certificateOption == "Cancel" {
return ActionDisplay
}
permanent := strings.Contains(certificateOption, "Permanent")
duration := time.Hour * 24
if permanent {
duration *= 365 * 200
}
cert, key, _ := cert.Generate("", "", "", duration)
keyPair, err := tls.X509KeyPair(cert, key)
if err != nil {
NewOptions(state.Screen, fmt.Sprintf("Error creating certificate: %v", err), "Continue").Focus()
return ActionDisplay
}
prefix := ClientCertPrefix(state.U.Scheme + "://" + state.U.Host + state.U.Path)
state.Client.AddClientCertificate(string(prefix), keyPair)
if permanent {
if err = prefix.Save(cert, key); err != nil {
NewOptions(state.Screen, fmt.Sprintf("Error saving certificate: %v", err), "Continue").Focus()
return ActionDisplay
}
state.Conf.ClientCertPrefixes[prefix] = struct{}{}
if err = state.Conf.Save(); err != nil {
NewOptions(state.Screen, fmt.Sprintf("Error saving configuration: %v", err), "Continue").Focus()
return ActionDisplay
}
}
return ActionNavigate
}
func handleRedirectResponse(state *State) Action {
state.RedirectCount++
if state.RedirectCount >= 5 {
if keepTrying := NewOptions(state.Screen, fmt.Sprintf("The server issued 5 redirects, keep trying?"), "Keep Trying", "Cancel").Focus(); keepTrying == "Keep Trying" {
state.RedirectCount = 0
return ActionNavigate
}
return ActionDisplay
}
redirectTo, err := url.Parse(state.Response.Header.Meta)
if err != nil {
NewOptions(state.Screen, fmt.Sprintf("The server returned an invalid redirect URL\n\nURL: %v\nCode: %v\nMeta: %s", state.U.String(), state.Response.Header.Code, state.Response.Header.Meta), "Cancel").Focus()
return ActionDisplay
}
// Check with the user if the redirect is to another protocol or domain.
redirectTo = state.U.ResolveReference(redirectTo)
if redirectTo.Scheme != "gemini" {
if open := NewOptions(state.Screen, fmt.Sprintf("Follow non-gemini redirect?\n\n %v", redirectTo.String()), "Yes", "No").Focus(); open == "Yes" {
browser.OpenURL(redirectTo.String())
}
return ActionDisplay
}
if redirectTo.Host != state.U.Host {
if open := NewOptions(state.Screen, fmt.Sprintf("Follow cross-domain redirect?\n\n %v", redirectTo.String()), "Yes", "No").Focus(); open == "No" {
return ActionAskForURL
}
}
state.URL = redirectTo.String()
state.U = redirectTo
return ActionNavigate
}
func handleSuccessResponse(state *State) {
meta := state.Response.Header.Meta
if meta == "" {
meta = "text/gemini; charset=utf-8"
}
mediaType, params, err := mime.ParseMediaType(meta)
if err != nil {
NewOptions(state.Screen, fmt.Sprintf("Server returned invalid MIME type: %v", err), "OK").Focus()
return
}
if !(mediaType == "text/gemini" || mediaType == "text/plain") {
fileName := getFileNameFromURL(state.U, mediaType)
tmp := path.Join(os.TempDir(), fileName)
err := atomic.WriteFile(tmp, state.Response.Body)
if err != nil {
NewOptions(state.Screen, fmt.Sprintf("Failed to save file: %v", err), "OK").Focus()
return
}
switch NewOptions(state.Screen, fmt.Sprintf("Server returned a %q file (%v)\n\n%s", meta, fileName, state.U.String()), "Open", "Keep", "Discard").Focus() {
case "Open":
browser.OpenFile(tmp)
case "Keep":
_, err = copy(tmp, fileName)
if err != nil {
NewOptions(state.Screen, fmt.Sprintf("Failed to save file: %v", err), "OK").Focus()
return
}
case "Discard":
os.Remove(tmp)
}
return
}
// Use the charset to load the content.
var cs string
cs, ok := params["charset"]
if !ok || cs == "us-ascii" { // Remove us-ascii check at next Go release https://github.com/golang/text/commit/a8b4671254579a87fadf9f7fa577dc7368e9d009
cs = "utf-8"
}
e, err := ianaindex.MIME.Encoding(cs)
if err != nil || e == nil {
NewOptions(state.Screen, fmt.Sprintf("Unsupported character set %q: %v", cs, err), "OK").Focus()
return
}
r := transform.NewReader(state.Response.Body, e.NewDecoder())
b, err := NewBrowser(state.Screen, state.Conf.Width, state.U, r)
if err != nil {
NewOptions(state.Screen, fmt.Sprintf("Error displaying server response: %v", err), "OK").Focus()
return
}
if err = state.History.Add(b); err != nil {
NewOptions(state.Screen, fmt.Sprintf("Unable to persist history to disk: %v", err), "OK").Focus()
}
return
}
func copy(src, dst string) (int64, error) {
sourceFileStat, err := os.Stat(src)
if err != nil {
return 0, err
}
if !sourceFileStat.Mode().IsRegular() {
return 0, fmt.Errorf("%s is not a regular file", src)
}
source, err := os.Open(src)
if err != nil {
return 0, err
}
defer source.Close()
destination, err := os.Create(dst)
if err != nil {
return 0, err
}
defer destination.Close()
nBytes, err := io.Copy(destination, source)
return nBytes, err
}
func getFileNameFromURL(u *url.URL, mimeType string) string {
fileName := path.Base(u.String())
if fileName == "." {
fileName = fmt.Sprintf("download_%d", time.Now().Unix())
}
if path.Ext(fileName) == "" {
extensions, _ := mime.ExtensionsByType(mimeType)
if len(extensions) > 0 {
fileName += extensions[0]
}
}
return fileName
}
// flow breaks up text to its maximum width.
func flow(s string, maxWidth int) []string {
var ss []string
flowProcessor(s, maxWidth, func(line string) {
ss = append(ss, line)
})
return ss
}
func flowProcessor(s string, maxWidth int, out func(string)) {
var buf strings.Builder
var col int
var lastSpace int
for _, r := range s {
if r == '\r' {
continue
}
if r == '\n' {
out(buf.String())
buf.Reset()
col = 0
lastSpace = 0
continue
}
buf.WriteRune(r)
if unicode.IsSpace(r) {
lastSpace = col
}
if col == maxWidth {
// If the word is greater than the width, then break the word down.
end := lastSpace
if end == 0 {
end = col
}
out(strings.TrimSpace(buf.String()[:end]))
prefix := strings.TrimSpace(buf.String()[end:])
buf.Reset()
lastSpace = 0
buf.WriteString(prefix)
col = len(prefix)
continue
}
col++
}
out(buf.String())
}
func NewText(s tcell.Screen, text string) *Text {
return &Text{
Screen: s,
X: 0,
Y: 0,
Style: defaultStyle,
Text: text,
}
}
type Text struct {
Screen tcell.Screen
X int
Y int
MaxWidth int
Style tcell.Style
Text string
}
func (t *Text) WithOffset(x, y int) *Text {
t.X = x
t.Y = y
return t
}
func (t *Text) WithMaxWidth(x int) *Text {
t.MaxWidth = x
return t
}
func (t *Text) WithStyle(st tcell.Style) *Text {
t.Style = st
return t
}
func (t *Text) Draw() (x, y int) {
maxX, _ := t.Screen.Size()
maxWidth := maxX - t.X
if t.MaxWidth > 0 && maxWidth > t.MaxWidth {
maxWidth = t.MaxWidth
}
lines := flow(t.Text, maxWidth)
var requiredMaxWidth int
for lineIndex := 0; lineIndex < len(lines); lineIndex++ {
y = t.Y + lineIndex
x = t.X
for _, c := range lines[lineIndex] {
var comb []rune
w := runewidth.RuneWidth(c)
if w == 0 {
comb = []rune{c}
c = ' '
w = 1
}
t.Screen.SetContent(x, y, c, comb, t.Style)
x += w
if x > requiredMaxWidth {
requiredMaxWidth = x
}
}
}
return requiredMaxWidth, y
}
type Choice struct {
Index int
Option string
}
func ChoiceOptionIndex(options ...string) (op []string) {
op = make([]string, len(options))
for i := range options {
op[i] = strconv.FormatInt(int64(i), 10)
}
return op
}
func choiceIndex(options []string, s string) (index int, matchesPrefix bool) {
index = -1
for i, c := range options {
if c == s {
index = i
continue
}
if strings.HasPrefix(c, s) {
matchesPrefix = true
}
}
return
}
func NewChoice(options ...string) (runes chan rune, selection chan Choice, closer func()) {
var buffer string
runes = make(chan rune)
selection = make(chan Choice)
var ctx context.Context
ctx, closer = context.WithCancel(context.Background())
go func(ctx context.Context) {
defer close(runes)
defer close(selection)
index := -1
var matchesPrefix bool
for {
select {
case <-time.After(time.Millisecond * 200):
if index > -1 {
selection <- Choice{Index: index, Option: options[index]}
index = -1
}
buffer = ""
case r := <-runes:
buffer += string(r)
index, matchesPrefix = choiceIndex(options, buffer)
if index < 0 {
buffer = ""
continue
}
if matchesPrefix {
continue // Wait to see if any more is typed in.
}
selection <- Choice{Index: index, Option: options[index]}
index = -1
buffer = ""
case <-ctx.Done():
return
}
}
}(ctx)
return
}
func NewOptions(s tcell.Screen, msg string, opts ...string) *Options {
cancelIndex := -1
for i, o := range opts {
if o == "Cancel" || o == "Exit" {
cancelIndex = i
break
}
}
return &Options{
Screen: s,
Style: defaultStyle,
Message: msg,
Options: opts,
CancelIndex: cancelIndex,
}
}
type Options struct {
Screen tcell.Screen
X int
Y int
Style tcell.Style
Message string
Options []string
ActiveIndex int
CancelIndex int
}
func (o *Options) Draw() {
o.Screen.Clear()
t := NewText(o.Screen, o.Message)
_, y := t.Draw()
for i, oo := range o.Options {
style := defaultStyle
var prefix = " "
if i == o.ActiveIndex {
style = defaultStyle.Background(tcell.ColorGray)
prefix = ">"
}
NewText(o.Screen, fmt.Sprintf("%s [%d] %s", prefix, i, oo)).WithOffset(1, i+y+2).WithStyle(style).Draw()
}
}
func (o *Options) Up() {
if o.ActiveIndex == 0 {
o.ActiveIndex = len(o.Options) - 1
return
}
o.ActiveIndex--
}
func (o *Options) Down() {
if o.ActiveIndex == len(o.Options)-1 {
o.ActiveIndex = 0
return
}
o.ActiveIndex++
}
func (o *Options) Focus() string {
runes, selection, closer := NewChoice(ChoiceOptionIndex(o.Options...)...)
defer closer()
go func() {
for choice := range selection {
o.ActiveIndex = choice.Index
o.Screen.PostEvent(nil)
}
}()
o.Draw()
o.Screen.Show()
for {
switch ev := o.Screen.PollEvent().(type) {
case *tcell.EventResize:
o.Screen.Sync()
case *tcell.EventKey:
switch ev.Key() {
case tcell.KeyBacktab:
o.Up()
case tcell.KeyTab:
o.Down()
case tcell.KeyUp:
o.Up()
case tcell.KeyDown:
o.Down()
case tcell.KeyEscape:
if o.CancelIndex > -1 {
return o.Options[o.CancelIndex]
}
case tcell.KeyRune:
runes <- ev.Rune()
case tcell.KeyEnter:
return o.Options[o.ActiveIndex]
}
}
o.Draw()
o.Screen.Show()
}
}
func NewLineConverter(r io.Reader, width int) *LineConverter {
return &LineConverter{
Reader: r,
MaxWidth: width,
}
}
type LineConverter struct {
Reader io.Reader
MaxWidth int
preFormatted bool
}
func (lc *LineConverter) process(s string) (l Line, isVisualLine bool) {
if strings.HasPrefix(s, "```") {
lc.preFormatted = !lc.preFormatted
return l, false
}
if lc.preFormatted {
return PreformattedTextLine{Text: s}, true
}
if strings.HasPrefix(s, "=>") {
return LinkLine{Text: s, MaxWidth: lc.MaxWidth}, true
}
if strings.HasPrefix(s, "#") {
return HeadingLine{Text: s, MaxWidth: lc.MaxWidth}, true
}
if strings.HasPrefix(s, "* ") {
return UnorderedListItemLine{Text: s, MaxWidth: lc.MaxWidth}, true
}
if strings.HasPrefix(s, ">") {
return QuoteLine{Text: s, MaxWidth: lc.MaxWidth}, true
}
return TextLine{Text: s, MaxWidth: lc.MaxWidth}, true
}
func (lc *LineConverter) Lines() (lines []Line, err error) {
reader := bufio.NewReader(lc.Reader)
var s string
for {
s, err = reader.ReadString('\n')
line, isVisual := lc.process(strings.TrimRight(s, "\n"))
if isVisual {
lines = append(lines, line)
}
if err != nil {
break
}
}
if err == io.EOF {
err = nil
}
return
}
type Line interface {
Draw(to tcell.Screen, atX, atY int, highlighted bool) (x, y int)
}
type TextLine struct {
Text string
MaxWidth int
}
func (l TextLine) Draw(to tcell.Screen, atX, atY int, highlighted bool) (x, y int) {
return NewText(to, l.Text).WithOffset(atX, atY).WithMaxWidth(l.MaxWidth).Draw()
}
type PreformattedTextLine struct {
Text string
}
func (l PreformattedTextLine) Draw(to tcell.Screen, atX, atY int, highlighted bool) (x, y int) {
for _, c := range l.Text {
var comb []rune
w := runewidth.RuneWidth(c)
if w == 0 {
comb = []rune{c}
c = ' '
w = 1
}
to.SetContent(atX, atY, c, comb, preformattedStyle)
atX += w
}
return atX, atY
}
type LinkLine struct {
Text string
MaxWidth int
}
func (l LinkLine) URL(relativeTo *url.URL) (u *url.URL, err error) {
var urlString []rune
for _, r := range strings.TrimSpace(strings.TrimPrefix(l.Text, "=>")) {
if unicode.IsSpace(r) {
break
}
urlString = append(urlString, r)
}
u, err = url.Parse(string(urlString))
if err != nil {
return
}
if relativeTo == nil {
return
}