-
Notifications
You must be signed in to change notification settings - Fork 17
/
closest.go
76 lines (71 loc) · 2.25 KB
/
closest.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
//go:build cgo
// +build cgo
package wallutils
import "errors"
// ClosestByResolution returns a wallpaper that is closest to the average
// monitor resolution. If several wallpapers matches, a random one is returned.
// The idea is that a slice of wallpapers in a wallpaper collection with several
// available resolutions is given as input, and a suitable wallpaper is returned.
func ClosestByResolution(wallpapers []*Wallpaper) (*Wallpaper, error) {
if len(wallpapers) == 0 {
return nil, errors.New("no wallpapers")
}
avgRes, err := AverageResolution()
if err != nil {
return nil, err
}
// map: "distance to average resolution" => wallpaper
d := make(map[int](*Wallpaper))
var dist int
var minDist int
var minDistSet bool
for _, wp := range wallpapers {
res := wp.Res()
dist = Distance(avgRes, res)
if dist < minDist || !minDistSet {
minDist = dist
minDistSet = true
}
d[dist] = wp
}
// ok, have a map, now find the filename of the smallest distance
return d[minDist], nil
}
// ClosestByResolutionInFilename takes a list of filenames on the form
// "*_WIDTHxHEIGHT.ext", where WIDTH and HEIGHT are numbers.
// The filename that is closest to the average monitor resolution is returned.
// Any filenames not following the pattern will cause an error being returned.
func ClosestByResolutionInFilename(filenames []string) (string, error) {
if len(filenames) == 0 {
return "", errors.New("no filenames")
}
avgRes, err := AverageResolution()
if err != nil {
return "", err
}
// map: (distance to average resolution) => (filename)
d := make(map[int]string)
var dist int
var minDist int
var minDistSet bool
for _, filename := range filenames {
res, err := FilenameToRes(filename)
if err != nil {
return "", err
}
dist = Distance(avgRes, res)
if dist < minDist || !minDistSet {
minDist = dist
minDistSet = true
}
// fmt.Printf("FILENAME %s HAS DISTANCE %d TO AVERAGE RESOLUTION %s\n", filename, dist, avgRes)
d[dist] = filename
}
// ok, have a map, now find the filename of the smallest distance
return d[minDist], nil
}
// Closest does the same as ClosestByResolutionInfilename.
// It is provided for backwards compatibility.
func Closest(filenames []string) (string, error) {
return ClosestByResolutionInFilename(filenames)
}