forked from fyne-io/fyne
/
svg_cache.go
93 lines (80 loc) · 1.55 KB
/
svg_cache.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
package gl
import (
"image"
"os"
"sync"
"time"
"fyne.io/fyne"
)
type rasterInfo struct {
pix *image.RGBA
w, h int
expires time.Time
}
var cacheDuration = (time.Minute * 5)
var rasters = make(map[fyne.Resource]*rasterInfo)
var rasterMutex sync.RWMutex
var janitorOnce sync.Once
func init() {
if t, err := time.ParseDuration(os.Getenv("FYNE_CACHE")); err == nil {
cacheDuration = t
}
svgCacheJanitor()
}
func svgCacheJanitor() {
delay := cacheDuration / 2
if delay < time.Second {
delay = time.Second
}
go janitorOnce.Do(func() {
for {
time.Sleep(delay)
now := time.Now()
rasterMutex.Lock()
for k, v := range rasters {
if v.expires.Before(now) {
delete(rasters, k)
}
}
rasterMutex.Unlock()
}
})
}
func svgCacheGet(res fyne.Resource, w int, h int) *image.RGBA {
rasterMutex.RLock()
defer rasterMutex.RUnlock()
v, ok := rasters[res]
if !ok || v == nil || v.w != w || v.h != h {
return nil
}
v.expires = time.Now().Add(cacheDuration)
return v.pix
}
func svgCachePut(res fyne.Resource, pix *image.RGBA, w int, h int) {
rasterMutex.Lock()
defer rasterMutex.Unlock()
defer recover()
rasters[res] = &rasterInfo{
pix: pix,
w: w,
h: h,
expires: time.Now().Add(cacheDuration),
}
}
func svgCacheReset() {
rasterMutex.Lock()
for k := range rasters {
delete(rasters, k)
}
rasterMutex.Unlock()
}
func svgCacheMonitorTheme() {
listener := make(chan fyne.Settings)
fyne.CurrentApp().Settings().AddChangeListener(listener)
go func() {
for {
<-listener
svgCacheReset()
}
}()
}