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
|
package ui
import (
"context"
"fmt"
"log/slog"
"sync"
"github.com/gdamore/tcell/v2"
"github.com/rivo/tview"
"github.com/urfave/cli/v2"
"git.gabrielgio.me/dict/db"
)
var UICommand = &cli.Command{
Name: "ui",
Usage: "interactive dictionary",
Flags: []cli.Flag{
&cli.StringFlag{
Name: "database",
Value: "main.dict",
Usage: "Dictionary database location",
},
},
Action: func(cCtx *cli.Context) error {
name := cCtx.String("database")
return Run(context.Background(), name)
},
}
func Run(ctx context.Context, name string) error {
db, err := db.Open(name)
if err != nil {
return err
}
textView := tview.NewTextView().
SetDynamicColors(true).
SetRegions(true)
app := tview.NewApplication()
search := ""
tx := sync.Mutex{}
input := tview.NewInputField().
SetChangedFunc(func(v string) {
tx.Lock()
defer tx.Unlock()
search = v
go func(v string) {
words, err := db.SelectDict(ctx, v, 20)
if err != nil {
return
}
tx.Lock()
if search != v {
tx.Unlock()
return
}
tx.Unlock()
textView.Clear()
lastWord := ""
for _, w := range words {
w.Word = tview.Escape(w.Word)
w.Line = tview.Escape(w.Line)
if lastWord == w.Word {
fmt.Fprintf(textView, "%s\n", w.Line)
} else if lastWord == "" {
fmt.Fprintf(textView, "[::bu]%s[-:-:-]\n", w.Word)
fmt.Fprintf(textView, "%s\n", w.Line)
} else {
fmt.Fprintf(textView, "\n[::bu]%s[-:-:-]\n", w.Word)
fmt.Fprintf(textView, "%s\n", w.Line)
}
lastWord = w.Word
}
app.Draw()
}(v)
}).
SetAutocompleteFunc(func(v string) []string {
if len(v) == 0 {
return []string{}
}
vs, err := db.SelectSpell(ctx, v)
if err != nil {
slog.Error("Error select spelling", "error", err)
return []string{}
}
return vs
})
input.SetDoneFunc(func(key tcell.Key) {
if key == tcell.KeyEscape {
textView.Clear()
input.SetText("")
}
})
grid := tview.NewGrid().
SetRows(1, 0).
AddItem(input, 0, 0, 1, 3, 0, 0, false).
AddItem(textView, 1, 0, 1, 3, 0, 0, false)
return app.
SetRoot(grid, true).
SetFocus(input).
Run()
}
|