diff --git a/dialog/file.go b/dialog/file.go index 2ad8e27163..4596bb2e14 100644 --- a/dialog/file.go +++ b/dialog/file.go @@ -262,6 +262,35 @@ func (f *fileDialog) setSelected(file *fileDialogItem) { } } +// effectiveStartingDir calculates the directory at which the file dialog +// should open, based on the values of CWD, home, and any error conditions +// which occur. +// +// Order of precedence is: +// +// * os.Getwd() +// * os.UserHomeDir() +// * "/" (should be filesystem root on all supported platforms) +func (f *FileDialog) effectiveStartingDir() string { + + // Try to use CWD + var err error = nil + dir, err := os.Getwd() + if err == nil { + return dir + } + fyne.LogError("Could not load CWD", err) + + // fail over to home dir + dir, err = os.UserHomeDir() + if err == nil { + return dir + } + fyne.LogError("Could not load user home dir", err) + + return "/" +} + func showFile(file *FileDialog) *fileDialog { d := &fileDialog{file: file} ui := d.makeUI() diff --git a/dialog/file_test.go b/dialog/file_test.go index 174b93eb4d..68083d483d 100644 --- a/dialog/file_test.go +++ b/dialog/file_test.go @@ -15,6 +15,51 @@ import ( "fyne.io/fyne/widget" ) +// comparePaths compares if two file paths point to the same thing, and calls +// t.Fatalf() if there is an error in performing the comparison. +// +// Returns true of both paths point to the same thing. +// +// You should use this if you need to compare file paths, since it explicitly +// normalizes the paths to a stable canonical form. It also nicely +// abstracts out the requisite error handling. +// +// You should only call this function on paths that you expect to be valid. +func comparePaths(t *testing.T, p1, p2 string) bool { + a1, err := filepath.Abs(p1) + if err != nil { + t.Fatalf("Failed to normalize path '%s'", p1) + } + + a2, err := filepath.Abs(p2) + if err != nil { + t.Fatalf("Failed to normalize path '%s'", p2) + } + + return a1 == a2 +} + +func TestEffectiveStartingDir(t *testing.T) { + wd, err := os.Getwd() + if err != nil { + t.Skipf("os.Getwd() failed, cannot run this test on this system (error getting ./), error was '%s'", err) + } + + dialog := &FileDialog{} + + // test that we get ./ when running with the default struct values + res := dialog.effectiveStartingDir() + expect := wd + if err != nil { + t.Skipf("os.Getwd() failed, cannot run this test on this system, error was '%s'", err) + } + if !comparePaths(t, res, expect) { + t.Errorf("Expected effectiveStartingDir() to be '%s', but it was '%s'", + expect, res) + } + +} + func TestShowFileOpen(t *testing.T) { var chosen fyne.URIReadCloser var openErr error