svg.go 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. package cache
  2. import (
  3. "image"
  4. "sync"
  5. "time"
  6. )
  7. var svgs = &sync.Map{} // make(map[string]*svgInfo)
  8. // GetSvg gets svg image from cache if it exists.
  9. func GetSvg(name string, w int, h int) *image.NRGBA {
  10. sinfo, ok := svgs.Load(name)
  11. if !ok || sinfo == nil {
  12. return nil
  13. }
  14. svginfo := sinfo.(*svgInfo)
  15. if svginfo.w != w || svginfo.h != h {
  16. return nil
  17. }
  18. svginfo.setAlive()
  19. return svginfo.pix
  20. }
  21. // SetSvg sets a svg into the cache map.
  22. func SetSvg(name string, pix *image.NRGBA, w int, h int) {
  23. sinfo := &svgInfo{
  24. pix: pix,
  25. w: w,
  26. h: h,
  27. }
  28. sinfo.setAlive()
  29. svgs.Store(name, sinfo)
  30. }
  31. type svgInfo struct {
  32. // An svgInfo can be accessed from different goroutines, e.g., systray.
  33. // Use expiringCache instead of expiringCacheNoLock.
  34. expiringCache
  35. pix *image.NRGBA
  36. w, h int
  37. }
  38. // destroyExpiredSvgs destroys expired svgs cache data.
  39. func destroyExpiredSvgs(now time.Time) {
  40. expiredSvgs := make([]string, 0, 20)
  41. svgs.Range(func(key, value interface{}) bool {
  42. s, sinfo := key.(string), value.(*svgInfo)
  43. if sinfo.isExpired(now) {
  44. expiredSvgs = append(expiredSvgs, s)
  45. }
  46. return true
  47. })
  48. for _, exp := range expiredSvgs {
  49. svgs.Delete(exp)
  50. }
  51. }