testfile.go 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103
  1. package test
  2. import (
  3. "fmt"
  4. "io"
  5. "os"
  6. "path/filepath"
  7. "fyne.io/fyne/v2"
  8. "fyne.io/fyne/v2/storage"
  9. )
  10. type file struct {
  11. *os.File
  12. path string
  13. }
  14. type directory struct {
  15. fyne.URI
  16. }
  17. // Declare conformity to the ListableURI interface
  18. var _ fyne.ListableURI = (*directory)(nil)
  19. func (f *file) Open() (io.ReadCloser, error) {
  20. return os.Open(f.path)
  21. }
  22. func (f *file) Save() (io.WriteCloser, error) {
  23. return os.Open(f.path)
  24. }
  25. func (f *file) ReadOnly() bool {
  26. return true
  27. }
  28. func (f *file) Name() string {
  29. return filepath.Base(f.path)
  30. }
  31. func (f *file) URI() fyne.URI {
  32. return storage.NewFileURI(f.path)
  33. }
  34. func openFile(uri fyne.URI, create bool) (*file, error) {
  35. if uri.Scheme() != "file" {
  36. return nil, fmt.Errorf("unsupported URL protocol")
  37. }
  38. path := uri.String()[7:]
  39. f, err := os.Open(path)
  40. if err != nil && create {
  41. f, err = os.Create(path)
  42. }
  43. return &file{File: f, path: path}, err
  44. }
  45. func (d *testDriver) FileReaderForURI(uri fyne.URI) (fyne.URIReadCloser, error) {
  46. return openFile(uri, false)
  47. }
  48. func (d *testDriver) FileWriterForURI(uri fyne.URI) (fyne.URIWriteCloser, error) {
  49. return openFile(uri, true)
  50. }
  51. func (d *testDriver) ListerForURI(uri fyne.URI) (fyne.ListableURI, error) {
  52. if uri.Scheme() != "file" {
  53. return nil, fmt.Errorf("unsupported URL protocol")
  54. }
  55. path := uri.String()[len(uri.Scheme())+3 : len(uri.String())]
  56. s, err := os.Stat(path)
  57. if err != nil {
  58. return nil, err
  59. }
  60. if !s.IsDir() {
  61. return nil, fmt.Errorf("path '%s' is not a directory, cannot convert to listable URI", path)
  62. }
  63. return &directory{URI: uri}, nil
  64. }
  65. func (d *directory) List() ([]fyne.URI, error) {
  66. if d.Scheme() != "file" {
  67. return nil, fmt.Errorf("unsupported URL protocol")
  68. }
  69. path := d.String()[len(d.Scheme())+3 : len(d.String())]
  70. files, err := os.ReadDir(path)
  71. if err != nil {
  72. return nil, err
  73. }
  74. urilist := []fyne.URI{}
  75. for _, f := range files {
  76. uri := storage.NewFileURI(filepath.Join(path, f.Name()))
  77. urilist = append(urilist, uri)
  78. }
  79. return urilist, nil
  80. }