resource.go 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. package fyne
  2. import (
  3. "io"
  4. "net/http"
  5. "os"
  6. "path/filepath"
  7. )
  8. // Resource represents a single binary resource, such as an image or font.
  9. // A resource has an identifying name and byte array content.
  10. // The serialised path of a resource can be obtained which may result in a
  11. // blocking filesystem write operation.
  12. type Resource interface {
  13. Name() string
  14. Content() []byte
  15. }
  16. // ThemedResource is a version of a resource that can be updated to match a certain theme colour.
  17. // The `ThemeColorName` will be used to look up the color for the current theme and colorize the resource.
  18. //
  19. // Since: 2.5
  20. type ThemedResource interface {
  21. Resource
  22. ThemeColorName() ThemeColorName
  23. }
  24. // StaticResource is a bundled resource compiled into the application.
  25. // These resources are normally generated by the fyne_bundle command included in
  26. // the Fyne toolkit.
  27. type StaticResource struct {
  28. StaticName string
  29. StaticContent []byte
  30. }
  31. // Name returns the unique name of this resource, usually matching the file it
  32. // was generated from.
  33. func (r *StaticResource) Name() string {
  34. return r.StaticName
  35. }
  36. // Content returns the bytes of the bundled resource, no compression is applied
  37. // but any compression on the resource is retained.
  38. func (r *StaticResource) Content() []byte {
  39. return r.StaticContent
  40. }
  41. // NewStaticResource returns a new static resource object with the specified
  42. // name and content. Creating a new static resource in memory results in
  43. // sharable binary data that may be serialised to the system cache location.
  44. func NewStaticResource(name string, content []byte) *StaticResource {
  45. return &StaticResource{
  46. StaticName: name,
  47. StaticContent: content,
  48. }
  49. }
  50. // LoadResourceFromPath creates a new StaticResource in memory using the contents of the specified file.
  51. func LoadResourceFromPath(path string) (Resource, error) {
  52. bytes, err := os.ReadFile(filepath.Clean(path))
  53. if err != nil {
  54. return nil, err
  55. }
  56. name := filepath.Base(path)
  57. return NewStaticResource(name, bytes), nil
  58. }
  59. // LoadResourceFromURLString creates a new StaticResource in memory using the body of the specified URL.
  60. func LoadResourceFromURLString(urlStr string) (Resource, error) {
  61. res, err := http.Get(urlStr)
  62. if err != nil {
  63. return nil, err
  64. }
  65. defer res.Body.Close()
  66. bytes, err := io.ReadAll(res.Body)
  67. if err != nil {
  68. return nil, err
  69. }
  70. name := filepath.Base(urlStr)
  71. return NewStaticResource(name, bytes), nil
  72. }