gui/window: native open and save file dialogs

ShowFileDialog (UI thread) and ChooseFile (any goroutine, waits) show a
native dialog for the window -- NSOpenPanel/NSSavePanel as a sheet on
macOS, GetOpenFileNameW/GetSaveFileNameW on Windows -- with a title, a
start folder, a suggested name and allowed extensions. It only returns
the chosen path; one dialog at a time.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
terminarandClaude Opus 5.5 committed 2026-11-27 23:41:23 +01:00
1 parent e1495430c5
commit 5d141c7cef
7 files changed
+284 -2

No files matched your search

+57
View File
@@ -219,6 +219,63 @@ func SetAppIcon(png []byte) { setAppIcon(png) }
// unknown. Safe to call before a window exists.
func AccentColor() string { return accentColor() }
// FileDialog describes a native open or save dialog.
type FileDialog struct {
Save bool // a save dialog; otherwise open one existing file
Title string // the prompt; "" for the system's
Directory string // the folder to start in; "" for the system's choice
Name string // save: the suggested file name
Extensions []string // allowed extensions without the dot ("pdf"); empty: any file
}
// ErrDialogOpen: a file dialog of this window is already open.
var ErrDialogOpen = errors.New("window: a file dialog is already open")
// fileDialoger is implemented by backends with native file dialogs.
type fileDialoger interface {
FileDialog(d FileDialog, done func(path string, err error))
}
// ShowFileDialog shows a native open or save dialog for the window (UI
// thread; one at a time). done runs on the UI thread with the chosen
// path, or "" and a nil error when the user cancelled. A save dialog
// has asked about replacing an existing file already; nothing is read
// or written here -- that is the program's choice.
func (w *Window) ShowFileDialog(d FileDialog, done func(path string, err error)) {
f, ok := w.b.(fileDialoger)
if !ok {
done("", errors.New("window: file dialogs not supported by "+w.name))
return
}
f.FileDialog(d, done)
}
// ChooseFile shows a file dialog from any goroutine and waits for the
// user: the chosen path, or "" and nil when cancelled. ctx ending (the
// request was dropped) stops the wait, not the dialog.
func (w *Window) ChooseFile(ctx context.Context, d FileDialog) (string, error) {
type result struct {
path string
err error
}
ch := make(chan result, 1)
w.mu.Lock()
alive := w.alive
w.mu.Unlock()
if !alive {
return "", errors.New("window: destroyed")
}
w.Dispatch(func() {
w.ShowFileDialog(d, func(p string, err error) { ch <- result{p, err} })
})
select {
case r := <-ch:
return r.path, r.err
case <-ctx.Done():
return "", ctx.Err()
}
}
// DroppedDispatches counts Dispatch calls that arrived after Destroy.
func (w *Window) DroppedDispatches() int {
w.mu.Lock()