/
suggestion_adapter.go
72 lines (60 loc) · 1.55 KB
/
suggestion_adapter.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
// This is free and unencumbered software released into the public
// domain. For more information, see <http://unlicense.org> or the
// accompanying UNLICENSE file.
package suggestion
import (
"math"
"sort"
"github.com/nelsam/gxui"
"github.com/nelsam/vidar/scoring"
)
type suggestion struct {
name string
score float64
}
// Adapter is an adapter that is based on gxui's
// FilteredListAdapter and CodeSuggestionAdapter. There are some
// differences mostly revolving around displaying the suggestions.
type Adapter struct {
gxui.DefaultAdapter
pos int
suggestions []Suggestion
scores []float64
end int
}
func (a *Adapter) Set(pos int, suggestions ...Suggestion) {
if a.pos == pos {
return
}
a.pos = pos
a.suggestions = suggestions
}
func (a *Adapter) Pos() int {
return a.pos
}
func (a *Adapter) Sort(partial []rune) (longest int) {
a.scores = make([]float64, len(a.suggestions))
for i, suggestion := range a.suggestions {
a.scores[i] = scoring.Score([]rune(suggestion.Name), partial)
if a.scores[i] != math.MaxFloat64 {
longest = len([]rune(suggestion.String()))
}
}
a.end = len(a.suggestions)
sort.Sort(a)
for a.end > 0 && a.scores[a.end-1] == math.MaxFloat64 {
a.end--
}
a.SetItems(a.suggestions[:a.end])
return longest
}
func (a *Adapter) Len() int {
return a.end
}
func (a *Adapter) Less(i, j int) bool {
return a.scores[i] < a.scores[j]
}
func (a *Adapter) Swap(i, j int) {
a.suggestions[i], a.suggestions[j] = a.suggestions[j], a.suggestions[i]
a.scores[i], a.scores[j] = a.scores[j], a.scores[i]
}