testfile.go 2.0 KB

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