-
Notifications
You must be signed in to change notification settings - Fork 5
/
widget.go
319 lines (265 loc) · 7.16 KB
/
widget.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
// Package fastcopy implements the core fastcopy functionality.
package fastcopy
import (
"fmt"
"sort"
"strings"
"sync"
"unicode"
"github.com/abhinav/tmux-fastcopy/internal/ui"
tcell "github.com/gdamore/tcell/v2"
"github.com/gdamore/tcell/v2/views"
)
// Match is a single entry matched by fastcopy.
type Match struct {
// Matcher is the name of the matcher that found this match.
Matcher string
// Range identifies the matched area.
Range Range
}
func (m Match) String() string {
return fmt.Sprintf("(%q) %v", m.Matcher, m.Range)
}
// Range specifies a range of offsets in a text, referring to the [start:end)
// subslice of the text.
type Range struct{ Start, End int }
func (r Range) String() string {
return fmt.Sprintf("[%v, %v)", r.Start, r.End)
}
// Len reports the length of this range.
func (r Range) Len() int {
return r.End - r.Start
}
// Style configures the display style of the widget.
type Style struct {
Normal tcell.Style // normal text
Match tcell.Style // matched text
SkippedMatch tcell.Style // matched text that is not selected
HintLabel tcell.Style // labels for hints
HintLabelInput tcell.Style // typed portion of hints
// Multi-select mode:
SelectedMatch tcell.Style // one of the selected matches
DeselectLabel tcell.Style // label for deselection
}
// Selection is a choice made by the user in the fastcopy UI.
type Selection struct {
// Text is the matched text.
Text string
// Matchers is a list of names of matchers that matched this text.
// Invariant: this list contains at least one item.
Matchers []string
// Shift reports whether shift was pressed when this value was
// selected.
Shift bool
}
// Handler handles events from the widget.
type Handler interface {
// HandleSelection reports the hint label and the corresponding matched
// text.
HandleSelection(Selection)
}
//go:generate mockgen -destination mock_handler_test.go -package fastcopy github.com/abhinav/tmux-fastcopy/internal/fastcopy Handler
// WidgetConfig configures the fastcopy widget.
type WidgetConfig struct {
// Text to display on the widget.
Text string
// Matched offsets in text.
Matches []Match
// Alphabet we'll use to generate labels.
HintAlphabet []rune
// Handler handles events from the widget. This includes hint
// selection.
Handler Handler
// Style configures the look of the widget.
Style Style
// Internal override for generateHints.
generateHints func([]rune, string, []Match) []hint
}
// Widget is the main fastcopy widget. It displays some fixed text with zero or
// more hints and unique prefix-free labels next to each hint to select that
// label.
type Widget struct {
style Style
handler Handler
textw *ui.AnnotatedText
hints []hint
hintsByLabel map[string]int // label -> hints[i]
// Mutable attributes:
mu sync.RWMutex
input string // text input so far
shiftDown bool // whether shift was pressed
multiSelect bool // whether in multi select mode
}
// Build builds a new Fastcopy widget using the provided configuration.
func (cfg *WidgetConfig) Build() *Widget {
generateHints := generateHints
if cfg.generateHints != nil {
generateHints = cfg.generateHints
}
hints := generateHints(cfg.HintAlphabet, cfg.Text, cfg.Matches)
byLabel := make(map[string]int, len(hints))
for i, hint := range hints {
byLabel[hint.Label] = i
}
w := &Widget{
textw: &ui.AnnotatedText{
Text: cfg.Text,
Style: cfg.Style.Normal,
},
style: cfg.Style,
handler: cfg.Handler,
hints: hints,
hintsByLabel: byLabel,
}
w.annotateText()
return w
}
// Draw draws the widget onto the provided view.
func (w *Widget) Draw(view views.View) {
w.textw.Draw(view)
}
// Input reports the text input into the label so far to partially select a
// label.
func (w *Widget) Input() string {
w.mu.RLock()
defer w.mu.RUnlock()
return w.input
}
// HandleEvent handles input for the widget. This only responds to text input,
// and delegates everything else to the caller.
func (w *Widget) HandleEvent(ev tcell.Event) (handled bool) {
ek, ok := ev.(*tcell.EventKey)
if !ok {
return false
}
switch ek.Key() {
case tcell.KeyBackspace, tcell.KeyBackspace2:
handled = true
w.mu.Lock()
if n := len(w.input); n > 0 {
w.input = w.input[:n-1]
defer w.inputChanged()
}
w.mu.Unlock()
case tcell.KeyTab:
handled = true
if !w.multiSelect {
w.multiSelect = true
} else {
w.multiSelect = false
w.handleSelection()
}
case tcell.KeyEnter:
// In multi-select mode, <enter>
// always confirms the current selection.
if w.multiSelect {
handled = true
w.handleSelection()
}
case tcell.KeyRune:
handled = true
w.mu.Lock()
r := ek.Rune()
// Per the documentation of EventKey, it may report the rune
// 'A' without the ModShift modifier set.
if unicode.IsUpper(r) {
r = unicode.ToLower(r)
w.shiftDown = true
} else {
w.shiftDown = ek.Modifiers()&tcell.ModShift != 0
}
w.input += string(r)
defer w.inputChanged()
w.mu.Unlock()
}
return handled
}
func (w *Widget) inputChanged() {
// We use prefix-free hint labels, so if a label matches the input
// exactly, we have a guarantee that this is a match.
defer w.annotateText()
w.mu.Lock()
idx, ok := w.hintsByLabel[w.input]
if ok {
h := w.hints[idx]
h.Selected = !h.Selected // toggle selection
w.hints[idx] = h
// Clear the input to allow for more selections
// if we're in multi-select mode.
w.input = ""
}
w.mu.Unlock()
// If we're not in multi-select mode,
// we can report the selection immediately.
if ok && !w.multiSelect {
w.handleSelection()
}
}
func (w *Widget) handleSelection() {
matchers := make(map[string]struct{})
var (
text strings.Builder
count int
)
for idx, h := range w.hints {
if !h.Selected {
continue
}
if count > 0 {
text.WriteString(" ")
}
count++
text.WriteString(h.Text)
for _, m := range h.Matches {
matchers[m.Matcher] = struct{}{}
}
// Deselect the hint in the widget
// in case we want to select it again.
//
// This typically won't happen because HandleSelection upstream
// will exit the UI loop,
// but there's no guarantee of that for the Widget interface.
h.Selected = false
w.hints[idx] = h
}
if count == 0 {
// There were no matches selected.
// This is a no-op.
return
}
sel := Selection{
Text: text.String(),
Shift: w.shiftDown,
}
for m := range matchers {
sel.Matchers = append(sel.Matchers, m)
}
sort.Strings(sel.Matchers)
w.handler.HandleSelection(sel)
}
func (w *Widget) annotateText() {
w.mu.Lock()
defer w.mu.Unlock()
var anns []ui.TextAnnotation
for _, hint := range w.hints {
input := w.input
style := AnnotationStyle{
Match: w.style.Match,
Skipped: w.style.SkippedMatch,
Label: w.style.HintLabel,
LabelTyped: w.style.HintLabelInput,
}
if hint.Selected {
// If this hint is selected, we're in multi-select mode,
// and we want to allow deselection.
//
// Pretend there's no input,
// and use the DeselectLabel style for hints.
input = ""
style.Match = w.style.SelectedMatch
style.Label = w.style.DeselectLabel
}
anns = append(anns, hint.Annotations(input, style)...)
}
w.textw.SetAnnotations(anns...)
}