Files: native open & save pickers

A file picker lets people choose a file to open or a location for saving their work. The system’s browsing interface connects that choice to the files and storage locations available on the device.

Day uses each platform’s native file picker. As with dialogs, an action opens the picker and awaits its result:

button(res::str::open()).action(move || {
    day::task(async move {
        if let Some(file) = open_file()
            .filter(res::str::text_files().format(), &["txt", "md"])
            .await
        {
            // `day::task` takes a `Future<Output = ()>`, so handle the error here
            // rather than reaching for `?`.
            match file.read_to_string() {
                // FileUrl::read_to_string
                Ok(text) => editor.set(text),
                Err(e) => status.set(res::str::operation_failed(e.to_string()).format()),
            }
        }
    });
});

button(res::str::save()).action(move || {
    day::task(async move {
        let saved: Option<FileUrl> = save_file(editor.get_untracked().into_bytes())
            .suggested_name("notes.txt")
            .filter(res::str::text_files().format(), &["txt"])
            .await;
    });
});

For OS file associations, Finder/Dock drops, and cold/warm document delivery, see Document types and file activation. Use FileUrl::read_limited(limit).await for bounded reads that do not block the native UI thread.

The UI snippets use generated res::str accessors from an app’s Fluent catalog; see the example messages and catalog setup.

The path type: FileUrl

A file location crosses back as a FileUrl, a newtype wrapping a single locator string. Each platform hands back a different kind of locator, and the type stores whichever arrives:

  • A string, because of Android: the Storage Access Framework returns a content:// URI rather than a filesystem path; a std::path::PathBuf cannot represent it and std::fs cannot open it.
  • A newtype, for one parser: the accessors below live in one place instead of at every call site.
  • Stored verbatim: url::Url normalizes and validates in ways that mangle content:// authorities, and it would add a large dependency, so the locator is kept as received.

FileUrl is the lossless union (a filesystem path on desktop/iOS, a content:// URI on Android) with accessors:

methodresult
as_str()the raw locator
local_path() -> Option<PathBuf>Some for filesystem paths (and file://), None for content://
file_name() -> Option<String>the last path component, for display
read() / read_to_string()the bytes / UTF-8 text (local paths; content:// errors)

Opened files are always readable. Where a platform doesn’t hand back a usable path, the toolkit materializes one first: Android copies the picked document into the app cache, and iOS imports it into the app sandbox. So open_file().await?.read_to_string() works on every target.

The builders (day-pieces, in the prelude)

  • open_file() → OpenFile: .title(..), .filter(name, &["ext", …]), .await → Option<FileUrl>.
  • open_files() → OpenFiles: the same .title(..) and .filter(..), .await → Vec<FileUrl>: every file the user picked, in the picker’s order, and an empty Vec on cancel. The picker allows a multiple selection; a toolkit without one still answers with the single pick.
  • open_folder() → OpenFolder: .title(..), .await → Option<FileUrl>: the chosen directory, or None on cancel. Only toolkits that answer Cap::FolderDialog as Native show a chooser; the others resolve None at once, so an app checks the capability before offering an “Add Folder…” command (the phones answer Unsupported).
  • save_file(data) → SaveFile: .title(..), .suggested_name(..), .filter(..), .await → Option<FileUrl>. The bytes are staged to an app-writable temp file that the toolkit hands to the native save UI; the pieces layer delivers them to a chosen local destination and cleans up.
// A music library's "Add Files…" and "Add Folder…" commands.
let tracks: Vec<FileUrl> = open_files()
    .filter(res::str::audio_files().format(), &["mp3", "flac", "m4a"])
    .await;

// Ask `capability(Cap::FolderDialog)` before offering the command (docs/cover.md shows the
// same probe for the status bar); phones answer `Unsupported`.
if capability(Cap::FolderDialog) == Support::Native
    && let Some(folder) = open_folder().title(res::str::add_folder().format()).await
{
    scan(folder.local_path());
}

Both probes and the enums are in the prelude (capability, Cap, Support).

Toolkit implementations

Platform guidance: Apple: file management; Android: accessing shared documents.

ToolkitOpen (one or several)FolderSave
appkitNSOpenPanel (sheet; allowsMultipleSelection, every URLs entry reported)NSOpenPanel with canChooseDirectoriesNSSavePanel (sheet)
uikitUIDocumentPickerViewController (.import; allowsMultipleSelection, each pick copied into the sandbox)none: resolves NoneUIDocumentPickerViewController (export)
gtkGtkFileDialog.open / open_multiple (GTK 4.10+)GtkFileDialog.select_folderGtkFileDialog.save
qtQFileDialog (ExistingFile / ExistingFiles) via the C++ shimQFileDialog (Directory + ShowDirsOnly)QFileDialog (AnyFile/AcceptSave)
androidACTION_OPEN_DOCUMENT (+ EXTRA_ALLOW_MULTIPLE, every ClipData item) + ContentResolver (copy → cache)none: resolves NoneACTION_CREATE_DOCUMENT + ContentResolver
arkui (HarmonyOS)ArkTS DocumentViewPicker.select (maxSelectNumber for several) + @ohos.file.fs (copy → cache)none: resolves NoneDocumentViewPicker.save + @ohos.file.fs
dom (web)<input type=file> (multiple for several; the browser’s picker)none: resolves Nonea Blob download
mockrecords the spec; resolved programmaticallysamesame
WinUIWinRT FileOpenPicker (PickSingleFileAsync / PickMultipleFilesAsync)WinRT FolderPickerWinRT FileSavePicker

Cap::FolderDialog is Native exactly where the Folder column names a chooser: the four desktops. The phone and web toolkits answer Unsupported and resolve an open_folder() request as cancelled at once, so the await never hangs; an app that offers “Add Folder…” asks the capability first and hides the command elsewhere.

On HarmonyOS the picker lives in the ArkTS @kit.CoreFileKit layer, not the native NodeAPI, so the day-toolkit-arkui toolkit calls up into its ArkTS host over NAPI (safe: Day’s loop runs on the JS thread); the host drives DocumentViewPicker and answers via a registered onFileResult callback, wired in the framework’s ArkTS host page (crates/day-toolkit-arkui/platform/harmony/ets/Index.ets, staged into every app’s hvigor project by day build — docs/harmonyos).

A browser has no filesystem, so on Web the bytes ride a per-page store instead of paths: an opened file’s content lands under a virtual /day-web/<name> path that FileUrl::read resolves, and a save’s staged bytes leave as a download named by suggested_name. The app uses the same builders and the same FileUrl surface on web as on every other target.

All toolkits present the picker non-blocking (sheet / open() / delegate / Activity result), so the main loop keeps running and dayscript stays live while a picker is up.

Windows picker behavior

The WinUI toolkit advertises Cap::FileDialogs = Native and Cap::FolderDialog = Native. It uses the system WinRT pickers (FileOpenPicker, FolderPicker, FileSavePicker), initialized with the host HWND through IInitializeWithWindow (the desktop picker interop contract). Open filters become .ext entries, with * when no filters are supplied (the folder picker always carries *, which the desktop requires); save filters retain their names. The WinRT API does not expose a custom dialog title. A several-files pick goes through PickMultipleFilesAsync and reports every chosen path. The selected local path becomes a FileUrl, so read() returns the original bytes.

Registration precedes native setup. Missing owners, activation/filter/initialization failures, canceled operations, and errors retrieving the result or path resolve as Dismissed, rather than leaving the calling future pending. Completion removes the registration before notifying Rust; duplicate or late replies are ignored.

Validate on a Windows host with Day-Showcase/dayscript/files.yaml, then manually open and cancel the native picker and select a file with a Unicode path. In Day-Sketch, insert an image through the + menu, edit its geometry/opacity/rotation, save the drawing, and reopen it. Scripted respond validates the portable presentation flow; it does not select a file through the real Windows picker UI.

macOS sandboxing

See macOS App Sandbox for Day.toml configuration and persistent file access. FileUrl::bookmark(read_only) returns opaque bookmark bytes; FileUrl::resolve_bookmark(bytes) returns a FileAccess guard. Keep it alive through I/O and renew stale bookmarks while the guard is held. A saved path alone does not preserve permission.